]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winmisc.c
11e2ca0f7d1353b46db523ca2d66f48b8ba85ad6
[PuTTY.git] / windows / winmisc.c
1 /*
2  * winmisc.c: miscellaneous Windows-specific things
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "putty.h"
8 #ifndef SECURITY_WIN32
9 #define SECURITY_WIN32
10 #endif
11 #include <security.h>
12
13 OSVERSIONINFO osVersion;
14
15 char *platform_get_x_display(void) {
16     /* We may as well check for DISPLAY in case it's useful. */
17     return dupstr(getenv("DISPLAY"));
18 }
19
20 Filename *filename_from_str(const char *str)
21 {
22     Filename *ret = snew(Filename);
23     ret->path = dupstr(str);
24     return ret;
25 }
26
27 Filename *filename_copy(const Filename *fn)
28 {
29     return filename_from_str(fn->path);
30 }
31
32 const char *filename_to_str(const Filename *fn)
33 {
34     return fn->path;
35 }
36
37 int filename_equal(const Filename *f1, const Filename *f2)
38 {
39     return !strcmp(f1->path, f2->path);
40 }
41
42 int filename_is_null(const Filename *fn)
43 {
44     return !*fn->path;
45 }
46
47 void filename_free(Filename *fn)
48 {
49     sfree(fn->path);
50     sfree(fn);
51 }
52
53 int filename_serialise(const Filename *f, void *vdata)
54 {
55     char *data = (char *)vdata;
56     int len = strlen(f->path) + 1;     /* include trailing NUL */
57     if (data) {
58         strcpy(data, f->path);
59     }
60     return len;
61 }
62 Filename *filename_deserialise(void *vdata, int maxsize, int *used)
63 {
64     char *data = (char *)vdata;
65     char *end;
66     end = memchr(data, '\0', maxsize);
67     if (!end)
68         return NULL;
69     end++;
70     *used = end - data;
71     return filename_from_str(data);
72 }
73
74 char filename_char_sanitise(char c)
75 {
76     if (strchr("<>:\"/\\|?*", c))
77         return '.';
78     return c;
79 }
80
81 #ifndef NO_SECUREZEROMEMORY
82 /*
83  * Windows implementation of smemclr (see misc.c) using SecureZeroMemory.
84  */
85 void smemclr(void *b, size_t n) {
86     if (b && n > 0)
87         SecureZeroMemory(b, n);
88 }
89 #endif
90
91 char *get_username(void)
92 {
93     DWORD namelen;
94     char *user;
95     int got_username = FALSE;
96     DECL_WINDOWS_FUNCTION(static, BOOLEAN, GetUserNameExA,
97                           (EXTENDED_NAME_FORMAT, LPSTR, PULONG));
98
99     {
100         static int tried_usernameex = FALSE;
101         if (!tried_usernameex) {
102             /* Not available on Win9x, so load dynamically */
103             HMODULE secur32 = load_system32_dll("secur32.dll");
104             GET_WINDOWS_FUNCTION(secur32, GetUserNameExA);
105             tried_usernameex = TRUE;
106         }
107     }
108
109     if (p_GetUserNameExA) {
110         /*
111          * If available, use the principal -- this avoids the problem
112          * that the local username is case-insensitive but Kerberos
113          * usernames are case-sensitive.
114          */
115
116         /* Get the length */
117         namelen = 0;
118         (void) p_GetUserNameExA(NameUserPrincipal, NULL, &namelen);
119
120         user = snewn(namelen, char);
121         got_username = p_GetUserNameExA(NameUserPrincipal, user, &namelen);
122         if (got_username) {
123             char *p = strchr(user, '@');
124             if (p) *p = 0;
125         } else {
126             sfree(user);
127         }
128     }
129
130     if (!got_username) {
131         /* Fall back to local user name */
132         namelen = 0;
133         if (GetUserName(NULL, &namelen) == FALSE) {
134             /*
135              * Apparently this doesn't work at least on Windows XP SP2.
136              * Thus assume a maximum of 256. It will fail again if it
137              * doesn't fit.
138              */
139             namelen = 256;
140         }
141
142         user = snewn(namelen, char);
143         got_username = GetUserName(user, &namelen);
144         if (!got_username) {
145             sfree(user);
146         }
147     }
148
149     return got_username ? user : NULL;
150 }
151
152 void dll_hijacking_protection(void)
153 {
154     /*
155      * If the OS provides it, call SetDefaultDllDirectories() to
156      * prevent DLLs from being loaded from the directory containing
157      * our own binary, and instead only load from system32.
158      *
159      * This is a protection against hijacking attacks, if someone runs
160      * PuTTY directly from their web browser's download directory
161      * having previously been enticed into clicking on an unwise link
162      * that downloaded a malicious DLL to the same directory under one
163      * of various magic names that seem to be things that standard
164      * Windows DLLs delegate to.
165      *
166      * It shouldn't break deliberate loading of user-provided DLLs
167      * such as GSSAPI providers, because those are specified by their
168      * full pathname by the user-provided configuration.
169      */
170     static HMODULE kernel32_module;
171     DECL_WINDOWS_FUNCTION(static, BOOL, SetDefaultDllDirectories, (DWORD));
172
173     if (!kernel32_module) {
174         kernel32_module = load_system32_dll("kernel32.dll");
175         GET_WINDOWS_FUNCTION(kernel32_module, SetDefaultDllDirectories);
176     }
177
178     if (p_SetDefaultDllDirectories) {
179         /* LOAD_LIBRARY_SEARCH_SYSTEM32 only */
180         p_SetDefaultDllDirectories(0x800);
181     }
182 }
183
184 BOOL init_winver(void)
185 {
186     ZeroMemory(&osVersion, sizeof(osVersion));
187     osVersion.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
188     return GetVersionEx ( (OSVERSIONINFO *) &osVersion);
189 }
190
191 HMODULE load_system32_dll(const char *libname)
192 {
193     /*
194      * Wrapper function to load a DLL out of c:\windows\system32
195      * without going through the full DLL search path. (Hence no
196      * attack is possible by placing a substitute DLL earlier on that
197      * path.)
198      */
199     static char *sysdir = NULL;
200     char *fullpath;
201     HMODULE ret;
202
203     if (!sysdir) {
204         int size = 0, len;
205         do {
206             size = 3*size/2 + 512;
207             sysdir = sresize(sysdir, size, char);
208             len = GetSystemDirectory(sysdir, size);
209         } while (len >= size);
210     }
211
212     fullpath = dupcat(sysdir, "\\", libname, NULL);
213     ret = LoadLibrary(fullpath);
214     sfree(fullpath);
215     return ret;
216 }
217
218 /*
219  * A tree234 containing mappings from system error codes to strings.
220  */
221
222 struct errstring {
223     int error;
224     char *text;
225 };
226
227 static int errstring_find(void *av, void *bv)
228 {
229     int *a = (int *)av;
230     struct errstring *b = (struct errstring *)bv;
231     if (*a < b->error)
232         return -1;
233     if (*a > b->error)
234         return +1;
235     return 0;
236 }
237 static int errstring_compare(void *av, void *bv)
238 {
239     struct errstring *a = (struct errstring *)av;
240     return errstring_find(&a->error, bv);
241 }
242
243 static tree234 *errstrings = NULL;
244
245 const char *win_strerror(int error)
246 {
247     struct errstring *es;
248
249     if (!errstrings)
250         errstrings = newtree234(errstring_compare);
251
252     es = find234(errstrings, &error, errstring_find);
253
254     if (!es) {
255         char msgtext[65536]; /* maximum size for FormatMessage is 64K */
256
257         es = snew(struct errstring);
258         es->error = error;
259         if (!FormatMessage((FORMAT_MESSAGE_FROM_SYSTEM |
260                             FORMAT_MESSAGE_IGNORE_INSERTS), NULL, error,
261                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
262                            msgtext, lenof(msgtext)-1, NULL)) {
263             sprintf(msgtext,
264                     "(unable to format: FormatMessage returned %u)",
265                     (unsigned int)GetLastError());
266         } else {
267             int len = strlen(msgtext);
268             if (len > 0 && msgtext[len-1] == '\n')
269                 msgtext[len-1] = '\0';
270         }
271         es->text = dupprintf("Error %d: %s", error, msgtext);
272         add234(errstrings, es);
273     }
274
275     return es->text;
276 }
277
278 #ifdef DEBUG
279 static FILE *debug_fp = NULL;
280 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
281 static int debug_got_console = 0;
282
283 void dputs(const char *buf)
284 {
285     DWORD dw;
286
287     if (!debug_got_console) {
288         if (AllocConsole()) {
289             debug_got_console = 1;
290             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
291         }
292     }
293     if (!debug_fp) {
294         debug_fp = fopen("debug.log", "w");
295     }
296
297     if (debug_hdl != INVALID_HANDLE_VALUE) {
298         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
299     }
300     fputs(buf, debug_fp);
301     fflush(debug_fp);
302 }
303 #endif
304
305 #ifdef MINEFIELD
306 /*
307  * Minefield - a Windows equivalent for Electric Fence
308  */
309
310 #define PAGESIZE 4096
311
312 /*
313  * Design:
314  * 
315  * We start by reserving as much virtual address space as Windows
316  * will sensibly (or not sensibly) let us have. We flag it all as
317  * invalid memory.
318  * 
319  * Any allocation attempt is satisfied by committing one or more
320  * pages, with an uncommitted page on either side. The returned
321  * memory region is jammed up against the _end_ of the pages.
322  * 
323  * Freeing anything causes instantaneous decommitment of the pages
324  * involved, so stale pointers are caught as soon as possible.
325  */
326
327 static int minefield_initialised = 0;
328 static void *minefield_region = NULL;
329 static long minefield_size = 0;
330 static long minefield_npages = 0;
331 static long minefield_curpos = 0;
332 static unsigned short *minefield_admin = NULL;
333 static void *minefield_pages = NULL;
334
335 static void minefield_admin_hide(int hide)
336 {
337     int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
338     VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
339 }
340
341 static void minefield_init(void)
342 {
343     int size;
344     int admin_size;
345     int i;
346
347     for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
348         minefield_region = VirtualAlloc(NULL, size,
349                                         MEM_RESERVE, PAGE_NOACCESS);
350         if (minefield_region)
351             break;
352     }
353     minefield_size = size;
354
355     /*
356      * Firstly, allocate a section of that to be the admin block.
357      * We'll need a two-byte field for each page.
358      */
359     minefield_admin = minefield_region;
360     minefield_npages = minefield_size / PAGESIZE;
361     admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
362     minefield_npages = (minefield_size - admin_size) / PAGESIZE;
363     minefield_pages = (char *) minefield_region + admin_size;
364
365     /*
366      * Commit the admin region.
367      */
368     VirtualAlloc(minefield_admin, minefield_npages * 2,
369                  MEM_COMMIT, PAGE_READWRITE);
370
371     /*
372      * Mark all pages as unused (0xFFFF).
373      */
374     for (i = 0; i < minefield_npages; i++)
375         minefield_admin[i] = 0xFFFF;
376
377     /*
378      * Hide the admin region.
379      */
380     minefield_admin_hide(1);
381
382     minefield_initialised = 1;
383 }
384
385 static void minefield_bomb(void)
386 {
387     div(1, *(int *) minefield_pages);
388 }
389
390 static void *minefield_alloc(int size)
391 {
392     int npages;
393     int pos, lim, region_end, region_start;
394     int start;
395     int i;
396
397     npages = (size + PAGESIZE - 1) / PAGESIZE;
398
399     minefield_admin_hide(0);
400
401     /*
402      * Search from current position until we find a contiguous
403      * bunch of npages+2 unused pages.
404      */
405     pos = minefield_curpos;
406     lim = minefield_npages;
407     while (1) {
408         /* Skip over used pages. */
409         while (pos < lim && minefield_admin[pos] != 0xFFFF)
410             pos++;
411         /* Count unused pages. */
412         start = pos;
413         while (pos < lim && pos - start < npages + 2 &&
414                minefield_admin[pos] == 0xFFFF)
415             pos++;
416         if (pos - start == npages + 2)
417             break;
418         /* If we've reached the limit, reset the limit or stop. */
419         if (pos >= lim) {
420             if (lim == minefield_npages) {
421                 /* go round and start again at zero */
422                 lim = minefield_curpos;
423                 pos = 0;
424             } else {
425                 minefield_admin_hide(1);
426                 return NULL;
427             }
428         }
429     }
430
431     minefield_curpos = pos - 1;
432
433     /*
434      * We have npages+2 unused pages starting at start. We leave
435      * the first and last of these alone and use the rest.
436      */
437     region_end = (start + npages + 1) * PAGESIZE;
438     region_start = region_end - size;
439     /* FIXME: could align here if we wanted */
440
441     /*
442      * Update the admin region.
443      */
444     for (i = start + 2; i < start + npages + 1; i++)
445         minefield_admin[i] = 0xFFFE;   /* used but no region starts here */
446     minefield_admin[start + 1] = region_start % PAGESIZE;
447
448     minefield_admin_hide(1);
449
450     VirtualAlloc((char *) minefield_pages + region_start, size,
451                  MEM_COMMIT, PAGE_READWRITE);
452     return (char *) minefield_pages + region_start;
453 }
454
455 static void minefield_free(void *ptr)
456 {
457     int region_start, i, j;
458
459     minefield_admin_hide(0);
460
461     region_start = (char *) ptr - (char *) minefield_pages;
462     i = region_start / PAGESIZE;
463     if (i < 0 || i >= minefield_npages ||
464         minefield_admin[i] != region_start % PAGESIZE)
465         minefield_bomb();
466     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
467         minefield_admin[j] = 0xFFFF;
468     }
469
470     VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
471
472     minefield_admin_hide(1);
473 }
474
475 static int minefield_get_size(void *ptr)
476 {
477     int region_start, i, j;
478
479     minefield_admin_hide(0);
480
481     region_start = (char *) ptr - (char *) minefield_pages;
482     i = region_start / PAGESIZE;
483     if (i < 0 || i >= minefield_npages ||
484         minefield_admin[i] != region_start % PAGESIZE)
485         minefield_bomb();
486     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
487
488     minefield_admin_hide(1);
489
490     return j * PAGESIZE - region_start;
491 }
492
493 void *minefield_c_malloc(size_t size)
494 {
495     if (!minefield_initialised)
496         minefield_init();
497     return minefield_alloc(size);
498 }
499
500 void minefield_c_free(void *p)
501 {
502     if (!minefield_initialised)
503         minefield_init();
504     minefield_free(p);
505 }
506
507 /*
508  * realloc _always_ moves the chunk, for rapid detection of code
509  * that assumes it won't.
510  */
511 void *minefield_c_realloc(void *p, size_t size)
512 {
513     size_t oldsize;
514     void *q;
515     if (!minefield_initialised)
516         minefield_init();
517     q = minefield_alloc(size);
518     oldsize = minefield_get_size(p);
519     memcpy(q, p, (oldsize < size ? oldsize : size));
520     minefield_free(p);
521     return q;
522 }
523
524 #endif                          /* MINEFIELD */
525
526 FontSpec *fontspec_new(const char *name,
527                         int bold, int height, int charset)
528 {
529     FontSpec *f = snew(FontSpec);
530     f->name = dupstr(name);
531     f->isbold = bold;
532     f->height = height;
533     f->charset = charset;
534     return f;
535 }
536 FontSpec *fontspec_copy(const FontSpec *f)
537 {
538     return fontspec_new(f->name, f->isbold, f->height, f->charset);
539 }
540 void fontspec_free(FontSpec *f)
541 {
542     sfree(f->name);
543     sfree(f);
544 }
545 int fontspec_serialise(FontSpec *f, void *vdata)
546 {
547     char *data = (char *)vdata;
548     int len = strlen(f->name) + 1;     /* include trailing NUL */
549     if (data) {
550         strcpy(data, f->name);
551         PUT_32BIT_MSB_FIRST(data + len, f->isbold);
552         PUT_32BIT_MSB_FIRST(data + len + 4, f->height);
553         PUT_32BIT_MSB_FIRST(data + len + 8, f->charset);
554     }
555     return len + 12;                   /* also include three 4-byte ints */
556 }
557 FontSpec *fontspec_deserialise(void *vdata, int maxsize, int *used)
558 {
559     char *data = (char *)vdata;
560     char *end;
561     if (maxsize < 13)
562         return NULL;
563     end = memchr(data, '\0', maxsize-12);
564     if (!end)
565         return NULL;
566     end++;
567     *used = end - data + 12;
568     return fontspec_new(data,
569                         GET_32BIT_MSB_FIRST(end),
570                         GET_32BIT_MSB_FIRST(end + 4),
571                         GET_32BIT_MSB_FIRST(end + 8));
572 }