]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - windows/winmisc.c
first pass
[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 | LOAD_LIBRARY_SEARCH_USER_DIRS only */
180         p_SetDefaultDllDirectories(0x800|0x400);
181     }
182 }
183
184 void dll_hijacking_protection_add_path(const wchar_t *path)
185 {
186     static HMODULE kernel32_module;
187     DECL_WINDOWS_FUNCTION(static, BOOL, AddDllDirectory, (PCWSTR));
188
189     if (!kernel32_module) {
190         kernel32_module = load_system32_dll("kernel32.dll");
191         GET_WINDOWS_FUNCTION(kernel32_module, AddDllDirectory);
192     }
193
194     if (p_AddDllDirectory) {
195         p_AddDllDirectory(path);
196     }
197 }
198 BOOL init_winver(void)
199 {
200     ZeroMemory(&osVersion, sizeof(osVersion));
201     osVersion.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
202     return GetVersionEx ( (OSVERSIONINFO *) &osVersion);
203 }
204
205 HMODULE load_system32_dll(const char *libname)
206 {
207     /*
208      * Wrapper function to load a DLL out of c:\windows\system32
209      * without going through the full DLL search path. (Hence no
210      * attack is possible by placing a substitute DLL earlier on that
211      * path.)
212      */
213     static char *sysdir = NULL;
214     char *fullpath;
215     HMODULE ret;
216
217     if (!sysdir) {
218         int size = 0, len;
219         do {
220             size = 3*size/2 + 512;
221             sysdir = sresize(sysdir, size, char);
222             len = GetSystemDirectory(sysdir, size);
223         } while (len >= size);
224     }
225
226     fullpath = dupcat(sysdir, "\\", libname, NULL);
227     ret = LoadLibrary(fullpath);
228     sfree(fullpath);
229     return ret;
230 }
231
232 /*
233  * A tree234 containing mappings from system error codes to strings.
234  */
235
236 struct errstring {
237     int error;
238     char *text;
239 };
240
241 static int errstring_find(void *av, void *bv)
242 {
243     int *a = (int *)av;
244     struct errstring *b = (struct errstring *)bv;
245     if (*a < b->error)
246         return -1;
247     if (*a > b->error)
248         return +1;
249     return 0;
250 }
251 static int errstring_compare(void *av, void *bv)
252 {
253     struct errstring *a = (struct errstring *)av;
254     return errstring_find(&a->error, bv);
255 }
256
257 static tree234 *errstrings = NULL;
258
259 const char *win_strerror(int error)
260 {
261     struct errstring *es;
262
263     if (!errstrings)
264         errstrings = newtree234(errstring_compare);
265
266     es = find234(errstrings, &error, errstring_find);
267
268     if (!es) {
269         char msgtext[65536]; /* maximum size for FormatMessage is 64K */
270
271         es = snew(struct errstring);
272         es->error = error;
273         if (!FormatMessage((FORMAT_MESSAGE_FROM_SYSTEM |
274                             FORMAT_MESSAGE_IGNORE_INSERTS), NULL, error,
275                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
276                            msgtext, lenof(msgtext)-1, NULL)) {
277             sprintf(msgtext,
278                     "(unable to format: FormatMessage returned %u)",
279                     (unsigned int)GetLastError());
280         } else {
281             int len = strlen(msgtext);
282             if (len > 0 && msgtext[len-1] == '\n')
283                 msgtext[len-1] = '\0';
284         }
285         es->text = dupprintf("Error %d: %s", error, msgtext);
286         add234(errstrings, es);
287     }
288
289     return es->text;
290 }
291
292 #ifdef DEBUG
293 static FILE *debug_fp = NULL;
294 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
295 static int debug_got_console = 0;
296
297 void dputs(const char *buf)
298 {
299     DWORD dw;
300
301     if (!debug_got_console) {
302         if (AllocConsole()) {
303             debug_got_console = 1;
304             debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
305         }
306     }
307     if (!debug_fp) {
308         debug_fp = fopen("debug.log", "w");
309     }
310
311     if (debug_hdl != INVALID_HANDLE_VALUE) {
312         WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
313     }
314     fputs(buf, debug_fp);
315     fflush(debug_fp);
316 }
317 #endif
318
319 #ifdef MINEFIELD
320 /*
321  * Minefield - a Windows equivalent for Electric Fence
322  */
323
324 #define PAGESIZE 4096
325
326 /*
327  * Design:
328  * 
329  * We start by reserving as much virtual address space as Windows
330  * will sensibly (or not sensibly) let us have. We flag it all as
331  * invalid memory.
332  * 
333  * Any allocation attempt is satisfied by committing one or more
334  * pages, with an uncommitted page on either side. The returned
335  * memory region is jammed up against the _end_ of the pages.
336  * 
337  * Freeing anything causes instantaneous decommitment of the pages
338  * involved, so stale pointers are caught as soon as possible.
339  */
340
341 static int minefield_initialised = 0;
342 static void *minefield_region = NULL;
343 static long minefield_size = 0;
344 static long minefield_npages = 0;
345 static long minefield_curpos = 0;
346 static unsigned short *minefield_admin = NULL;
347 static void *minefield_pages = NULL;
348
349 static void minefield_admin_hide(int hide)
350 {
351     int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
352     VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
353 }
354
355 static void minefield_init(void)
356 {
357     int size;
358     int admin_size;
359     int i;
360
361     for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
362         minefield_region = VirtualAlloc(NULL, size,
363                                         MEM_RESERVE, PAGE_NOACCESS);
364         if (minefield_region)
365             break;
366     }
367     minefield_size = size;
368
369     /*
370      * Firstly, allocate a section of that to be the admin block.
371      * We'll need a two-byte field for each page.
372      */
373     minefield_admin = minefield_region;
374     minefield_npages = minefield_size / PAGESIZE;
375     admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
376     minefield_npages = (minefield_size - admin_size) / PAGESIZE;
377     minefield_pages = (char *) minefield_region + admin_size;
378
379     /*
380      * Commit the admin region.
381      */
382     VirtualAlloc(minefield_admin, minefield_npages * 2,
383                  MEM_COMMIT, PAGE_READWRITE);
384
385     /*
386      * Mark all pages as unused (0xFFFF).
387      */
388     for (i = 0; i < minefield_npages; i++)
389         minefield_admin[i] = 0xFFFF;
390
391     /*
392      * Hide the admin region.
393      */
394     minefield_admin_hide(1);
395
396     minefield_initialised = 1;
397 }
398
399 static void minefield_bomb(void)
400 {
401     div(1, *(int *) minefield_pages);
402 }
403
404 static void *minefield_alloc(int size)
405 {
406     int npages;
407     int pos, lim, region_end, region_start;
408     int start;
409     int i;
410
411     npages = (size + PAGESIZE - 1) / PAGESIZE;
412
413     minefield_admin_hide(0);
414
415     /*
416      * Search from current position until we find a contiguous
417      * bunch of npages+2 unused pages.
418      */
419     pos = minefield_curpos;
420     lim = minefield_npages;
421     while (1) {
422         /* Skip over used pages. */
423         while (pos < lim && minefield_admin[pos] != 0xFFFF)
424             pos++;
425         /* Count unused pages. */
426         start = pos;
427         while (pos < lim && pos - start < npages + 2 &&
428                minefield_admin[pos] == 0xFFFF)
429             pos++;
430         if (pos - start == npages + 2)
431             break;
432         /* If we've reached the limit, reset the limit or stop. */
433         if (pos >= lim) {
434             if (lim == minefield_npages) {
435                 /* go round and start again at zero */
436                 lim = minefield_curpos;
437                 pos = 0;
438             } else {
439                 minefield_admin_hide(1);
440                 return NULL;
441             }
442         }
443     }
444
445     minefield_curpos = pos - 1;
446
447     /*
448      * We have npages+2 unused pages starting at start. We leave
449      * the first and last of these alone and use the rest.
450      */
451     region_end = (start + npages + 1) * PAGESIZE;
452     region_start = region_end - size;
453     /* FIXME: could align here if we wanted */
454
455     /*
456      * Update the admin region.
457      */
458     for (i = start + 2; i < start + npages + 1; i++)
459         minefield_admin[i] = 0xFFFE;   /* used but no region starts here */
460     minefield_admin[start + 1] = region_start % PAGESIZE;
461
462     minefield_admin_hide(1);
463
464     VirtualAlloc((char *) minefield_pages + region_start, size,
465                  MEM_COMMIT, PAGE_READWRITE);
466     return (char *) minefield_pages + region_start;
467 }
468
469 static void minefield_free(void *ptr)
470 {
471     int region_start, i, j;
472
473     minefield_admin_hide(0);
474
475     region_start = (char *) ptr - (char *) minefield_pages;
476     i = region_start / PAGESIZE;
477     if (i < 0 || i >= minefield_npages ||
478         minefield_admin[i] != region_start % PAGESIZE)
479         minefield_bomb();
480     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
481         minefield_admin[j] = 0xFFFF;
482     }
483
484     VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
485
486     minefield_admin_hide(1);
487 }
488
489 static int minefield_get_size(void *ptr)
490 {
491     int region_start, i, j;
492
493     minefield_admin_hide(0);
494
495     region_start = (char *) ptr - (char *) minefield_pages;
496     i = region_start / PAGESIZE;
497     if (i < 0 || i >= minefield_npages ||
498         minefield_admin[i] != region_start % PAGESIZE)
499         minefield_bomb();
500     for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
501
502     minefield_admin_hide(1);
503
504     return j * PAGESIZE - region_start;
505 }
506
507 void *minefield_c_malloc(size_t size)
508 {
509     if (!minefield_initialised)
510         minefield_init();
511     return minefield_alloc(size);
512 }
513
514 void minefield_c_free(void *p)
515 {
516     if (!minefield_initialised)
517         minefield_init();
518     minefield_free(p);
519 }
520
521 /*
522  * realloc _always_ moves the chunk, for rapid detection of code
523  * that assumes it won't.
524  */
525 void *minefield_c_realloc(void *p, size_t size)
526 {
527     size_t oldsize;
528     void *q;
529     if (!minefield_initialised)
530         minefield_init();
531     q = minefield_alloc(size);
532     oldsize = minefield_get_size(p);
533     memcpy(q, p, (oldsize < size ? oldsize : size));
534     minefield_free(p);
535     return q;
536 }
537
538 #endif                          /* MINEFIELD */
539
540 FontSpec *fontspec_new(const char *name,
541                         int bold, int height, int charset)
542 {
543     FontSpec *f = snew(FontSpec);
544     f->name = dupstr(name);
545     f->isbold = bold;
546     f->height = height;
547     f->charset = charset;
548     return f;
549 }
550 FontSpec *fontspec_copy(const FontSpec *f)
551 {
552     return fontspec_new(f->name, f->isbold, f->height, f->charset);
553 }
554 void fontspec_free(FontSpec *f)
555 {
556     sfree(f->name);
557     sfree(f);
558 }
559 int fontspec_serialise(FontSpec *f, void *vdata)
560 {
561     char *data = (char *)vdata;
562     int len = strlen(f->name) + 1;     /* include trailing NUL */
563     if (data) {
564         strcpy(data, f->name);
565         PUT_32BIT_MSB_FIRST(data + len, f->isbold);
566         PUT_32BIT_MSB_FIRST(data + len + 4, f->height);
567         PUT_32BIT_MSB_FIRST(data + len + 8, f->charset);
568     }
569     return len + 12;                   /* also include three 4-byte ints */
570 }
571 FontSpec *fontspec_deserialise(void *vdata, int maxsize, int *used)
572 {
573     char *data = (char *)vdata;
574     char *end;
575     if (maxsize < 13)
576         return NULL;
577     end = memchr(data, '\0', maxsize-12);
578     if (!end)
579         return NULL;
580     end++;
581     *used = end - data + 12;
582     return fontspec_new(data,
583                         GET_32BIT_MSB_FIRST(end),
584                         GET_32BIT_MSB_FIRST(end + 4),
585                         GET_32BIT_MSB_FIRST(end + 8));
586 }