xref: /freebsd/crypto/openssl/crypto/dso/dso_win32.c (revision 5b56413d04e608379c9a306373554a8e4d321bc0)
1 /*
2  * Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include "e_os.h"
11 #include "dso_local.h"
12 
13 #if defined(DSO_WIN32)
14 
15 # ifdef _WIN32_WCE
16 #  if _WIN32_WCE < 300
17 static FARPROC GetProcAddressA(HMODULE hModule, LPCSTR lpProcName)
18 {
19     WCHAR lpProcNameW[64];
20     int i;
21 
22     for (i = 0; lpProcName[i] && i < 64; i++)
23         lpProcNameW[i] = (WCHAR)lpProcName[i];
24     if (i == 64)
25         return NULL;
26     lpProcNameW[i] = 0;
27 
28     return GetProcAddressW(hModule, lpProcNameW);
29 }
30 #  endif
31 #  undef GetProcAddress
32 #  define GetProcAddress GetProcAddressA
33 
34 static HINSTANCE LoadLibraryA(LPCSTR lpLibFileName)
35 {
36     WCHAR *fnamw;
37     size_t len_0 = strlen(lpLibFileName) + 1, i;
38 
39 #  ifdef _MSC_VER
40     fnamw = (WCHAR *)_alloca(len_0 * sizeof(WCHAR));
41 #  else
42     fnamw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
43 #  endif
44     if (fnamw == NULL) {
45         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
46         return NULL;
47     }
48 #  if defined(_WIN32_WCE) && _WIN32_WCE>=101
49     if (!MultiByteToWideChar(CP_ACP, 0, lpLibFileName, len_0, fnamw, len_0))
50 #  endif
51         for (i = 0; i < len_0; i++)
52             fnamw[i] = (WCHAR)lpLibFileName[i];
53 
54     return LoadLibraryW(fnamw);
55 }
56 # endif
57 
58 /* Part of the hack in "win32_load" ... */
59 # define DSO_MAX_TRANSLATED_SIZE 256
60 
61 static int win32_load(DSO *dso);
62 static int win32_unload(DSO *dso);
63 static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname);
64 static char *win32_name_converter(DSO *dso, const char *filename);
65 static char *win32_merger(DSO *dso, const char *filespec1,
66                           const char *filespec2);
67 static int win32_pathbyaddr(void *addr, char *path, int sz);
68 static void *win32_globallookup(const char *name);
69 
70 static const char *openssl_strnchr(const char *string, int c, size_t len);
71 
72 static DSO_METHOD dso_meth_win32 = {
73     "OpenSSL 'win32' shared library method",
74     win32_load,
75     win32_unload,
76     win32_bind_func,
77     NULL,                       /* ctrl */
78     win32_name_converter,
79     win32_merger,
80     NULL,                       /* init */
81     NULL,                       /* finish */
82     win32_pathbyaddr,           /* pathbyaddr */
83     win32_globallookup
84 };
85 
86 DSO_METHOD *DSO_METHOD_openssl(void)
87 {
88     return &dso_meth_win32;
89 }
90 
91 /*
92  * For this DSO_METHOD, our meth_data STACK will contain; (i) a pointer to
93  * the handle (HINSTANCE) returned from LoadLibrary(), and copied.
94  */
95 
96 static int win32_load(DSO *dso)
97 {
98     HINSTANCE h = NULL, *p = NULL;
99     /* See applicable comments from dso_dl.c */
100     char *filename = DSO_convert_filename(dso, NULL);
101 
102     if (filename == NULL) {
103         ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME);
104         goto err;
105     }
106     h = LoadLibraryA(filename);
107     if (h == NULL) {
108         ERR_raise_data(ERR_LIB_DSO, DSO_R_LOAD_FAILED,
109                        "filename(%s)", filename);
110         goto err;
111     }
112     p = OPENSSL_malloc(sizeof(*p));
113     if (p == NULL) {
114         ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
115         goto err;
116     }
117     *p = h;
118     if (!sk_void_push(dso->meth_data, p)) {
119         ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR);
120         goto err;
121     }
122     /* Success */
123     dso->loaded_filename = filename;
124     return 1;
125  err:
126     /* Cleanup ! */
127     OPENSSL_free(filename);
128     OPENSSL_free(p);
129     if (h != NULL)
130         FreeLibrary(h);
131     return 0;
132 }
133 
134 static int win32_unload(DSO *dso)
135 {
136     HINSTANCE *p;
137     if (dso == NULL) {
138         ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
139         return 0;
140     }
141     if (sk_void_num(dso->meth_data) < 1)
142         return 1;
143     p = sk_void_pop(dso->meth_data);
144     if (p == NULL) {
145         ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE);
146         return 0;
147     }
148     if (!FreeLibrary(*p)) {
149         ERR_raise(ERR_LIB_DSO, DSO_R_UNLOAD_FAILED);
150         /*
151          * We should push the value back onto the stack in case of a retry.
152          */
153         sk_void_push(dso->meth_data, p);
154         return 0;
155     }
156     /* Cleanup */
157     OPENSSL_free(p);
158     return 1;
159 }
160 
161 static DSO_FUNC_TYPE win32_bind_func(DSO *dso, const char *symname)
162 {
163     HINSTANCE *ptr;
164     union {
165         void *p;
166         FARPROC f;
167     } sym;
168 
169     if ((dso == NULL) || (symname == NULL)) {
170         ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
171         return NULL;
172     }
173     if (sk_void_num(dso->meth_data) < 1) {
174         ERR_raise(ERR_LIB_DSO, DSO_R_STACK_ERROR);
175         return NULL;
176     }
177     ptr = sk_void_value(dso->meth_data, sk_void_num(dso->meth_data) - 1);
178     if (ptr == NULL) {
179         ERR_raise(ERR_LIB_DSO, DSO_R_NULL_HANDLE);
180         return NULL;
181     }
182     sym.f = GetProcAddress(*ptr, symname);
183     if (sym.p == NULL) {
184         ERR_raise_data(ERR_LIB_DSO, DSO_R_SYM_FAILURE, "symname(%s)", symname);
185         return NULL;
186     }
187     return (DSO_FUNC_TYPE)sym.f;
188 }
189 
190 struct file_st {
191     const char *node;
192     int nodelen;
193     const char *device;
194     int devicelen;
195     const char *predir;
196     int predirlen;
197     const char *dir;
198     int dirlen;
199     const char *file;
200     int filelen;
201 };
202 
203 static struct file_st *win32_splitter(DSO *dso, const char *filename,
204                                       int assume_last_is_dir)
205 {
206     struct file_st *result = NULL;
207     enum { IN_NODE, IN_DEVICE, IN_FILE } position;
208     const char *start = filename;
209     char last;
210 
211     if (!filename) {
212         ERR_raise(ERR_LIB_DSO, DSO_R_NO_FILENAME);
213         return NULL;
214     }
215 
216     result = OPENSSL_zalloc(sizeof(*result));
217     if (result == NULL) {
218         ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
219         return NULL;
220     }
221 
222     position = IN_DEVICE;
223 
224     if ((filename[0] == '\\' && filename[1] == '\\')
225         || (filename[0] == '/' && filename[1] == '/')) {
226         position = IN_NODE;
227         filename += 2;
228         start = filename;
229         result->node = start;
230     }
231 
232     do {
233         last = filename[0];
234         switch (last) {
235         case ':':
236             if (position != IN_DEVICE) {
237                 ERR_raise(ERR_LIB_DSO, DSO_R_INCORRECT_FILE_SYNTAX);
238                 OPENSSL_free(result);
239                 return NULL;
240             }
241             result->device = start;
242             result->devicelen = (int)(filename - start);
243             position = IN_FILE;
244             start = ++filename;
245             result->dir = start;
246             break;
247         case '\\':
248         case '/':
249             if (position == IN_NODE) {
250                 result->nodelen = (int)(filename - start);
251                 position = IN_FILE;
252                 start = ++filename;
253                 result->dir = start;
254             } else if (position == IN_DEVICE) {
255                 position = IN_FILE;
256                 filename++;
257                 result->dir = start;
258                 result->dirlen = (int)(filename - start);
259                 start = filename;
260             } else {
261                 filename++;
262                 result->dirlen += (int)(filename - start);
263                 start = filename;
264             }
265             break;
266         case '\0':
267             if (position == IN_NODE) {
268                 result->nodelen = (int)(filename - start);
269             } else {
270                 if (filename - start > 0) {
271                     if (assume_last_is_dir) {
272                         if (position == IN_DEVICE) {
273                             result->dir = start;
274                             result->dirlen = 0;
275                         }
276                         result->dirlen += (int)(filename - start);
277                     } else {
278                         result->file = start;
279                         result->filelen = (int)(filename - start);
280                     }
281                 }
282             }
283             break;
284         default:
285             filename++;
286             break;
287         }
288     }
289     while (last);
290 
291     if (!result->nodelen)
292         result->node = NULL;
293     if (!result->devicelen)
294         result->device = NULL;
295     if (!result->dirlen)
296         result->dir = NULL;
297     if (!result->filelen)
298         result->file = NULL;
299 
300     return result;
301 }
302 
303 static char *win32_joiner(DSO *dso, const struct file_st *file_split)
304 {
305     int len = 0, offset = 0;
306     char *result = NULL;
307     const char *start;
308 
309     if (!file_split) {
310         ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
311         return NULL;
312     }
313     if (file_split->node) {
314         len += 2 + file_split->nodelen; /* 2 for starting \\ */
315         if (file_split->predir || file_split->dir || file_split->file)
316             len++;              /* 1 for ending \ */
317     } else if (file_split->device) {
318         len += file_split->devicelen + 1; /* 1 for ending : */
319     }
320     len += file_split->predirlen;
321     if (file_split->predir && (file_split->dir || file_split->file)) {
322         len++;                  /* 1 for ending \ */
323     }
324     len += file_split->dirlen;
325     if (file_split->dir && file_split->file) {
326         len++;                  /* 1 for ending \ */
327     }
328     len += file_split->filelen;
329 
330     if (!len) {
331         ERR_raise(ERR_LIB_DSO, DSO_R_EMPTY_FILE_STRUCTURE);
332         return NULL;
333     }
334 
335     result = OPENSSL_malloc(len + 1);
336     if (result == NULL) {
337         ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
338         return NULL;
339     }
340 
341     if (file_split->node) {
342         strcpy(&result[offset], "\\\\");
343         offset += 2;
344         strncpy(&result[offset], file_split->node, file_split->nodelen);
345         offset += file_split->nodelen;
346         if (file_split->predir || file_split->dir || file_split->file) {
347             result[offset] = '\\';
348             offset++;
349         }
350     } else if (file_split->device) {
351         strncpy(&result[offset], file_split->device, file_split->devicelen);
352         offset += file_split->devicelen;
353         result[offset] = ':';
354         offset++;
355     }
356     start = file_split->predir;
357     while (file_split->predirlen > (start - file_split->predir)) {
358         const char *end = openssl_strnchr(start, '/',
359                                           file_split->predirlen - (start -
360                                                                    file_split->predir));
361         if (!end)
362             end = start
363                 + file_split->predirlen - (start - file_split->predir);
364         strncpy(&result[offset], start, end - start);
365         offset += (int)(end - start);
366         result[offset] = '\\';
367         offset++;
368         start = end + 1;
369     }
370     start = file_split->dir;
371     while (file_split->dirlen > (start - file_split->dir)) {
372         const char *end = openssl_strnchr(start, '/',
373                                           file_split->dirlen - (start -
374                                                                 file_split->dir));
375         if (!end)
376             end = start + file_split->dirlen - (start - file_split->dir);
377         strncpy(&result[offset], start, end - start);
378         offset += (int)(end - start);
379         result[offset] = '\\';
380         offset++;
381         start = end + 1;
382     }
383     strncpy(&result[offset], file_split->file, file_split->filelen);
384     offset += file_split->filelen;
385     result[offset] = '\0';
386     return result;
387 }
388 
389 static char *win32_merger(DSO *dso, const char *filespec1,
390                           const char *filespec2)
391 {
392     char *merged = NULL;
393     struct file_st *filespec1_split = NULL;
394     struct file_st *filespec2_split = NULL;
395 
396     if (!filespec1 && !filespec2) {
397         ERR_raise(ERR_LIB_DSO, ERR_R_PASSED_NULL_PARAMETER);
398         return NULL;
399     }
400     if (!filespec2) {
401         merged = OPENSSL_strdup(filespec1);
402         if (merged == NULL) {
403             ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
404             return NULL;
405         }
406     } else if (!filespec1) {
407         merged = OPENSSL_strdup(filespec2);
408         if (merged == NULL) {
409             ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
410             return NULL;
411         }
412     } else {
413         filespec1_split = win32_splitter(dso, filespec1, 0);
414         if (!filespec1_split) {
415             ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
416             return NULL;
417         }
418         filespec2_split = win32_splitter(dso, filespec2, 1);
419         if (!filespec2_split) {
420             ERR_raise(ERR_LIB_DSO, ERR_R_MALLOC_FAILURE);
421             OPENSSL_free(filespec1_split);
422             return NULL;
423         }
424 
425         /* Fill in into filespec1_split */
426         if (!filespec1_split->node && !filespec1_split->device) {
427             filespec1_split->node = filespec2_split->node;
428             filespec1_split->nodelen = filespec2_split->nodelen;
429             filespec1_split->device = filespec2_split->device;
430             filespec1_split->devicelen = filespec2_split->devicelen;
431         }
432         if (!filespec1_split->dir) {
433             filespec1_split->dir = filespec2_split->dir;
434             filespec1_split->dirlen = filespec2_split->dirlen;
435         } else if (filespec1_split->dir[0] != '\\'
436                    && filespec1_split->dir[0] != '/') {
437             filespec1_split->predir = filespec2_split->dir;
438             filespec1_split->predirlen = filespec2_split->dirlen;
439         }
440         if (!filespec1_split->file) {
441             filespec1_split->file = filespec2_split->file;
442             filespec1_split->filelen = filespec2_split->filelen;
443         }
444 
445         merged = win32_joiner(dso, filespec1_split);
446     }
447     OPENSSL_free(filespec1_split);
448     OPENSSL_free(filespec2_split);
449     return merged;
450 }
451 
452 static char *win32_name_converter(DSO *dso, const char *filename)
453 {
454     char *translated;
455     int len, transform;
456 
457     len = strlen(filename);
458     transform = ((strstr(filename, "/") == NULL) &&
459                  (strstr(filename, "\\") == NULL) &&
460                  (strstr(filename, ":") == NULL));
461     if (transform)
462         /* We will convert this to "%s.dll" */
463         translated = OPENSSL_malloc(len + 5);
464     else
465         /* We will simply duplicate filename */
466         translated = OPENSSL_malloc(len + 1);
467     if (translated == NULL) {
468         ERR_raise(ERR_LIB_DSO, DSO_R_NAME_TRANSLATION_FAILED);
469         return NULL;
470     }
471     if (transform)
472         sprintf(translated, "%s.dll", filename);
473     else
474         sprintf(translated, "%s", filename);
475     return translated;
476 }
477 
478 static const char *openssl_strnchr(const char *string, int c, size_t len)
479 {
480     size_t i;
481     const char *p;
482     for (i = 0, p = string; i < len && *p; i++, p++) {
483         if (*p == c)
484             return p;
485     }
486     return NULL;
487 }
488 
489 # include <tlhelp32.h>
490 # ifdef _WIN32_WCE
491 #  define DLLNAME "TOOLHELP.DLL"
492 # else
493 #  ifdef MODULEENTRY32
494 #   undef MODULEENTRY32         /* unmask the ASCII version! */
495 #  endif
496 #  define DLLNAME "KERNEL32.DLL"
497 # endif
498 
499 typedef HANDLE(WINAPI *CREATETOOLHELP32SNAPSHOT) (DWORD, DWORD);
500 typedef BOOL(WINAPI *CLOSETOOLHELP32SNAPSHOT) (HANDLE);
501 typedef BOOL(WINAPI *MODULE32) (HANDLE, MODULEENTRY32 *);
502 
503 static int win32_pathbyaddr(void *addr, char *path, int sz)
504 {
505     HMODULE dll;
506     HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
507     MODULEENTRY32 me32;
508     CREATETOOLHELP32SNAPSHOT create_snap;
509     CLOSETOOLHELP32SNAPSHOT close_snap;
510     MODULE32 module_first, module_next;
511 
512     if (addr == NULL) {
513         union {
514             int (*f) (void *, char *, int);
515             void *p;
516         } t = {
517             win32_pathbyaddr
518         };
519         addr = t.p;
520     }
521 
522     dll = LoadLibrary(TEXT(DLLNAME));
523     if (dll == NULL) {
524         ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED);
525         return -1;
526     }
527 
528     create_snap = (CREATETOOLHELP32SNAPSHOT)
529         GetProcAddress(dll, "CreateToolhelp32Snapshot");
530     if (create_snap == NULL) {
531         FreeLibrary(dll);
532         ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED);
533         return -1;
534     }
535     /* We take the rest for granted... */
536 # ifdef _WIN32_WCE
537     close_snap = (CLOSETOOLHELP32SNAPSHOT)
538         GetProcAddress(dll, "CloseToolhelp32Snapshot");
539 # else
540     close_snap = (CLOSETOOLHELP32SNAPSHOT) CloseHandle;
541 # endif
542     module_first = (MODULE32) GetProcAddress(dll, "Module32First");
543     module_next = (MODULE32) GetProcAddress(dll, "Module32Next");
544 
545     /*
546      * Take a snapshot of current process which includes
547      * list of all involved modules.
548      */
549     hModuleSnap = (*create_snap) (TH32CS_SNAPMODULE, 0);
550     if (hModuleSnap == INVALID_HANDLE_VALUE) {
551         FreeLibrary(dll);
552         ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED);
553         return -1;
554     }
555 
556     me32.dwSize = sizeof(me32);
557 
558     if (!(*module_first) (hModuleSnap, &me32)) {
559         (*close_snap) (hModuleSnap);
560         FreeLibrary(dll);
561         ERR_raise(ERR_LIB_DSO, DSO_R_FAILURE);
562         return -1;
563     }
564 
565     /* Enumerate the modules to find one which includes me. */
566     do {
567         if ((size_t) addr >= (size_t) me32.modBaseAddr &&
568             (size_t) addr < (size_t) (me32.modBaseAddr + me32.modBaseSize)) {
569             (*close_snap) (hModuleSnap);
570             FreeLibrary(dll);
571 # ifdef _WIN32_WCE
572 #  if _WIN32_WCE >= 101
573             return WideCharToMultiByte(CP_ACP, 0, me32.szExePath, -1,
574                                        path, sz, NULL, NULL);
575 #  else
576             {
577                 int i, len = (int)wcslen(me32.szExePath);
578                 if (sz <= 0)
579                     return len + 1;
580                 if (len >= sz)
581                     len = sz - 1;
582                 for (i = 0; i < len; i++)
583                     path[i] = (char)me32.szExePath[i];
584                 path[len++] = '\0';
585                 return len;
586             }
587 #  endif
588 # else
589             {
590                 int len = (int)strlen(me32.szExePath);
591                 if (sz <= 0)
592                     return len + 1;
593                 if (len >= sz)
594                     len = sz - 1;
595                 memcpy(path, me32.szExePath, len);
596                 path[len++] = '\0';
597                 return len;
598             }
599 # endif
600         }
601     } while ((*module_next) (hModuleSnap, &me32));
602 
603     (*close_snap) (hModuleSnap);
604     FreeLibrary(dll);
605     return 0;
606 }
607 
608 static void *win32_globallookup(const char *name)
609 {
610     HMODULE dll;
611     HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
612     MODULEENTRY32 me32;
613     CREATETOOLHELP32SNAPSHOT create_snap;
614     CLOSETOOLHELP32SNAPSHOT close_snap;
615     MODULE32 module_first, module_next;
616     union {
617         void *p;
618         FARPROC f;
619     } ret = { NULL };
620 
621     dll = LoadLibrary(TEXT(DLLNAME));
622     if (dll == NULL) {
623         ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED);
624         return NULL;
625     }
626 
627     create_snap = (CREATETOOLHELP32SNAPSHOT)
628         GetProcAddress(dll, "CreateToolhelp32Snapshot");
629     if (create_snap == NULL) {
630         FreeLibrary(dll);
631         ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED);
632         return NULL;
633     }
634     /* We take the rest for granted... */
635 # ifdef _WIN32_WCE
636     close_snap = (CLOSETOOLHELP32SNAPSHOT)
637         GetProcAddress(dll, "CloseToolhelp32Snapshot");
638 # else
639     close_snap = (CLOSETOOLHELP32SNAPSHOT) CloseHandle;
640 # endif
641     module_first = (MODULE32) GetProcAddress(dll, "Module32First");
642     module_next = (MODULE32) GetProcAddress(dll, "Module32Next");
643 
644     hModuleSnap = (*create_snap) (TH32CS_SNAPMODULE, 0);
645     if (hModuleSnap == INVALID_HANDLE_VALUE) {
646         FreeLibrary(dll);
647         ERR_raise(ERR_LIB_DSO, DSO_R_UNSUPPORTED);
648         return NULL;
649     }
650 
651     me32.dwSize = sizeof(me32);
652 
653     if (!(*module_first) (hModuleSnap, &me32)) {
654         (*close_snap) (hModuleSnap);
655         FreeLibrary(dll);
656         return NULL;
657     }
658 
659     do {
660         if ((ret.f = GetProcAddress(me32.hModule, name))) {
661             (*close_snap) (hModuleSnap);
662             FreeLibrary(dll);
663             return ret.p;
664         }
665     } while ((*module_next) (hModuleSnap, &me32));
666 
667     (*close_snap) (hModuleSnap);
668     FreeLibrary(dll);
669     return NULL;
670 }
671 #endif                          /* DSO_WIN32 */
672