crypt32: Fix CryptFreeTls when calling with a freed index.
[wine] / dlls / crypt32 / serialize.c
1 /*
2  * Copyright 2004-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
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #include "windef.h"
24 #include "winbase.h"
25 #include "wincrypt.h"
26 #include "wine/debug.h"
27 #include "wine/exception.h"
28 #include "crypt32_private.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
31
32 /* An extended certificate property in serialized form is prefixed by this
33  * header.
34  */
35 typedef struct _WINE_CERT_PROP_HEADER
36 {
37     DWORD propID;
38     DWORD unknown; /* always 1 */
39     DWORD cb;
40 } WINE_CERT_PROP_HEADER, *PWINE_CERT_PROP_HEADER;
41
42 static BOOL CRYPT_SerializeStoreElement(const void *context,
43  const BYTE *encodedContext, DWORD cbEncodedContext, DWORD contextPropID,
44  PCWINE_CONTEXT_INTERFACE contextInterface, DWORD dwFlags, BOOL omitHashes,
45  BYTE *pbElement, DWORD *pcbElement)
46 {
47     BOOL ret;
48
49     TRACE("(%p, %p, %08x, %d, %p, %p)\n", context, contextInterface, dwFlags,
50      omitHashes, pbElement, pcbElement);
51
52     if (context)
53     {
54         DWORD bytesNeeded = sizeof(WINE_CERT_PROP_HEADER) + cbEncodedContext;
55         DWORD prop = 0;
56
57         ret = TRUE;
58         do {
59             prop = contextInterface->enumProps(context, prop);
60             if (prop && (!omitHashes || !IS_CERT_HASH_PROP_ID(prop)))
61             {
62                 DWORD propSize = 0;
63
64                 ret = contextInterface->getProp(context, prop, NULL, &propSize);
65                 if (ret)
66                     bytesNeeded += sizeof(WINE_CERT_PROP_HEADER) + propSize;
67             }
68         } while (ret && prop != 0);
69
70         if (!pbElement)
71         {
72             *pcbElement = bytesNeeded;
73             ret = TRUE;
74         }
75         else if (*pcbElement < bytesNeeded)
76         {
77             *pcbElement = bytesNeeded;
78             SetLastError(ERROR_MORE_DATA);
79             ret = FALSE;
80         }
81         else
82         {
83             PWINE_CERT_PROP_HEADER hdr;
84             DWORD bufSize = 0;
85             LPBYTE buf = NULL;
86
87             prop = 0;
88             do {
89                 prop = contextInterface->enumProps(context, prop);
90                 if (prop && (!omitHashes || !IS_CERT_HASH_PROP_ID(prop)))
91                 {
92                     DWORD propSize = 0;
93
94                     ret = contextInterface->getProp(context, prop, NULL,
95                      &propSize);
96                     if (ret)
97                     {
98                         if (bufSize < propSize)
99                         {
100                             if (buf)
101                                 buf = CryptMemRealloc(buf, propSize);
102                             else
103                                 buf = CryptMemAlloc(propSize);
104                             bufSize = propSize;
105                         }
106                         if (buf)
107                         {
108                             ret = contextInterface->getProp(context, prop, buf,
109                              &propSize);
110                             if (ret)
111                             {
112                                 hdr = (PWINE_CERT_PROP_HEADER)pbElement;
113                                 hdr->propID = prop;
114                                 hdr->unknown = 1;
115                                 hdr->cb = propSize;
116                                 pbElement += sizeof(WINE_CERT_PROP_HEADER);
117                                 if (propSize)
118                                 {
119                                     memcpy(pbElement, buf, propSize);
120                                     pbElement += propSize;
121                                 }
122                             }
123                         }
124                         else
125                             ret = FALSE;
126                     }
127                 }
128             } while (ret && prop != 0);
129             CryptMemFree(buf);
130
131             hdr = (PWINE_CERT_PROP_HEADER)pbElement;
132             hdr->propID = contextPropID;
133             hdr->unknown = 1;
134             hdr->cb = cbEncodedContext;
135             memcpy(pbElement + sizeof(WINE_CERT_PROP_HEADER),
136              encodedContext, cbEncodedContext);
137         }
138     }
139     else
140         ret = FALSE;
141     return ret;
142 }
143
144 BOOL WINAPI CertSerializeCertificateStoreElement(PCCERT_CONTEXT pCertContext,
145  DWORD dwFlags, BYTE *pbElement, DWORD *pcbElement)
146 {
147     return CRYPT_SerializeStoreElement(pCertContext,
148      pCertContext->pbCertEncoded, pCertContext->cbCertEncoded,
149      CERT_CERT_PROP_ID, pCertInterface, dwFlags, FALSE, pbElement, pcbElement);
150 }
151
152 BOOL WINAPI CertSerializeCRLStoreElement(PCCRL_CONTEXT pCrlContext,
153  DWORD dwFlags, BYTE *pbElement, DWORD *pcbElement)
154 {
155     return CRYPT_SerializeStoreElement(pCrlContext,
156      pCrlContext->pbCrlEncoded, pCrlContext->cbCrlEncoded,
157      CERT_CRL_PROP_ID, pCRLInterface, dwFlags, FALSE, pbElement, pcbElement);
158 }
159
160 BOOL WINAPI CertSerializeCTLStoreElement(PCCTL_CONTEXT pCtlContext,
161  DWORD dwFlags, BYTE *pbElement, DWORD *pcbElement)
162 {
163     return CRYPT_SerializeStoreElement(pCtlContext,
164      pCtlContext->pbCtlEncoded, pCtlContext->cbCtlEncoded,
165      CERT_CTL_PROP_ID, pCTLInterface, dwFlags, FALSE, pbElement, pcbElement);
166 }
167
168 /* Looks for the property with ID propID in the buffer buf.  Returns a pointer
169  * to its header if a valid header is found, NULL if not.  Valid means the
170  * length of thte property won't overrun buf, and the unknown field is 1.
171  */
172 static const WINE_CERT_PROP_HEADER *CRYPT_findPropID(const BYTE *buf,
173  DWORD size, DWORD propID)
174 {
175     const WINE_CERT_PROP_HEADER *ret = NULL;
176     BOOL done = FALSE;
177
178     while (size && !ret && !done)
179     {
180         if (size < sizeof(WINE_CERT_PROP_HEADER))
181         {
182             SetLastError(CRYPT_E_FILE_ERROR);
183             done = TRUE;
184         }
185         else
186         {
187             const WINE_CERT_PROP_HEADER *hdr =
188              (const WINE_CERT_PROP_HEADER *)buf;
189
190             size -= sizeof(WINE_CERT_PROP_HEADER);
191             buf += sizeof(WINE_CERT_PROP_HEADER);
192             if (size < hdr->cb)
193             {
194                 SetLastError(E_INVALIDARG);
195                 done = TRUE;
196             }
197             else if (!hdr->propID)
198             {
199                 /* assume a zero prop ID means the data are uninitialized, so
200                  * stop looking.
201                  */
202                 done = TRUE;
203             }
204             else if (hdr->unknown != 1)
205             {
206                 SetLastError(ERROR_FILE_NOT_FOUND);
207                 done = TRUE;
208             }
209             else if (hdr->propID == propID)
210                 ret = hdr;
211             else
212             {
213                 buf += hdr->cb;
214                 size -= hdr->cb;
215             }
216         }
217     }
218     return ret;
219 }
220
221 static BOOL CRYPT_ReadContextProp(
222  const WINE_CONTEXT_INTERFACE *contextInterface, const void *context,
223  const WINE_CERT_PROP_HEADER *hdr, const BYTE *pbElement, DWORD cbElement)
224 {
225     BOOL ret;
226
227     if (cbElement < hdr->cb)
228     {
229         SetLastError(E_INVALIDARG);
230         ret = FALSE;
231     }
232     else if (hdr->unknown != 1)
233     {
234         SetLastError(ERROR_FILE_NOT_FOUND);
235         ret = FALSE;
236     }
237     else if (hdr->propID != CERT_CERT_PROP_ID &&
238      hdr->propID != CERT_CRL_PROP_ID && hdr->propID != CERT_CTL_PROP_ID)
239     {
240         /* Have to create a blob for most types, but not
241          * for all.. arghh.
242          */
243         switch (hdr->propID)
244         {
245         case CERT_AUTO_ENROLL_PROP_ID:
246         case CERT_CTL_USAGE_PROP_ID:
247         case CERT_DESCRIPTION_PROP_ID:
248         case CERT_FRIENDLY_NAME_PROP_ID:
249         case CERT_HASH_PROP_ID:
250         case CERT_KEY_IDENTIFIER_PROP_ID:
251         case CERT_MD5_HASH_PROP_ID:
252         case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
253         case CERT_PUBKEY_ALG_PARA_PROP_ID:
254         case CERT_PVK_FILE_PROP_ID:
255         case CERT_SIGNATURE_HASH_PROP_ID:
256         case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
257         case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
258         case CERT_ENROLLMENT_PROP_ID:
259         case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
260         case CERT_RENEWAL_PROP_ID:
261         {
262             CRYPT_DATA_BLOB blob = { hdr->cb,
263              (LPBYTE)pbElement };
264
265             ret = contextInterface->setProp(context,
266              hdr->propID, 0, &blob);
267             break;
268         }
269         case CERT_DATE_STAMP_PROP_ID:
270             ret = contextInterface->setProp(context,
271              hdr->propID, 0, pbElement);
272             break;
273         case CERT_KEY_PROV_INFO_PROP_ID:
274         {
275             PCRYPT_KEY_PROV_INFO info =
276              (PCRYPT_KEY_PROV_INFO)pbElement;
277
278             CRYPT_FixKeyProvInfoPointers(info);
279             ret = contextInterface->setProp(context,
280              hdr->propID, 0, pbElement);
281             break;
282         }
283         default:
284             ret = FALSE;
285         }
286     }
287     else
288     {
289         /* ignore the context itself */
290         ret = TRUE;
291     }
292     return ret;
293 }
294
295 const void *CRYPT_ReadSerializedElement(const BYTE *pbElement, DWORD cbElement,
296  DWORD dwContextTypeFlags, DWORD *pdwContentType)
297 {
298     const void *context;
299
300     TRACE("(%p, %d, %08x, %p)\n", pbElement, cbElement, dwContextTypeFlags,
301      pdwContentType);
302
303     if (!cbElement)
304     {
305         SetLastError(ERROR_END_OF_MEDIA);
306         return NULL;
307     }
308
309     __TRY
310     {
311         const WINE_CONTEXT_INTERFACE *contextInterface = NULL;
312         const WINE_CERT_PROP_HEADER *hdr = NULL;
313         DWORD type = 0;
314         BOOL ret;
315
316         ret = TRUE;
317         context = NULL;
318         if (dwContextTypeFlags == CERT_STORE_ALL_CONTEXT_FLAG)
319         {
320             hdr = CRYPT_findPropID(pbElement, cbElement, CERT_CERT_PROP_ID);
321             if (hdr)
322                 type = CERT_STORE_CERTIFICATE_CONTEXT;
323             else
324             {
325                 hdr = CRYPT_findPropID(pbElement, cbElement, CERT_CRL_PROP_ID);
326                 if (hdr)
327                     type = CERT_STORE_CRL_CONTEXT;
328                 else
329                 {
330                     hdr = CRYPT_findPropID(pbElement, cbElement,
331                      CERT_CTL_PROP_ID);
332                     if (hdr)
333                         type = CERT_STORE_CTL_CONTEXT;
334                 }
335             }
336         }
337         else if (dwContextTypeFlags & CERT_STORE_CERTIFICATE_CONTEXT_FLAG)
338         {
339             hdr = CRYPT_findPropID(pbElement, cbElement, CERT_CERT_PROP_ID);
340             type = CERT_STORE_CERTIFICATE_CONTEXT;
341         }
342         else if (dwContextTypeFlags & CERT_STORE_CRL_CONTEXT_FLAG)
343         {
344             hdr = CRYPT_findPropID(pbElement, cbElement, CERT_CRL_PROP_ID);
345             type = CERT_STORE_CRL_CONTEXT;
346         }
347         else if (dwContextTypeFlags & CERT_STORE_CTL_CONTEXT_FLAG)
348         {
349             hdr = CRYPT_findPropID(pbElement, cbElement, CERT_CTL_PROP_ID);
350             type = CERT_STORE_CTL_CONTEXT;
351         }
352
353         switch (type)
354         {
355         case CERT_STORE_CERTIFICATE_CONTEXT:
356             contextInterface = pCertInterface;
357             break;
358         case CERT_STORE_CRL_CONTEXT:
359             contextInterface = pCRLInterface;
360             break;
361         case CERT_STORE_CTL_CONTEXT:
362             contextInterface = pCTLInterface;
363             break;
364         default:
365             SetLastError(E_INVALIDARG);
366             ret = FALSE;
367         }
368         if (!hdr)
369             ret = FALSE;
370
371         if (ret)
372             context = contextInterface->create(X509_ASN_ENCODING,
373              (BYTE *)hdr + sizeof(WINE_CERT_PROP_HEADER), hdr->cb);
374         if (ret && context)
375         {
376             BOOL noMoreProps = FALSE;
377
378             while (!noMoreProps && ret)
379             {
380                 if (cbElement < sizeof(WINE_CERT_PROP_HEADER))
381                     ret = FALSE;
382                 else
383                 {
384                     const WINE_CERT_PROP_HEADER *hdr =
385                      (const WINE_CERT_PROP_HEADER *)pbElement;
386
387                     TRACE("prop is %d\n", hdr->propID);
388                     cbElement -= sizeof(WINE_CERT_PROP_HEADER);
389                     pbElement += sizeof(WINE_CERT_PROP_HEADER);
390                     if (!hdr->propID)
391                     {
392                         /* Like in CRYPT_findPropID, stop if the propID is zero
393                          */
394                         noMoreProps = TRUE;
395                     }
396                     else
397                         ret = CRYPT_ReadContextProp(contextInterface, context,
398                          hdr, pbElement, cbElement);
399                     pbElement += hdr->cb;
400                     cbElement -= hdr->cb;
401                     if (!cbElement)
402                         noMoreProps = TRUE;
403                 }
404             }
405             if (ret)
406             {
407                 if (pdwContentType)
408                     *pdwContentType = type;
409             }
410             else
411             {
412                 contextInterface->free(context);
413                 context = NULL;
414             }
415         }
416     }
417     __EXCEPT_PAGE_FAULT
418     {
419         SetLastError(STATUS_ACCESS_VIOLATION);
420         context = NULL;
421     }
422     __ENDTRY
423     return context;
424 }
425
426 static const BYTE fileHeader[] = { 0, 0, 0, 0, 'C','E','R','T' };
427
428 typedef BOOL (*read_serialized_func)(void *handle, void *buffer,
429  DWORD bytesToRead, DWORD *bytesRead);
430
431 static BOOL CRYPT_ReadSerializedStore(void *handle,
432  read_serialized_func read_func, HCERTSTORE store)
433 {
434     BYTE fileHeaderBuf[sizeof(fileHeader)];
435     DWORD read;
436     BOOL ret;
437
438     /* Failure reading is non-critical, we'll leave the store empty */
439     ret = read_func(handle, fileHeaderBuf, sizeof(fileHeaderBuf), &read);
440     if (ret)
441     {
442         if (!read)
443             ; /* an empty file is okay */
444         else if (read != sizeof(fileHeaderBuf))
445             ret = FALSE;
446         else if (!memcmp(fileHeaderBuf, fileHeader, read))
447         {
448             WINE_CERT_PROP_HEADER propHdr;
449             const void *context = NULL;
450             const WINE_CONTEXT_INTERFACE *contextInterface = NULL;
451             LPBYTE buf = NULL;
452             DWORD bufSize = 0;
453
454             do {
455                 ret = read_func(handle, &propHdr, sizeof(propHdr), &read);
456                 if (ret && read == sizeof(propHdr))
457                 {
458                     if (contextInterface && context &&
459                      (propHdr.propID == CERT_CERT_PROP_ID ||
460                      propHdr.propID == CERT_CRL_PROP_ID ||
461                      propHdr.propID == CERT_CTL_PROP_ID))
462                     {
463                         /* We have a new context, so free the existing one */
464                         contextInterface->free(context);
465                     }
466                     if (propHdr.cb > bufSize)
467                     {
468                         /* Not reusing realloc, because the old data aren't
469                          * needed any longer.
470                          */
471                         CryptMemFree(buf);
472                         buf = CryptMemAlloc(propHdr.cb);
473                         bufSize = propHdr.cb;
474                     }
475                     if (buf)
476                     {
477                         ret = read_func(handle, buf, propHdr.cb, &read);
478                         if (ret && read == propHdr.cb)
479                         {
480                             if (propHdr.propID == CERT_CERT_PROP_ID)
481                             {
482                                 contextInterface = pCertInterface;
483                                 ret = contextInterface->addEncodedToStore(store,
484                                  X509_ASN_ENCODING, buf, read,
485                                  CERT_STORE_ADD_NEW, &context);
486                             }
487                             else if (propHdr.propID == CERT_CRL_PROP_ID)
488                             {
489                                 contextInterface = pCRLInterface;
490                                 ret = contextInterface->addEncodedToStore(store,
491                                  X509_ASN_ENCODING, buf, read,
492                                  CERT_STORE_ADD_NEW, &context);
493                             }
494                             else if (propHdr.propID == CERT_CTL_PROP_ID)
495                             {
496                                 contextInterface = pCTLInterface;
497                                 ret = contextInterface->addEncodedToStore(store,
498                                  X509_ASN_ENCODING, buf, read,
499                                  CERT_STORE_ADD_NEW, &context);
500                             }
501                             else
502                             {
503                                 if (!contextInterface)
504                                 {
505                                     WARN("prop id %d before a context id\n",
506                                      propHdr.propID);
507                                     ret = FALSE;
508                                 }
509                                 else
510                                     ret = CRYPT_ReadContextProp(
511                                      contextInterface, context, &propHdr, buf,
512                                      read);
513                             }
514                         }
515                     }
516                     else
517                         ret = FALSE;
518                 }
519             } while (ret && read > 0);
520             if (contextInterface && context)
521             {
522                 /* Free the last context added */
523                 contextInterface->free(context);
524             }
525             CryptMemFree(buf);
526             ret = TRUE;
527         }
528         else
529             ret = FALSE;
530     }
531     else
532         ret = TRUE;
533     return ret;
534 }
535
536 static BOOL read_file_wrapper(void *handle, void *buffer, DWORD bytesToRead,
537  DWORD *bytesRead)
538 {
539     return ReadFile(handle, buffer, bytesToRead, bytesRead, NULL);
540 }
541
542 BOOL CRYPT_ReadSerializedStoreFromFile(HANDLE file, HCERTSTORE store)
543 {
544     return CRYPT_ReadSerializedStore(file, read_file_wrapper, store);
545 }
546
547 struct BlobReader
548 {
549     const CRYPT_DATA_BLOB *blob;
550     DWORD current;
551 };
552
553 static BOOL read_blob_wrapper(void *handle, void *buffer, DWORD bytesToRead,
554  DWORD *bytesRead)
555 {
556     struct BlobReader *reader = handle;
557     BOOL ret;
558
559     if (reader->current < reader->blob->cbData)
560     {
561         *bytesRead = min(bytesToRead, reader->blob->cbData - reader->current);
562         memcpy(buffer, reader->blob->pbData + reader->current, *bytesRead);
563         ret = TRUE;
564     }
565     else
566         ret = FALSE;
567     return ret;
568 }
569
570 BOOL CRYPT_ReadSerializedStoreFromBlob(const CRYPT_DATA_BLOB *blob,
571  HCERTSTORE store)
572 {
573     struct BlobReader reader = { blob, 0 };
574
575     return CRYPT_ReadSerializedStore(&reader, read_blob_wrapper, store);
576 }
577
578 static BOOL WINAPI CRYPT_SerializeCertNoHash(PCCERT_CONTEXT pCertContext,
579  DWORD dwFlags, BYTE *pbElement, DWORD *pcbElement)
580 {
581     return CRYPT_SerializeStoreElement(pCertContext,
582      pCertContext->pbCertEncoded, pCertContext->cbCertEncoded,
583      CERT_CERT_PROP_ID, pCertInterface, dwFlags, TRUE, pbElement, pcbElement);
584 }
585
586 static BOOL WINAPI CRYPT_SerializeCRLNoHash(PCCRL_CONTEXT pCrlContext,
587  DWORD dwFlags, BYTE *pbElement, DWORD *pcbElement)
588 {
589     return CRYPT_SerializeStoreElement(pCrlContext,
590      pCrlContext->pbCrlEncoded, pCrlContext->cbCrlEncoded,
591      CERT_CRL_PROP_ID, pCRLInterface, dwFlags, TRUE, pbElement, pcbElement);
592 }
593
594 static BOOL WINAPI CRYPT_SerializeCTLNoHash(PCCTL_CONTEXT pCtlContext,
595  DWORD dwFlags, BYTE *pbElement, DWORD *pcbElement)
596 {
597     return CRYPT_SerializeStoreElement(pCtlContext,
598      pCtlContext->pbCtlEncoded, pCtlContext->cbCtlEncoded,
599      CERT_CTL_PROP_ID, pCTLInterface, dwFlags, TRUE, pbElement, pcbElement);
600 }
601
602 typedef BOOL (*SerializedOutputFunc)(void *handle, const void *buffer,
603  DWORD size);
604
605 static BOOL CRYPT_SerializeContextsToStream(SerializedOutputFunc output,
606  void *handle, const WINE_CONTEXT_INTERFACE *contextInterface, HCERTSTORE store)
607 {
608     const void *context = NULL;
609     BOOL ret;
610
611     do {
612         context = contextInterface->enumContextsInStore(store, context);
613         if (context)
614         {
615             DWORD size = 0;
616             LPBYTE buf = NULL;
617
618             ret = contextInterface->serialize(context, 0, NULL, &size);
619             if (size)
620                 buf = CryptMemAlloc(size);
621             if (buf)
622             {
623                 ret = contextInterface->serialize(context, 0, buf, &size);
624                 if (ret)
625                     ret = output(handle, buf, size);
626             }
627             CryptMemFree(buf);
628         }
629         else
630             ret = TRUE;
631     } while (ret && context != NULL);
632     if (context)
633         contextInterface->free(context);
634     return ret;
635 }
636
637 static BOOL CRYPT_WriteSerializedStoreToStream(HCERTSTORE store,
638  SerializedOutputFunc output, void *handle)
639 {
640     static const BYTE fileTrailer[12] = { 0 };
641     WINE_CONTEXT_INTERFACE interface;
642     BOOL ret;
643
644     ret = output(handle, fileHeader, sizeof(fileHeader));
645     if (ret)
646     {
647         memcpy(&interface, pCertInterface, sizeof(interface));
648         interface.serialize = (SerializeElementFunc)CRYPT_SerializeCertNoHash;
649         ret = CRYPT_SerializeContextsToStream(output, handle, &interface,
650          store);
651     }
652     if (ret)
653     {
654         memcpy(&interface, pCRLInterface, sizeof(interface));
655         interface.serialize = (SerializeElementFunc)CRYPT_SerializeCRLNoHash;
656         ret = CRYPT_SerializeContextsToStream(output, handle, &interface,
657          store);
658     }
659     if (ret)
660     {
661         memcpy(&interface, pCTLInterface, sizeof(interface));
662         interface.serialize = (SerializeElementFunc)CRYPT_SerializeCTLNoHash;
663         ret = CRYPT_SerializeContextsToStream(output, handle, &interface,
664          store);
665     }
666     if (ret)
667         ret = output(handle, fileTrailer, sizeof(fileTrailer));
668     return ret;
669 }
670
671 static BOOL CRYPT_FileOutputFunc(void *handle, const void *buffer, DWORD size)
672 {
673     return WriteFile(handle, buffer, size, &size, NULL);
674 }
675
676 static BOOL CRYPT_WriteSerializedStoreToFile(HANDLE file, HCERTSTORE store)
677 {
678     SetFilePointer(file, 0, NULL, FILE_BEGIN);
679     return CRYPT_WriteSerializedStoreToStream(store, CRYPT_FileOutputFunc,
680      file);
681 }
682
683 static BOOL CRYPT_SavePKCSToMem(HCERTSTORE store,
684  DWORD dwMsgAndCertEncodingType, void *handle)
685 {
686     CERT_BLOB *blob = handle;
687     CRYPT_SIGNED_INFO signedInfo = { 0 };
688     PCCERT_CONTEXT cert = NULL;
689     PCCRL_CONTEXT crl = NULL;
690     DWORD size;
691     BOOL ret = TRUE;
692
693     TRACE("(%d, %p)\n", blob->pbData ? blob->cbData : 0, blob->pbData);
694
695     do {
696         cert = CertEnumCertificatesInStore(store, cert);
697         if (cert)
698             signedInfo.cCertEncoded++;
699     } while (cert);
700     if (signedInfo.cCertEncoded)
701     {
702         signedInfo.rgCertEncoded = CryptMemAlloc(
703          signedInfo.cCertEncoded * sizeof(CERT_BLOB));
704         if (!signedInfo.rgCertEncoded)
705         {
706             SetLastError(ERROR_OUTOFMEMORY);
707             ret = FALSE;
708         }
709         else
710         {
711             DWORD i = 0;
712
713             do {
714                 cert = CertEnumCertificatesInStore(store, cert);
715                 if (cert)
716                 {
717                     signedInfo.rgCertEncoded[i].cbData = cert->cbCertEncoded;
718                     signedInfo.rgCertEncoded[i].pbData = cert->pbCertEncoded;
719                     i++;
720                 }
721             } while (cert);
722         }
723     }
724
725     do {
726         crl = CertEnumCRLsInStore(store, crl);
727         if (crl)
728             signedInfo.cCrlEncoded++;
729     } while (crl);
730     if (signedInfo.cCrlEncoded)
731     {
732         signedInfo.rgCrlEncoded = CryptMemAlloc(
733          signedInfo.cCrlEncoded * sizeof(CERT_BLOB));
734         if (!signedInfo.rgCrlEncoded)
735         {
736             SetLastError(ERROR_OUTOFMEMORY);
737             ret = FALSE;
738         }
739         else
740         {
741             DWORD i = 0;
742
743             do {
744                 crl = CertEnumCRLsInStore(store, crl);
745                 if (crl)
746                 {
747                     signedInfo.rgCrlEncoded[i].cbData = crl->cbCrlEncoded;
748                     signedInfo.rgCrlEncoded[i].pbData = crl->pbCrlEncoded;
749                     i++;
750                 }
751             } while (crl);
752         }
753     }
754     if (ret)
755     {
756         ret = CRYPT_AsnEncodeCMSSignedInfo(&signedInfo, NULL, &size);
757         if (ret)
758         {
759             if (!blob->pbData)
760                 blob->cbData = size;
761             else if (blob->cbData < size)
762             {
763                 blob->cbData = size;
764                 SetLastError(ERROR_MORE_DATA);
765                 ret = FALSE;
766             }
767             else
768             {
769                 blob->cbData = size;
770                 ret = CRYPT_AsnEncodeCMSSignedInfo(&signedInfo, blob->pbData,
771                  &blob->cbData);
772             }
773         }
774     }
775     CryptMemFree(signedInfo.rgCertEncoded);
776     CryptMemFree(signedInfo.rgCrlEncoded);
777     TRACE("returning %d\n", ret);
778     return ret;
779 }
780
781 static BOOL CRYPT_SavePKCSToFile(HCERTSTORE store,
782  DWORD dwMsgAndCertEncodingType, void *handle)
783 {
784     CERT_BLOB blob = { 0, NULL };
785     BOOL ret;
786
787     TRACE("(%p)\n", handle);
788
789     ret = CRYPT_SavePKCSToMem(store, dwMsgAndCertEncodingType, &blob);
790     if (ret)
791     {
792         blob.pbData = CryptMemAlloc(blob.cbData);
793         if (blob.pbData)
794         {
795             ret = CRYPT_SavePKCSToMem(store, dwMsgAndCertEncodingType, &blob);
796             if (ret)
797                 ret = WriteFile(handle, blob.pbData, blob.cbData,
798                  &blob.cbData, NULL);
799         }
800         else
801         {
802             SetLastError(ERROR_OUTOFMEMORY);
803             ret = FALSE;
804         }
805     }
806     TRACE("returning %d\n", ret);
807     return ret;
808 }
809
810 static BOOL CRYPT_SaveSerializedToFile(HCERTSTORE store,
811  DWORD dwMsgAndCertEncodingType, void *handle)
812 {
813     return CRYPT_WriteSerializedStoreToFile(handle, store);
814 }
815
816 struct MemWrittenTracker
817 {
818     DWORD cbData;
819     BYTE *pbData;
820     DWORD written;
821 };
822
823 /* handle is a pointer to a MemWrittenTracker.  Assumes its pointer is valid. */
824 static BOOL CRYPT_MemOutputFunc(void *handle, const void *buffer, DWORD size)
825 {
826     struct MemWrittenTracker *tracker = handle;
827     BOOL ret;
828
829     if (tracker->written + size > tracker->cbData)
830     {
831         SetLastError(ERROR_MORE_DATA);
832         /* Update written so caller can notify its caller of the required size
833          */
834         tracker->written += size;
835         ret = FALSE;
836     }
837     else
838     {
839         memcpy(tracker->pbData + tracker->written, buffer, size);
840         tracker->written += size;
841         ret = TRUE;
842     }
843     return ret;
844 }
845
846 static BOOL CRYPT_CountSerializedBytes(void *handle, const void *buffer,
847  DWORD size)
848 {
849     *(DWORD *)handle += size;
850     return TRUE;
851 }
852
853 static BOOL CRYPT_SaveSerializedToMem(HCERTSTORE store,
854  DWORD dwMsgAndCertEncodingType, void *handle)
855 {
856     CERT_BLOB *blob = handle;
857     DWORD size = 0;
858     BOOL ret;
859
860     ret = CRYPT_WriteSerializedStoreToStream(store, CRYPT_CountSerializedBytes,
861      &size);
862     if (ret)
863     {
864         if (!blob->pbData)
865             blob->cbData = size;
866         else if (blob->cbData < size)
867         {
868             SetLastError(ERROR_MORE_DATA);
869             blob->cbData = size;
870             ret = FALSE;
871         }
872         else
873         {
874             struct MemWrittenTracker tracker = { blob->cbData, blob->pbData,
875              0 };
876
877             ret = CRYPT_WriteSerializedStoreToStream(store, CRYPT_MemOutputFunc,
878              &tracker);
879             if (!ret && GetLastError() == ERROR_MORE_DATA)
880                 blob->cbData = tracker.written;
881         }
882     }
883     TRACE("returning %d\n", ret);
884     return ret;
885 }
886
887 BOOL WINAPI CertSaveStore(HCERTSTORE hCertStore, DWORD dwMsgAndCertEncodingType,
888  DWORD dwSaveAs, DWORD dwSaveTo, void *pvSaveToPara, DWORD dwFlags)
889 {
890     BOOL (*saveFunc)(HCERTSTORE, DWORD, void *);
891     void *handle;
892     BOOL ret, closeFile = TRUE;
893
894     TRACE("(%p, %08x, %d, %d, %p, %08x)\n", hCertStore,
895           dwMsgAndCertEncodingType, dwSaveAs, dwSaveTo, pvSaveToPara, dwFlags);
896
897     switch (dwSaveAs)
898     {
899     case CERT_STORE_SAVE_AS_STORE:
900         if (dwSaveTo == CERT_STORE_SAVE_TO_MEMORY)
901             saveFunc = CRYPT_SaveSerializedToMem;
902         else
903             saveFunc = CRYPT_SaveSerializedToFile;
904         break;
905     case CERT_STORE_SAVE_AS_PKCS7:
906         if (dwSaveTo == CERT_STORE_SAVE_TO_MEMORY)
907             saveFunc = CRYPT_SavePKCSToMem;
908         else
909             saveFunc = CRYPT_SavePKCSToFile;
910         break;
911     default:
912         WARN("unimplemented for %d\n", dwSaveAs);
913         SetLastError(ERROR_INVALID_PARAMETER);
914         return FALSE;
915     }
916     switch (dwSaveTo)
917     {
918     case CERT_STORE_SAVE_TO_FILE:
919         handle = pvSaveToPara;
920         closeFile = FALSE;
921         break;
922     case CERT_STORE_SAVE_TO_FILENAME_A:
923         handle = CreateFileA(pvSaveToPara, GENERIC_WRITE, 0, NULL,
924          CREATE_ALWAYS, 0, NULL);
925         break;
926     case CERT_STORE_SAVE_TO_FILENAME_W:
927         handle = CreateFileW(pvSaveToPara, GENERIC_WRITE, 0, NULL,
928          CREATE_ALWAYS, 0, NULL);
929         break;
930     case CERT_STORE_SAVE_TO_MEMORY:
931         handle = pvSaveToPara;
932         break;
933     default:
934         WARN("unimplemented for %d\n", dwSaveTo);
935         SetLastError(ERROR_INVALID_PARAMETER);
936         return FALSE;
937     }
938     ret = saveFunc(hCertStore, dwMsgAndCertEncodingType, handle);
939     if (closeFile)
940         CloseHandle(handle);
941     TRACE("returning %d\n", ret);
942     return ret;
943 }
944
945 BOOL WINAPI CertAddSerializedElementToStore(HCERTSTORE hCertStore,
946  const BYTE *pbElement, DWORD cbElement, DWORD dwAddDisposition, DWORD dwFlags,
947  DWORD dwContextTypeFlags, DWORD *pdwContentType, const void **ppvContext)
948 {
949     const void *context;
950     DWORD type;
951     BOOL ret;
952
953     TRACE("(%p, %p, %d, %08x, %08x, %08x, %p, %p)\n", hCertStore,
954      pbElement, cbElement, dwAddDisposition, dwFlags, dwContextTypeFlags,
955      pdwContentType, ppvContext);
956
957     /* Call the internal function, then delete the hashes.  Tests show this
958      * function uses real hash values, not whatever's stored in the hash
959      * property.
960      */
961     context = CRYPT_ReadSerializedElement(pbElement, cbElement,
962      dwContextTypeFlags, &type);
963     if (context)
964     {
965         const WINE_CONTEXT_INTERFACE *contextInterface = NULL;
966
967         switch (type)
968         {
969         case CERT_STORE_CERTIFICATE_CONTEXT:
970             contextInterface = pCertInterface;
971             break;
972         case CERT_STORE_CRL_CONTEXT:
973             contextInterface = pCRLInterface;
974             break;
975         case CERT_STORE_CTL_CONTEXT:
976             contextInterface = pCTLInterface;
977             break;
978         default:
979             SetLastError(E_INVALIDARG);
980         }
981         if (contextInterface)
982         {
983             contextInterface->setProp(context, CERT_HASH_PROP_ID, 0, NULL);
984             contextInterface->setProp(context, CERT_MD5_HASH_PROP_ID, 0, NULL);
985             contextInterface->setProp(context, CERT_SIGNATURE_HASH_PROP_ID, 0,
986              NULL);
987             if (pdwContentType)
988                 *pdwContentType = type;
989             ret = contextInterface->addContextToStore(hCertStore, context,
990              dwAddDisposition, ppvContext);
991             contextInterface->free(context);
992         }
993         else
994             ret = FALSE;
995     }
996     else
997         ret = FALSE;
998     return ret;
999 }