kernel32: Fix the case where memory is freed twice in GlobalFree.
[wine] / dlls / crypt32 / rootstore.c
1 /*
2  * Copyright 2007 Juan Lang
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18 #include "config.h"
19 #include <stdarg.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_STAT_H
23 #include <sys/stat.h>
24 #endif
25 #include <dirent.h>
26 #include <fcntl.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <errno.h>
31 #include <limits.h>
32 #include "ntstatus.h"
33 #define WIN32_NO_STATUS
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winreg.h"
37 #include "wincrypt.h"
38 #include "winternl.h"
39 #include "wine/debug.h"
40 #include "crypt32_private.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
43
44 #define INITIAL_CERT_BUFFER 1024
45
46 struct DynamicBuffer
47 {
48     DWORD allocated;
49     DWORD used;
50     BYTE *data;
51 };
52
53 static inline void reset_buffer(struct DynamicBuffer *buffer)
54 {
55     buffer->used = 0;
56     if (buffer->data) buffer->data[0] = 0;
57 }
58
59 static BOOL add_line_to_buffer(struct DynamicBuffer *buffer, LPCSTR line)
60 {
61     BOOL ret;
62
63     if (buffer->used + strlen(line) + 1 > buffer->allocated)
64     {
65         if (!buffer->allocated)
66         {
67             buffer->data = CryptMemAlloc(INITIAL_CERT_BUFFER);
68             if (buffer->data)
69             {
70                 buffer->data[0] = 0;
71                 buffer->allocated = INITIAL_CERT_BUFFER;
72             }
73         }
74         else
75         {
76             DWORD new_size = max(buffer->allocated * 2,
77              buffer->used + strlen(line) + 1);
78
79             buffer->data = CryptMemRealloc(buffer->data, new_size);
80             if (buffer->data)
81                 buffer->allocated = new_size;
82         }
83     }
84     if (buffer->data)
85     {
86         strcpy((char *)buffer->data + strlen((char *)buffer->data), line);
87         /* Not strlen + 1, otherwise we'd count the NULL for every line's
88          * addition (but we overwrite the previous NULL character.)  Not an
89          * overrun, we allocate strlen + 1 bytes above.
90          */
91         buffer->used += strlen(line);
92         ret = TRUE;
93     }
94     else
95         ret = FALSE;
96     return ret;
97 }
98
99 /* Reads any base64-encoded certificates present in fp and adds them to store.
100  * Returns TRUE if any certifcates were successfully imported.
101  */
102 static BOOL import_base64_certs_from_fp(FILE *fp, HCERTSTORE store)
103 {
104     char line[1024];
105     BOOL in_cert = FALSE;
106     struct DynamicBuffer saved_cert = { 0, 0, NULL };
107     int num_certs = 0;
108
109     TRACE("\n");
110     while (fgets(line, sizeof(line), fp))
111     {
112         static const char header[] = "-----BEGIN CERTIFICATE-----";
113         static const char trailer[] = "-----END CERTIFICATE-----";
114
115         if (!strncmp(line, header, strlen(header)))
116         {
117             TRACE("begin new certificate\n");
118             in_cert = TRUE;
119             reset_buffer(&saved_cert);
120         }
121         else if (!strncmp(line, trailer, strlen(trailer)))
122         {
123             DWORD size;
124
125             TRACE("end of certificate, adding cert\n");
126             in_cert = FALSE;
127             if (CryptStringToBinaryA((char *)saved_cert.data, saved_cert.used,
128              CRYPT_STRING_BASE64, NULL, &size, NULL, NULL))
129             {
130                 LPBYTE buf = CryptMemAlloc(size);
131
132                 if (buf)
133                 {
134                     CryptStringToBinaryA((char *)saved_cert.data,
135                      saved_cert.used, CRYPT_STRING_BASE64, buf, &size, NULL,
136                      NULL);
137                     if (CertAddEncodedCertificateToStore(store,
138                      X509_ASN_ENCODING, buf, size, CERT_STORE_ADD_NEW, NULL))
139                         num_certs++;
140                 }
141             }
142         }
143         else if (in_cert)
144             add_line_to_buffer(&saved_cert, line);
145     }
146     CryptMemFree(saved_cert.data);
147     TRACE("Read %d certs\n", num_certs);
148     return num_certs > 0;
149 }
150
151 static const char *trust_status_to_str(DWORD status)
152 {
153     static char buf[1024];
154     int pos = 0;
155
156     if (status & CERT_TRUST_IS_NOT_TIME_VALID)
157         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\texpired");
158     if (status & CERT_TRUST_IS_NOT_TIME_NESTED)
159         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\tbad time nesting");
160     if (status & CERT_TRUST_IS_REVOKED)
161         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\trevoked");
162     if (status & CERT_TRUST_IS_NOT_SIGNATURE_VALID)
163         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\tbad signature");
164     if (status & CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
165         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\tbad usage");
166     if (status & CERT_TRUST_IS_UNTRUSTED_ROOT)
167         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\tuntrusted root");
168     if (status & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
169         pos += snprintf(buf + pos, sizeof(buf) - pos,
170          "\n\tunknown revocation status");
171     if (status & CERT_TRUST_IS_CYCLIC)
172         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\tcyclic chain");
173     if (status & CERT_TRUST_INVALID_EXTENSION)
174         pos += snprintf(buf + pos, sizeof(buf) - pos,
175          "\n\tunsupported critical extension");
176     if (status & CERT_TRUST_INVALID_POLICY_CONSTRAINTS)
177         pos += snprintf(buf + pos, sizeof(buf) - pos, "\n\tbad policy");
178     if (status & CERT_TRUST_INVALID_BASIC_CONSTRAINTS)
179         pos += snprintf(buf + pos, sizeof(buf) - pos,
180          "\n\tbad basic constraints");
181     if (status & CERT_TRUST_INVALID_NAME_CONSTRAINTS)
182         pos += snprintf(buf + pos, sizeof(buf) - pos,
183          "\n\tbad name constraints");
184     if (status & CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT)
185         pos += snprintf(buf + pos, sizeof(buf) - pos,
186          "\n\tunsuported name constraint");
187     if (status & CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT)
188         pos += snprintf(buf + pos, sizeof(buf) - pos,
189          "\n\tundefined name constraint");
190     if (status & CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT)
191         pos += snprintf(buf + pos, sizeof(buf) - pos,
192          "\n\tdisallowed name constraint");
193     if (status & CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT)
194         pos += snprintf(buf + pos, sizeof(buf) - pos,
195          "\n\texcluded name constraint");
196     if (status & CERT_TRUST_IS_OFFLINE_REVOCATION)
197         pos += snprintf(buf + pos, sizeof(buf) - pos,
198          "\n\trevocation server offline");
199     if (status & CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY)
200         pos += snprintf(buf + pos, sizeof(buf) - pos,
201          "\n\tno issuance policy");
202     return buf;
203 }
204
205 static const char *get_cert_common_name(PCCERT_CONTEXT cert)
206 {
207     static char buf[1024];
208     const char *name = NULL;
209     CERT_NAME_INFO *nameInfo;
210     DWORD size;
211     BOOL ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME,
212      cert->pCertInfo->Subject.pbData, cert->pCertInfo->Subject.cbData,
213      CRYPT_DECODE_NOCOPY_FLAG | CRYPT_DECODE_ALLOC_FLAG, NULL, &nameInfo,
214      &size);
215
216     if (ret)
217     {
218         PCERT_RDN_ATTR commonName = CertFindRDNAttr(szOID_COMMON_NAME,
219          nameInfo);
220
221         if (commonName)
222         {
223             CertRDNValueToStrA(commonName->dwValueType,
224              &commonName->Value, buf, sizeof(buf));
225             name = buf;
226         }
227         LocalFree(nameInfo);
228     }
229     return name;
230 }
231
232 static void check_and_store_certs(HCERTSTORE from, HCERTSTORE to)
233 {
234     PCCERT_CONTEXT cert = NULL;
235     DWORD root_count = 0;
236
237     TRACE("\n");
238
239     do {
240         cert = CertEnumCertificatesInStore(from, cert);
241         if (cert)
242         {
243             CERT_CHAIN_ENGINE_CONFIG chainEngineConfig =
244              { sizeof(chainEngineConfig), 0 };
245             HCERTCHAINENGINE engine = CRYPT_CreateChainEngine(to,
246              &chainEngineConfig);
247
248             if (engine)
249             {
250                 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
251                 PCCERT_CHAIN_CONTEXT chain;
252                 BOOL ret = CertGetCertificateChain(engine, cert, NULL, from,
253                  &chainPara, 0, NULL, &chain);
254
255                 if (!ret)
256                     TRACE("rejecting %s: %s\n", get_cert_common_name(cert),
257                      "chain creation failed");
258                 else
259                 {
260                     /* The only allowed error is CERT_TRUST_IS_UNTRUSTED_ROOT */
261                     if (chain->TrustStatus.dwErrorStatus &
262                      ~CERT_TRUST_IS_UNTRUSTED_ROOT)
263                         TRACE("rejecting %s: %s\n", get_cert_common_name(cert),
264                          trust_status_to_str(chain->TrustStatus.dwErrorStatus &
265                          ~CERT_TRUST_IS_UNTRUSTED_ROOT));
266                     else
267                     {
268                         DWORD i, j;
269
270                         for (i = 0; i < chain->cChain; i++)
271                             for (j = 0; j < chain->rgpChain[i]->cElement; j++)
272                                 if (CertAddCertificateContextToStore(to,
273                                  chain->rgpChain[i]->rgpElement[j]->pCertContext,
274                                  CERT_STORE_ADD_NEW, NULL))
275                                     root_count++;
276                     }
277                 }
278                 CertFreeCertificateChainEngine(engine);
279             }
280         }
281     } while (cert);
282     TRACE("Added %d root certificates\n", root_count);
283 }
284
285 /* Reads the file fd, and imports any certificates in it into store.
286  * Returns TRUE if any certificates were successfully imported.
287  */
288 static BOOL import_certs_from_file(int fd, HCERTSTORE store)
289 {
290     BOOL ret = FALSE;
291     FILE *fp;
292
293     TRACE("\n");
294
295     fp = fdopen(fd, "r");
296     if (fp)
297     {
298         ret = import_base64_certs_from_fp(fp, store);
299         fclose(fp);
300     }
301     return ret;
302 }
303
304 static BOOL import_certs_from_path(LPCSTR path, HCERTSTORE store,
305  BOOL allow_dir);
306
307 /* Opens path, which must be a directory, and imports certificates from every
308  * file in the directory into store.
309  * Returns TRUE if any certificates were successfully imported.
310  */
311 static BOOL import_certs_from_dir(LPCSTR path, HCERTSTORE store)
312 {
313     BOOL ret = FALSE;
314     DIR *dir;
315
316     TRACE("(%s, %p)\n", debugstr_a(path), store);
317
318     dir = opendir(path);
319     if (dir)
320     {
321         size_t bufsize = strlen(path) + 1 + PATH_MAX + 1;
322         char *filebuf = CryptMemAlloc(bufsize);
323
324         if (filebuf)
325         {
326             struct dirent *entry;
327             while ((entry = readdir(dir)))
328             {
329                 if (strcmp(entry->d_name, ".") && strcmp(entry->d_name, ".."))
330                 {
331                     snprintf(filebuf, bufsize, "%s/%s", path, entry->d_name);
332                     if (import_certs_from_path(filebuf, store, FALSE) && !ret)
333                         ret = TRUE;
334                 }
335             }
336             closedir(dir);
337             CryptMemFree(filebuf);
338         }
339     }
340     return ret;
341 }
342
343 /* Opens path, which may be a file or a directory, and imports any certificates
344  * it finds into store.
345  * Returns TRUE if any certificates were successfully imported.
346  */
347 static BOOL import_certs_from_path(LPCSTR path, HCERTSTORE store,
348  BOOL allow_dir)
349 {
350     BOOL ret = FALSE;
351     int fd;
352
353     TRACE("(%s, %p, %d)\n", debugstr_a(path), store, allow_dir);
354
355     fd = open(path, O_RDONLY);
356     if (fd != -1)
357     {
358         struct stat st;
359
360         if (fstat(fd, &st) == 0)
361         {
362             if (S_ISREG(st.st_mode))
363                 ret = import_certs_from_file(fd, store);
364             else if (S_ISDIR(st.st_mode))
365             {
366                 if (allow_dir)
367                     ret = import_certs_from_dir(path, store);
368                 else
369                     WARN("%s is a directory and directories are disallowed\n",
370                      debugstr_a(path));
371             }
372             else
373                 ERR("%s: invalid file type\n", path);
374         }
375         close(fd);
376     }
377     return ret;
378 }
379
380 static BOOL WINAPI CRYPT_RootWriteCert(HCERTSTORE hCertStore,
381  PCCERT_CONTEXT cert, DWORD dwFlags)
382 {
383     /* The root store can't have certs added */
384     return FALSE;
385 }
386
387 static BOOL WINAPI CRYPT_RootDeleteCert(HCERTSTORE hCertStore,
388  PCCERT_CONTEXT cert, DWORD dwFlags)
389 {
390     /* The root store can't have certs deleted */
391     return FALSE;
392 }
393
394 static BOOL WINAPI CRYPT_RootWriteCRL(HCERTSTORE hCertStore,
395  PCCRL_CONTEXT crl, DWORD dwFlags)
396 {
397     /* The root store can have CRLs added.  At worst, a malicious application
398      * can DoS itself, as the changes aren't persisted in any way.
399      */
400     return TRUE;
401 }
402
403 static BOOL WINAPI CRYPT_RootDeleteCRL(HCERTSTORE hCertStore,
404  PCCRL_CONTEXT crl, DWORD dwFlags)
405 {
406     /* The root store can't have CRLs deleted */
407     return FALSE;
408 }
409
410 static void *rootProvFuncs[] = {
411     NULL, /* CERT_STORE_PROV_CLOSE_FUNC */
412     NULL, /* CERT_STORE_PROV_READ_CERT_FUNC */
413     CRYPT_RootWriteCert,
414     CRYPT_RootDeleteCert,
415     NULL, /* CERT_STORE_PROV_SET_CERT_PROPERTY_FUNC */
416     NULL, /* CERT_STORE_PROV_READ_CRL_FUNC */
417     CRYPT_RootWriteCRL,
418     CRYPT_RootDeleteCRL,
419     NULL, /* CERT_STORE_PROV_SET_CRL_PROPERTY_FUNC */
420     NULL, /* CERT_STORE_PROV_READ_CTL_FUNC */
421     NULL, /* CERT_STORE_PROV_WRITE_CTL_FUNC */
422     NULL, /* CERT_STORE_PROV_DELETE_CTL_FUNC */
423     NULL, /* CERT_STORE_PROV_SET_CTL_PROPERTY_FUNC */
424     NULL, /* CERT_STORE_PROV_CONTROL_FUNC */
425 };
426
427 static const char * const CRYPT_knownLocations[] = {
428  "/etc/ssl/certs/ca-certificates.crt",
429  "/etc/ssl/certs",
430  "/etc/pki/tls/certs/ca-bundle.crt",
431 };
432
433 /* Reads certificates from the list of known locations.  Stops when any
434  * location contains any certificates, to prevent spending unnecessary time
435  * adding redundant certificates, e.g. when both a certificate bundle and
436  * individual certificates exist in the same directory.
437  */
438 static PWINECRYPT_CERTSTORE CRYPT_RootOpenStoreFromKnownLocations(void)
439 {
440     HCERTSTORE root = NULL;
441     HCERTSTORE from = CertOpenStore(CERT_STORE_PROV_MEMORY,
442      X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
443     HCERTSTORE to = CertOpenStore(CERT_STORE_PROV_MEMORY,
444      X509_ASN_ENCODING, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
445
446     if (from && to)
447     {
448         CERT_STORE_PROV_INFO provInfo = {
449          sizeof(CERT_STORE_PROV_INFO),
450          sizeof(rootProvFuncs) / sizeof(rootProvFuncs[0]),
451          rootProvFuncs,
452          NULL,
453          0,
454          NULL
455         };
456         DWORD i;
457         BOOL ret = FALSE;
458
459         for (i = 0; !ret &&
460          i < sizeof(CRYPT_knownLocations) / sizeof(CRYPT_knownLocations[0]);
461          i++)
462             ret = import_certs_from_path(CRYPT_knownLocations[i], from, TRUE);
463         check_and_store_certs(from, to);
464         root = CRYPT_ProvCreateStore(0, to, &provInfo);
465     }
466     CertCloseStore(from, 0);
467     TRACE("returning %p\n", root);
468     return root;
469 }
470
471 static PWINECRYPT_CERTSTORE CRYPT_rootStore;
472
473 PWINECRYPT_CERTSTORE CRYPT_RootOpenStore(HCRYPTPROV hCryptProv, DWORD dwFlags)
474 {
475     TRACE("(%ld, %08x)\n", hCryptProv, dwFlags);
476
477     if (dwFlags & CERT_STORE_DELETE_FLAG)
478     {
479         WARN("root store can't be deleted\n");
480         SetLastError(ERROR_ACCESS_DENIED);
481         return NULL;
482     }
483     switch (dwFlags & CERT_SYSTEM_STORE_LOCATION_MASK)
484     {
485     case CERT_SYSTEM_STORE_LOCAL_MACHINE:
486     case CERT_SYSTEM_STORE_CURRENT_USER:
487         break;
488     default:
489         TRACE("location %08x unsupported\n",
490          dwFlags & CERT_SYSTEM_STORE_LOCATION_MASK);
491         SetLastError(E_INVALIDARG);
492         return NULL;
493     }
494     if (!CRYPT_rootStore)
495     {
496         HCERTSTORE root = CRYPT_RootOpenStoreFromKnownLocations();
497
498         InterlockedCompareExchangePointer((PVOID *)&CRYPT_rootStore, root,
499          NULL);
500         if (CRYPT_rootStore != root)
501             CertCloseStore(root, 0);
502     }
503     CertDuplicateStore(CRYPT_rootStore);
504     return CRYPT_rootStore;
505 }