crypt32: Add/improve some traces.
[wine] / dlls / crypt32 / msg.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 <stdarg.h>
19 #include "windef.h"
20 #include "winbase.h"
21 #include "wincrypt.h"
22 #include "snmp.h"
23
24 #include "wine/debug.h"
25 #include "wine/exception.h"
26 #include "crypt32_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
29
30 /* Called when a message's ref count reaches zero.  Free any message-specific
31  * data here.
32  */
33 typedef void (*CryptMsgCloseFunc)(HCRYPTMSG msg);
34
35 typedef BOOL (*CryptMsgGetParamFunc)(HCRYPTMSG hCryptMsg, DWORD dwParamType,
36  DWORD dwIndex, void *pvData, DWORD *pcbData);
37
38 typedef BOOL (*CryptMsgUpdateFunc)(HCRYPTMSG hCryptMsg, const BYTE *pbData,
39  DWORD cbData, BOOL fFinal);
40
41 typedef BOOL (*CryptMsgControlFunc)(HCRYPTMSG hCryptMsg, DWORD dwFlags,
42  DWORD dwCtrlType, const void *pvCtrlPara);
43
44 BOOL CRYPT_DefaultMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
45  DWORD dwCtrlType, const void *pvCtrlPara)
46 {
47     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
48     SetLastError(E_INVALIDARG);
49     return FALSE;
50 }
51
52 typedef enum _CryptMsgState {
53     MsgStateInit,
54     MsgStateUpdated,
55     MsgStateFinalized
56 } CryptMsgState;
57
58 typedef struct _CryptMsgBase
59 {
60     LONG                 ref;
61     DWORD                open_flags;
62     BOOL                 streamed;
63     CMSG_STREAM_INFO     stream_info;
64     CryptMsgState        state;
65     CryptMsgCloseFunc    close;
66     CryptMsgUpdateFunc   update;
67     CryptMsgGetParamFunc get_param;
68     CryptMsgControlFunc  control;
69 } CryptMsgBase;
70
71 static inline void CryptMsgBase_Init(CryptMsgBase *msg, DWORD dwFlags,
72  PCMSG_STREAM_INFO pStreamInfo, CryptMsgCloseFunc close,
73  CryptMsgGetParamFunc get_param, CryptMsgUpdateFunc update,
74  CryptMsgControlFunc control)
75 {
76     msg->ref = 1;
77     msg->open_flags = dwFlags;
78     if (pStreamInfo)
79     {
80         msg->streamed = TRUE;
81         memcpy(&msg->stream_info, pStreamInfo, sizeof(msg->stream_info));
82     }
83     else
84     {
85         msg->streamed = FALSE;
86         memset(&msg->stream_info, 0, sizeof(msg->stream_info));
87     }
88     msg->close = close;
89     msg->get_param = get_param;
90     msg->update = update;
91     msg->control = control;
92     msg->state = MsgStateInit;
93 }
94
95 typedef struct _CDataEncodeMsg
96 {
97     CryptMsgBase base;
98     DWORD        bare_content_len;
99     LPBYTE       bare_content;
100 } CDataEncodeMsg;
101
102 static const BYTE empty_data_content[] = { 0x04,0x00 };
103
104 static void CDataEncodeMsg_Close(HCRYPTMSG hCryptMsg)
105 {
106     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
107
108     if (msg->bare_content != empty_data_content)
109         LocalFree(msg->bare_content);
110 }
111
112 static WINAPI BOOL CRYPT_EncodeContentLength(DWORD dwCertEncodingType,
113  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
114  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
115 {
116     DWORD dataLen = *(DWORD *)pvStructInfo;
117     DWORD lenBytes;
118     BOOL ret = TRUE;
119
120     /* Trick:  report bytes needed based on total message length, even though
121      * the message isn't available yet.  The caller will use the length
122      * reported here to encode its length.
123      */
124     CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
125     if (!pbEncoded)
126         *pcbEncoded = 1 + lenBytes + dataLen;
127     else
128     {
129         if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
130          pcbEncoded, 1 + lenBytes)))
131         {
132             if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
133                 pbEncoded = *(BYTE **)pbEncoded;
134             *pbEncoded++ = ASN_OCTETSTRING;
135             CRYPT_EncodeLen(dataLen, pbEncoded,
136              &lenBytes);
137         }
138     }
139     return ret;
140 }
141
142 static BOOL CRYPT_EncodeDataContentInfoHeader(CDataEncodeMsg *msg,
143  CRYPT_DATA_BLOB *header)
144 {
145     BOOL ret;
146
147     if (msg->base.streamed && msg->base.stream_info.cbContent == 0xffffffff)
148     {
149         static const BYTE headerValue[] = { 0x30,0x80,0x06,0x09,0x2a,0x86,0x48,
150          0x86,0xf7,0x0d,0x01,0x07,0x01,0xa0,0x80,0x24,0x80 };
151
152         header->pbData = LocalAlloc(0, sizeof(headerValue));
153         if (header->pbData)
154         {
155             header->cbData = sizeof(headerValue);
156             memcpy(header->pbData, headerValue, sizeof(headerValue));
157             ret = TRUE;
158         }
159         else
160             ret = FALSE;
161     }
162     else
163     {
164         struct AsnConstructedItem constructed = { 0,
165          &msg->base.stream_info.cbContent, CRYPT_EncodeContentLength };
166         struct AsnEncodeSequenceItem items[2] = {
167          { szOID_RSA_data, CRYPT_AsnEncodeOid, 0 },
168          { &constructed,   CRYPT_AsnEncodeConstructed, 0 },
169         };
170
171         ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
172          sizeof(items) / sizeof(items[0]), CRYPT_ENCODE_ALLOC_FLAG, NULL,
173          (LPBYTE)&header->pbData, &header->cbData);
174         if (ret)
175         {
176             /* Trick:  subtract the content length from the reported length,
177              * as the actual content hasn't come yet.
178              */
179             header->cbData -= msg->base.stream_info.cbContent;
180         }
181     }
182     return ret;
183 }
184
185 static BOOL CDataEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
186  DWORD cbData, BOOL fFinal)
187 {
188     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
189     BOOL ret = FALSE;
190
191     if (msg->base.streamed)
192     {
193         __TRY
194         {
195             if (msg->base.state != MsgStateUpdated)
196             {
197                 CRYPT_DATA_BLOB header;
198
199                 ret = CRYPT_EncodeDataContentInfoHeader(msg, &header);
200                 if (ret)
201                 {
202                     ret = msg->base.stream_info.pfnStreamOutput(
203                      msg->base.stream_info.pvArg, header.pbData, header.cbData,
204                      FALSE);
205                     LocalFree(header.pbData);
206                 }
207             }
208             /* Curiously, every indefinite-length streamed update appears to
209              * get its own tag and length, regardless of fFinal.
210              */
211             if (msg->base.stream_info.cbContent == 0xffffffff)
212             {
213                 BYTE *header;
214                 DWORD headerLen;
215
216                 ret = CRYPT_EncodeContentLength(X509_ASN_ENCODING, NULL,
217                  &cbData, CRYPT_ENCODE_ALLOC_FLAG, NULL, (BYTE *)&header,
218                  &headerLen);
219                 if (ret)
220                 {
221                     ret = msg->base.stream_info.pfnStreamOutput(
222                      msg->base.stream_info.pvArg, header, headerLen,
223                      FALSE);
224                     LocalFree(header);
225                 }
226             }
227             if (!fFinal)
228                 ret = msg->base.stream_info.pfnStreamOutput(
229                  msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
230                  FALSE);
231             else
232             {
233                 if (msg->base.stream_info.cbContent == 0xffffffff)
234                 {
235                     BYTE indefinite_trailer[6] = { 0 };
236
237                     ret = msg->base.stream_info.pfnStreamOutput(
238                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
239                      FALSE);
240                     if (ret)
241                         ret = msg->base.stream_info.pfnStreamOutput(
242                          msg->base.stream_info.pvArg, indefinite_trailer,
243                          sizeof(indefinite_trailer), TRUE);
244                 }
245                 else
246                     ret = msg->base.stream_info.pfnStreamOutput(
247                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData, TRUE);
248             }
249         }
250         __EXCEPT_PAGE_FAULT
251         {
252             SetLastError(STATUS_ACCESS_VIOLATION);
253             ret = FALSE;
254         }
255         __ENDTRY;
256     }
257     else
258     {
259         if (!fFinal)
260         {
261             if (msg->base.open_flags & CMSG_DETACHED_FLAG)
262                 SetLastError(E_INVALIDARG);
263             else
264                 SetLastError(CRYPT_E_MSG_ERROR);
265         }
266         else
267         {
268             if (!cbData)
269                 SetLastError(E_INVALIDARG);
270             else
271             {
272                 CRYPT_DATA_BLOB blob = { cbData, (LPBYTE)pbData };
273
274                 /* non-streamed data messages don't allow non-final updates,
275                  * don't bother checking whether data already exist, they can't.
276                  */
277                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
278                  &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &msg->bare_content,
279                  &msg->bare_content_len);
280             }
281         }
282     }
283     return ret;
284 }
285
286 static BOOL CRYPT_CopyParam(void *pvData, DWORD *pcbData, const void *src,
287  DWORD len)
288 {
289     BOOL ret = TRUE;
290
291     if (!pvData)
292         *pcbData = len;
293     else if (*pcbData < len)
294     {
295         *pcbData = len;
296         SetLastError(ERROR_MORE_DATA);
297         ret = FALSE;
298     }
299     else
300     {
301         *pcbData = len;
302         memcpy(pvData, src, len);
303     }
304     return ret;
305 }
306
307 static BOOL CDataEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
308  DWORD dwIndex, void *pvData, DWORD *pcbData)
309 {
310     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
311     BOOL ret = FALSE;
312
313     switch (dwParamType)
314     {
315     case CMSG_CONTENT_PARAM:
316         if (msg->base.streamed)
317             SetLastError(E_INVALIDARG);
318         else
319         {
320             CRYPT_CONTENT_INFO info;
321             char rsa_data[] = "1.2.840.113549.1.7.1";
322
323             info.pszObjId = rsa_data;
324             info.Content.cbData = msg->bare_content_len;
325             info.Content.pbData = msg->bare_content;
326             ret = CryptEncodeObject(X509_ASN_ENCODING, PKCS_CONTENT_INFO, &info,
327              pvData, pcbData);
328         }
329         break;
330     case CMSG_BARE_CONTENT_PARAM:
331         if (msg->base.streamed)
332             SetLastError(E_INVALIDARG);
333         else
334             ret = CRYPT_CopyParam(pvData, pcbData, msg->bare_content,
335              msg->bare_content_len);
336         break;
337     default:
338         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
339     }
340     return ret;
341 }
342
343 static HCRYPTMSG CDataEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
344  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
345 {
346     CDataEncodeMsg *msg;
347
348     if (pvMsgEncodeInfo)
349     {
350         SetLastError(E_INVALIDARG);
351         return NULL;
352     }
353     msg = CryptMemAlloc(sizeof(CDataEncodeMsg));
354     if (msg)
355     {
356         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
357          CDataEncodeMsg_Close, CDataEncodeMsg_GetParam, CDataEncodeMsg_Update,
358          CRYPT_DefaultMsgControl);
359         msg->bare_content_len = sizeof(empty_data_content);
360         msg->bare_content = (LPBYTE)empty_data_content;
361     }
362     return (HCRYPTMSG)msg;
363 }
364
365 typedef struct _CHashEncodeMsg
366 {
367     CryptMsgBase    base;
368     HCRYPTPROV      prov;
369     HCRYPTHASH      hash;
370     CRYPT_DATA_BLOB data;
371 } CHashEncodeMsg;
372
373 static void CHashEncodeMsg_Close(HCRYPTMSG hCryptMsg)
374 {
375     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
376
377     CryptMemFree(msg->data.pbData);
378     CryptDestroyHash(msg->hash);
379     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
380         CryptReleaseContext(msg->prov, 0);
381 }
382
383 static BOOL CRYPT_EncodePKCSDigestedData(CHashEncodeMsg *msg, void *pvData,
384  DWORD *pcbData)
385 {
386     BOOL ret;
387     ALG_ID algID;
388     DWORD size = sizeof(algID);
389
390     ret = CryptGetHashParam(msg->hash, HP_ALGID, (BYTE *)&algID, &size, 0);
391     if (ret)
392     {
393         CRYPT_DIGESTED_DATA digestedData = { 0 };
394         char oid_rsa_data[] = szOID_RSA_data;
395
396         digestedData.version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
397         digestedData.DigestAlgorithm.pszObjId = (LPSTR)CertAlgIdToOID(algID);
398         /* FIXME: what about digestedData.DigestAlgorithm.Parameters? */
399         /* Quirk:  OID is only encoded messages if an update has happened */
400         if (msg->base.state != MsgStateInit)
401             digestedData.ContentInfo.pszObjId = oid_rsa_data;
402         if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->data.cbData)
403         {
404             ret = CRYPT_AsnEncodeOctets(0, NULL, &msg->data,
405              CRYPT_ENCODE_ALLOC_FLAG, NULL,
406              (LPBYTE)&digestedData.ContentInfo.Content.pbData,
407              &digestedData.ContentInfo.Content.cbData);
408         }
409         if (msg->base.state == MsgStateFinalized)
410         {
411             size = sizeof(DWORD);
412             ret = CryptGetHashParam(msg->hash, HP_HASHSIZE,
413              (LPBYTE)&digestedData.hash.cbData, &size, 0);
414             if (ret)
415             {
416                 digestedData.hash.pbData = CryptMemAlloc(
417                  digestedData.hash.cbData);
418                 ret = CryptGetHashParam(msg->hash, HP_HASHVAL,
419                  digestedData.hash.pbData, &digestedData.hash.cbData, 0);
420             }
421         }
422         if (ret)
423             ret = CRYPT_AsnEncodePKCSDigestedData(&digestedData, pvData,
424              pcbData);
425         CryptMemFree(digestedData.hash.pbData);
426         LocalFree(digestedData.ContentInfo.Content.pbData);
427     }
428     return ret;
429 }
430
431 static BOOL CHashEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
432  DWORD dwIndex, void *pvData, DWORD *pcbData)
433 {
434     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
435     BOOL ret = FALSE;
436
437     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
438      pvData, pcbData);
439
440     switch (dwParamType)
441     {
442     case CMSG_BARE_CONTENT_PARAM:
443         if (msg->base.streamed)
444             SetLastError(E_INVALIDARG);
445         else
446             ret = CRYPT_EncodePKCSDigestedData(msg, pvData, pcbData);
447         break;
448     case CMSG_CONTENT_PARAM:
449     {
450         CRYPT_CONTENT_INFO info;
451
452         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
453          &info.Content.cbData);
454         if (ret)
455         {
456             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
457             if (info.Content.pbData)
458             {
459                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
460                  info.Content.pbData, &info.Content.cbData);
461                 if (ret)
462                 {
463                     char oid_rsa_hashed[] = szOID_RSA_hashedData;
464
465                     info.pszObjId = oid_rsa_hashed;
466                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
467                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
468                 }
469                 CryptMemFree(info.Content.pbData);
470             }
471             else
472                 ret = FALSE;
473         }
474         break;
475     }
476     case CMSG_COMPUTED_HASH_PARAM:
477         ret = CryptGetHashParam(msg->hash, HP_HASHVAL, (BYTE *)pvData, pcbData,
478          0);
479         break;
480     case CMSG_VERSION_PARAM:
481         if (msg->base.state != MsgStateFinalized)
482             SetLastError(CRYPT_E_MSG_ERROR);
483         else
484         {
485             DWORD version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
486
487             /* Since the data are always encoded as octets, the version is
488              * always 0 (see rfc3852, section 7)
489              */
490             ret = CRYPT_CopyParam(pvData, pcbData, &version, sizeof(version));
491         }
492         break;
493     default:
494         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
495     }
496     return ret;
497 }
498
499 static BOOL CHashEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
500  DWORD cbData, BOOL fFinal)
501 {
502     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
503     BOOL ret = FALSE;
504
505     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
506
507     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
508     {
509         /* Doesn't do much, as stream output is never called, and you
510          * can't get the content.
511          */
512         ret = CryptHashData(msg->hash, pbData, cbData, 0);
513     }
514     else
515     {
516         if (!fFinal)
517             SetLastError(CRYPT_E_MSG_ERROR);
518         else
519         {
520             ret = CryptHashData(msg->hash, pbData, cbData, 0);
521             if (ret)
522             {
523                 msg->data.pbData = CryptMemAlloc(cbData);
524                 if (msg->data.pbData)
525                 {
526                     memcpy(msg->data.pbData + msg->data.cbData, pbData, cbData);
527                     msg->data.cbData += cbData;
528                 }
529                 else
530                     ret = FALSE;
531             }
532         }
533     }
534     return ret;
535 }
536
537 static HCRYPTMSG CHashEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
538  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
539 {
540     CHashEncodeMsg *msg;
541     const CMSG_HASHED_ENCODE_INFO *info =
542      (const CMSG_HASHED_ENCODE_INFO *)pvMsgEncodeInfo;
543     HCRYPTPROV prov;
544     ALG_ID algID;
545
546     if (info->cbSize != sizeof(CMSG_HASHED_ENCODE_INFO))
547     {
548         SetLastError(E_INVALIDARG);
549         return NULL;
550     }
551     if (!(algID = CertOIDToAlgId(info->HashAlgorithm.pszObjId)))
552     {
553         SetLastError(CRYPT_E_UNKNOWN_ALGO);
554         return NULL;
555     }
556     if (info->hCryptProv)
557         prov = info->hCryptProv;
558     else
559     {
560         prov = CRYPT_GetDefaultProvider();
561         dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
562     }
563     msg = CryptMemAlloc(sizeof(CHashEncodeMsg));
564     if (msg)
565     {
566         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
567          CHashEncodeMsg_Close, CHashEncodeMsg_GetParam, CHashEncodeMsg_Update,
568          CRYPT_DefaultMsgControl);
569         msg->prov = prov;
570         msg->data.cbData = 0;
571         msg->data.pbData = NULL;
572         if (!CryptCreateHash(prov, algID, 0, 0, &msg->hash))
573         {
574             CryptMsgClose(msg);
575             msg = NULL;
576         }
577     }
578     return (HCRYPTMSG)msg;
579 }
580
581 typedef struct _CMSG_SIGNER_ENCODE_INFO_WITH_CMS
582 {
583     DWORD                      cbSize;
584     PCERT_INFO                 pCertInfo;
585     HCRYPTPROV                 hCryptProv;
586     DWORD                      dwKeySpec;
587     CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
588     void                      *pvHashAuxInfo;
589     DWORD                      cAuthAttr;
590     PCRYPT_ATTRIBUTE           rgAuthAttr;
591     DWORD                      cUnauthAttr;
592     PCRYPT_ATTRIBUTE           rgUnauthAttr;
593     CERT_ID                    SignerId;
594     CRYPT_ALGORITHM_IDENTIFIER HashEncryptionAlgorithm;
595     void                      *pvHashEncryptionAuxInfo;
596 } CMSG_SIGNER_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNER_ENCODE_INFO_WITH_CMS;
597
598 typedef struct _CMSG_SIGNED_ENCODE_INFO_WITH_CMS
599 {
600     DWORD                             cbSize;
601     DWORD                             cSigners;
602     PCMSG_SIGNER_ENCODE_INFO_WITH_CMS rgSigners;
603     DWORD                             cCertEncoded;
604     PCERT_BLOB                        rgCertEncoded;
605     DWORD                             cCrlEncoded;
606     PCRL_BLOB                         rgCrlEncoded;
607     DWORD                             cAttrCertEncoded;
608     PCERT_BLOB                        rgAttrCertEncoded;
609 } CMSG_SIGNED_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNED_ENCODE_INFO_WITH_CMS;
610
611 static BOOL CRYPT_IsValidSigner(CMSG_SIGNER_ENCODE_INFO_WITH_CMS *signer)
612 {
613     if (signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO) &&
614      signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
615     {
616         SetLastError(E_INVALIDARG);
617         return FALSE;
618     }
619     if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
620     {
621         FIXME("CMSG_SIGNER_ENCODE_INFO with CMS fields unsupported\n");
622         return FALSE;
623     }
624     if (!signer->pCertInfo->SerialNumber.cbData)
625     {
626         SetLastError(E_INVALIDARG);
627         return FALSE;
628     }
629     if (!signer->pCertInfo->Issuer.cbData)
630     {
631         SetLastError(E_INVALIDARG);
632         return FALSE;
633     }
634     if (!signer->hCryptProv)
635     {
636         SetLastError(E_INVALIDARG);
637         return FALSE;
638     }
639     if (!CertOIDToAlgId(signer->HashAlgorithm.pszObjId))
640     {
641         SetLastError(CRYPT_E_UNKNOWN_ALGO);
642         return FALSE;
643     }
644     return TRUE;
645 }
646
647 static BOOL CRYPT_ConstructBlob(CRYPT_DATA_BLOB *out, const CRYPT_DATA_BLOB *in)
648 {
649     BOOL ret = TRUE;
650
651     out->cbData = in->cbData;
652     if (out->cbData)
653     {
654         out->pbData = CryptMemAlloc(out->cbData);
655         if (out->pbData)
656             memcpy(out->pbData, in->pbData, out->cbData);
657         else
658             ret = FALSE;
659     }
660     else
661         out->pbData = NULL;
662     return ret;
663 }
664
665 typedef struct _BlobArray
666 {
667     DWORD            cBlobs;
668     PCRYPT_DATA_BLOB blobs;
669 } BlobArray;
670
671 static BOOL CRYPT_ConstructBlobArray(BlobArray *out, const BlobArray *in)
672 {
673     BOOL ret = TRUE;
674
675     out->cBlobs = in->cBlobs;
676     if (out->cBlobs)
677     {
678         out->blobs = CryptMemAlloc(out->cBlobs * sizeof(CRYPT_DATA_BLOB));
679         if (out->blobs)
680         {
681             DWORD i;
682
683             memset(out->blobs, 0, out->cBlobs * sizeof(CRYPT_DATA_BLOB));
684             for (i = 0; ret && i < out->cBlobs; i++)
685                 ret = CRYPT_ConstructBlob(&out->blobs[i], &in->blobs[i]);
686         }
687         else
688             ret = FALSE;
689     }
690     return ret;
691 }
692
693 static void CRYPT_FreeBlobArray(BlobArray *array)
694 {
695     DWORD i;
696
697     for (i = 0; i < array->cBlobs; i++)
698         CryptMemFree(array->blobs[i].pbData);
699     CryptMemFree(array->blobs);
700 }
701
702 static BOOL CRYPT_ConstructAttribute(CRYPT_ATTRIBUTE *out,
703  const CRYPT_ATTRIBUTE *in)
704 {
705     BOOL ret;
706
707     out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
708     if (out->pszObjId)
709     {
710         strcpy(out->pszObjId, in->pszObjId);
711         ret = CRYPT_ConstructBlobArray((BlobArray *)&out->cValue,
712          (const BlobArray *)&in->cValue);
713     }
714     else
715         ret = FALSE;
716     return ret;
717 }
718
719 static BOOL CRYPT_ConstructAttributes(CRYPT_ATTRIBUTES *out,
720  const CRYPT_ATTRIBUTES *in)
721 {
722     BOOL ret = TRUE;
723
724     out->cAttr = in->cAttr;
725     if (out->cAttr)
726     {
727         out->rgAttr = CryptMemAlloc(out->cAttr * sizeof(CRYPT_ATTRIBUTE));
728         if (out->rgAttr)
729         {
730             DWORD i;
731
732             memset(out->rgAttr, 0, out->cAttr * sizeof(CRYPT_ATTRIBUTE));
733             for (i = 0; ret && i < out->cAttr; i++)
734                 ret = CRYPT_ConstructAttribute(&out->rgAttr[i], &in->rgAttr[i]);
735         }
736         else
737             ret = FALSE;
738     }
739     else
740         out->rgAttr = NULL;
741     return ret;
742 }
743
744 /* Constructs a CMSG_SIGNER_INFO from a CMSG_SIGNER_ENCODE_INFO_WITH_CMS. */
745 static BOOL CSignerInfo_Construct(CMSG_SIGNER_INFO *info,
746  CMSG_SIGNER_ENCODE_INFO_WITH_CMS *in)
747 {
748     BOOL ret;
749
750     /* Note: needs to change if CMS fields are supported */
751     info->dwVersion = CMSG_SIGNER_INFO_V1;
752     ret = CRYPT_ConstructBlob(&info->Issuer, &in->pCertInfo->Issuer);
753     if (ret)
754         ret = CRYPT_ConstructBlob(&info->SerialNumber,
755          &in->pCertInfo->SerialNumber);
756     /* Assumption:  algorithm IDs will point to static strings, not
757      * stack-based ones, so copying the pointer values is safe.
758      */
759     info->HashAlgorithm.pszObjId = in->HashAlgorithm.pszObjId;
760     if (ret)
761         ret = CRYPT_ConstructBlob(&info->HashAlgorithm.Parameters,
762          &in->HashAlgorithm.Parameters);
763     memset(&info->HashEncryptionAlgorithm, 0,
764      sizeof(info->HashEncryptionAlgorithm));
765     if (ret)
766         ret = CRYPT_ConstructAttributes(&info->AuthAttrs,
767          (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
768     if (ret)
769         ret = CRYPT_ConstructAttributes(&info->UnauthAttrs,
770          (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
771     return ret;
772 }
773
774 static void CSignerInfo_Free(CMSG_SIGNER_INFO *info)
775 {
776     DWORD i, j;
777
778     CryptMemFree(info->Issuer.pbData);
779     CryptMemFree(info->SerialNumber.pbData);
780     CryptMemFree(info->HashAlgorithm.Parameters.pbData);
781     CryptMemFree(info->EncryptedHash.pbData);
782     for (i = 0; i < info->AuthAttrs.cAttr; i++)
783     {
784         for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
785             CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
786         CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
787         CryptMemFree(info->AuthAttrs.rgAttr[i].pszObjId);
788     }
789     CryptMemFree(info->AuthAttrs.rgAttr);
790     for (i = 0; i < info->UnauthAttrs.cAttr; i++)
791     {
792         for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
793             CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
794         CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
795         CryptMemFree(info->UnauthAttrs.rgAttr[i].pszObjId);
796     }
797     CryptMemFree(info->UnauthAttrs.rgAttr);
798 }
799
800 typedef struct _CSignerHandles
801 {
802     HCRYPTHASH contentHash;
803     HCRYPTHASH authAttrHash;
804     HCRYPTKEY  key;
805 } CSignerHandles;
806
807 typedef struct _CSignedMsgData
808 {
809     CRYPT_SIGNED_INFO *info;
810     CSignerHandles    *signerHandles;
811 } CSignedMsgData;
812
813 /* Constructs the signer handles for the signerIndex'th signer of msg_data.
814  * Assumes signerIndex is a valid idnex, and that msg_data's info has already
815  * been constructed.
816  */
817 static BOOL CSignedMsgData_ConstructSignerHandles(CSignedMsgData *msg_data,
818  DWORD signerIndex, HCRYPTPROV crypt_prov)
819 {
820     ALG_ID algID;
821     BOOL ret;
822
823     algID = CertOIDToAlgId(
824      msg_data->info->rgSignerInfo[signerIndex].HashAlgorithm.pszObjId);
825     ret = CryptCreateHash(crypt_prov, algID, 0, 0,
826      &msg_data->signerHandles->contentHash);
827     if (ret && msg_data->info->rgSignerInfo[signerIndex].AuthAttrs.cAttr > 0)
828         ret = CryptCreateHash(crypt_prov, algID, 0, 0,
829          &msg_data->signerHandles->authAttrHash);
830     return ret;
831 }
832
833 /* Allocates a CSignedMsgData's handles.  Assumes its info has already been
834  * constructed.
835  */
836 static BOOL CSignedMsgData_AllocateHandles(CSignedMsgData *msg_data)
837 {
838     BOOL ret = TRUE;
839
840     if (msg_data->info->cSignerInfo)
841     {
842         msg_data->signerHandles =
843          CryptMemAlloc(msg_data->info->cSignerInfo * sizeof(CSignerHandles));
844         if (msg_data->signerHandles)
845             memset(msg_data->signerHandles, 0,
846              msg_data->info->cSignerInfo * sizeof(CSignerHandles));
847         else
848             ret = FALSE;
849     }
850     else
851         msg_data->signerHandles = NULL;
852     return ret;
853 }
854
855 static void CSignedMsgData_CloseHandles(CSignedMsgData *msg_data)
856 {
857     DWORD i;
858
859     for (i = 0; i < msg_data->info->cSignerInfo; i++)
860     {
861         if (msg_data->signerHandles[i].key)
862             CryptDestroyKey(msg_data->signerHandles[i].key);
863         if (msg_data->signerHandles[i].contentHash)
864             CryptDestroyHash(msg_data->signerHandles[i].contentHash);
865         if (msg_data->signerHandles[i].authAttrHash)
866             CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
867     }
868     CryptMemFree(msg_data->signerHandles);
869 }
870
871 static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
872  const BYTE *pbData, DWORD cbData)
873 {
874     DWORD i;
875     BOOL ret = TRUE;
876
877     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
878         ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
879          cbData, 0);
880     return ret;
881 }
882
883 static BOOL CRYPT_AppendAttribute(CRYPT_ATTRIBUTES *out,
884  const CRYPT_ATTRIBUTE *in)
885 {
886     BOOL ret = FALSE;
887
888     out->rgAttr = CryptMemRealloc(out->rgAttr,
889      (out->cAttr + 1) * sizeof(CRYPT_ATTRIBUTE));
890     if (out->rgAttr)
891     {
892         ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
893         if (ret)
894             out->cAttr++;
895     }
896     return ret;
897 }
898
899 static BOOL CSignedMsgData_AppendMessageDigestAttribute(
900  CSignedMsgData *msg_data, DWORD signerIndex)
901 {
902     BOOL ret;
903     DWORD size;
904     CRYPT_HASH_BLOB hash = { 0, NULL }, encodedHash = { 0, NULL };
905     char messageDigest[] = szOID_RSA_messageDigest;
906     CRYPT_ATTRIBUTE messageDigestAttr = { messageDigest, 1, &encodedHash };
907
908     size = sizeof(DWORD);
909     ret = CryptGetHashParam(
910      msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
911      (LPBYTE)&hash.cbData, &size, 0);
912     if (ret)
913     {
914         hash.pbData = CryptMemAlloc(hash.cbData);
915         ret = CryptGetHashParam(
916          msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
917          hash.pbData, &hash.cbData, 0);
918         if (ret)
919         {
920             ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
921              NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
922             if (ret)
923             {
924                 ret = CRYPT_AppendAttribute(
925                  &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
926                  &messageDigestAttr);
927                 LocalFree(encodedHash.pbData);
928             }
929         }
930         CryptMemFree(hash.pbData);
931     }
932     return ret;
933 }
934
935 typedef enum {
936     Sign,
937     Verify
938 } SignOrVerify;
939
940 static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
941  CSignedMsgData *msg_data, SignOrVerify flag)
942 {
943     DWORD i;
944     BOOL ret = TRUE;
945
946     TRACE("(%p)\n", msg_data);
947
948     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
949     {
950         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
951         {
952             if (flag == Sign)
953             {
954                 BYTE oid_rsa_data_encoded[] = { 0x06,0x09,0x2a,0x86,0x48,0x86,
955                  0xf7,0x0d,0x01,0x07,0x01 };
956                 CRYPT_DATA_BLOB content = { sizeof(oid_rsa_data_encoded),
957                  oid_rsa_data_encoded };
958                 char contentType[] = szOID_RSA_contentType;
959                 CRYPT_ATTRIBUTE contentTypeAttr = { contentType, 1, &content };
960
961                 /* FIXME: does this depend on inner OID? */
962                 ret = CRYPT_AppendAttribute(
963                  &msg_data->info->rgSignerInfo[i].AuthAttrs, &contentTypeAttr);
964                 if (ret)
965                     ret = CSignedMsgData_AppendMessageDigestAttribute(msg_data,
966                      i);
967             }
968             if (ret)
969             {
970                 LPBYTE encodedAttrs;
971                 DWORD size;
972
973                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
974                  &msg_data->info->rgSignerInfo[i].AuthAttrs,
975                  CRYPT_ENCODE_ALLOC_FLAG, NULL, (LPBYTE)&encodedAttrs, &size);
976                 if (ret)
977                 {
978                     ret = CryptHashData(
979                      msg_data->signerHandles[i].authAttrHash, encodedAttrs,
980                      size, 0);
981                     LocalFree(encodedAttrs);
982                 }
983             }
984         }
985     }
986     TRACE("returning %d\n", ret);
987     return ret;
988 }
989
990 static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
991 {
992     DWORD i;
993     BYTE tmp;
994
995     for (i = 0; i < hash->cbData / 2; i++)
996     {
997         tmp = hash->pbData[hash->cbData - i - 1];
998         hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
999         hash->pbData[i] = tmp;
1000     }
1001 }
1002
1003 static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
1004 {
1005     DWORD i;
1006     BOOL ret = TRUE;
1007
1008     TRACE("(%p)\n", msg_data);
1009
1010     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1011     {
1012         HCRYPTHASH hash;
1013
1014         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1015             hash = msg_data->signerHandles[i].authAttrHash;
1016         else
1017             hash = msg_data->signerHandles[i].contentHash;
1018         ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
1019          &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1020         if (ret)
1021         {
1022             msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
1023              CryptMemAlloc(
1024              msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1025             if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
1026             {
1027                 ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
1028                  msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
1029                  &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1030                 if (ret)
1031                     CRYPT_ReverseBytes(
1032                      &msg_data->info->rgSignerInfo[i].EncryptedHash);
1033             }
1034             else
1035                 ret = FALSE;
1036         }
1037     }
1038     return ret;
1039 }
1040
1041 static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1042  const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1043 {
1044     BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);
1045
1046     if (ret && fFinal)
1047     {
1048         ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
1049         if (ret && flag == Sign)
1050             ret = CSignedMsgData_Sign(msg_data);
1051     }
1052     return ret;
1053 }
1054
1055 typedef struct _CSignedEncodeMsg
1056 {
1057     CryptMsgBase    base;
1058     CRYPT_DATA_BLOB data;
1059     CSignedMsgData  msg_data;
1060 } CSignedEncodeMsg;
1061
1062 static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
1063 {
1064     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1065     DWORD i;
1066
1067     CryptMemFree(msg->data.pbData);
1068     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCertEncoded);
1069     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCrlEncoded);
1070     for (i = 0; i < msg->msg_data.info->cSignerInfo; i++)
1071         CSignerInfo_Free(&msg->msg_data.info->rgSignerInfo[i]);
1072     CSignedMsgData_CloseHandles(&msg->msg_data);
1073     CryptMemFree(msg->msg_data.info->rgSignerInfo);
1074     CryptMemFree(msg->msg_data.info);
1075 }
1076
1077 static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1078  DWORD dwIndex, void *pvData, DWORD *pcbData)
1079 {
1080     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1081     BOOL ret = FALSE;
1082
1083     switch (dwParamType)
1084     {
1085     case CMSG_CONTENT_PARAM:
1086     {
1087         CRYPT_CONTENT_INFO info;
1088
1089         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
1090          &info.Content.cbData);
1091         if (ret)
1092         {
1093             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
1094             if (info.Content.pbData)
1095             {
1096                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
1097                  info.Content.pbData, &info.Content.cbData);
1098                 if (ret)
1099                 {
1100                     char oid_rsa_signed[] = szOID_RSA_signedData;
1101
1102                     info.pszObjId = oid_rsa_signed;
1103                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
1104                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
1105                 }
1106                 CryptMemFree(info.Content.pbData);
1107             }
1108             else
1109                 ret = FALSE;
1110         }
1111         break;
1112     }
1113     case CMSG_BARE_CONTENT_PARAM:
1114     {
1115         CRYPT_SIGNED_INFO info;
1116         char oid_rsa_data[] = szOID_RSA_data;
1117
1118         memcpy(&info, msg->msg_data.info, sizeof(info));
1119         /* Quirk:  OID is only encoded messages if an update has happened */
1120         if (msg->base.state != MsgStateInit)
1121             info.content.pszObjId = oid_rsa_data;
1122         else
1123             info.content.pszObjId = NULL;
1124         if (msg->data.cbData)
1125         {
1126             CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
1127
1128             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1129              &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1130              &info.content.Content.pbData, &info.content.Content.cbData);
1131         }
1132         else
1133         {
1134             info.content.Content.cbData = 0;
1135             info.content.Content.pbData = NULL;
1136             ret = TRUE;
1137         }
1138         if (ret)
1139         {
1140             ret = CRYPT_AsnEncodePKCSSignedInfo(&info, pvData, pcbData);
1141             LocalFree(info.content.Content.pbData);
1142         }
1143         break;
1144     }
1145     case CMSG_COMPUTED_HASH_PARAM:
1146         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1147             SetLastError(CRYPT_E_INVALID_INDEX);
1148         else
1149             ret = CryptGetHashParam(
1150              msg->msg_data.signerHandles[dwIndex].contentHash, HP_HASHVAL,
1151              pvData, pcbData, 0);
1152         break;
1153     case CMSG_ENCODED_SIGNER:
1154         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1155             SetLastError(CRYPT_E_INVALID_INDEX);
1156         else
1157             ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1158              PKCS7_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1159              NULL, pvData, pcbData);
1160         break;
1161     case CMSG_VERSION_PARAM:
1162         ret = CRYPT_CopyParam(pvData, pcbData, &msg->msg_data.info->version,
1163          sizeof(msg->msg_data.info->version));
1164         break;
1165     default:
1166         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1167     }
1168     return ret;
1169 }
1170
1171 static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1172  DWORD cbData, BOOL fFinal)
1173 {
1174     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1175     BOOL ret = FALSE;
1176
1177     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1178     {
1179         ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
1180          Sign);
1181         if (msg->base.streamed)
1182             FIXME("streamed partial stub\n");
1183     }
1184     else
1185     {
1186         if (!fFinal)
1187             SetLastError(CRYPT_E_MSG_ERROR);
1188         else
1189         {
1190             if (cbData)
1191             {
1192                 msg->data.pbData = CryptMemAlloc(cbData);
1193                 if (msg->data.pbData)
1194                 {
1195                     memcpy(msg->data.pbData, pbData, cbData);
1196                     msg->data.cbData = cbData;
1197                     ret = TRUE;
1198                 }
1199             }
1200             else
1201                 ret = TRUE;
1202             if (ret)
1203                 ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1204                  fFinal, Sign);
1205         }
1206     }
1207     return ret;
1208 }
1209
1210 static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1211  const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1212  PCMSG_STREAM_INFO pStreamInfo)
1213 {
1214     const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info =
1215      (const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *)pvMsgEncodeInfo;
1216     DWORD i;
1217     CSignedEncodeMsg *msg;
1218
1219     if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
1220      info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1221     {
1222         SetLastError(E_INVALIDARG);
1223         return NULL;
1224     }
1225     if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1226     {
1227         FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
1228         return NULL;
1229     }
1230     for (i = 0; i < info->cSigners; i++)
1231         if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
1232             return NULL;
1233     msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
1234     if (msg)
1235     {
1236         BOOL ret = TRUE;
1237
1238         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1239          CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1240          CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1241         msg->data.cbData = 0;
1242         msg->data.pbData = NULL;
1243         msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
1244         if (msg->msg_data.info)
1245         {
1246             memset(msg->msg_data.info, 0, sizeof(CRYPT_SIGNED_INFO));
1247             msg->msg_data.info->version = CMSG_SIGNED_DATA_V1;
1248         }
1249         else
1250             ret = FALSE;
1251         if (ret && info->cSigners)
1252         {
1253             msg->msg_data.info->rgSignerInfo =
1254              CryptMemAlloc(info->cSigners * sizeof(CMSG_SIGNER_INFO));
1255             if (msg->msg_data.info->rgSignerInfo)
1256             {
1257                 msg->msg_data.info->cSignerInfo = info->cSigners;
1258                 memset(msg->msg_data.info->rgSignerInfo, 0,
1259                  msg->msg_data.info->cSignerInfo * sizeof(CMSG_SIGNER_INFO));
1260                 ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
1261                 for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1262                 {
1263                     ret = CSignerInfo_Construct(
1264                      &msg->msg_data.info->rgSignerInfo[i],
1265                      &info->rgSigners[i]);
1266                     if (ret)
1267                     {
1268                         ret = CSignedMsgData_ConstructSignerHandles(
1269                          &msg->msg_data, i, info->rgSigners[i].hCryptProv);
1270                         if (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1271                             CryptReleaseContext(info->rgSigners[i].hCryptProv,
1272                              0);
1273                     }
1274                 }
1275             }
1276             else
1277                 ret = FALSE;
1278         }
1279         if (ret)
1280             ret = CRYPT_ConstructBlobArray(
1281              (BlobArray *)&msg->msg_data.info->cCertEncoded,
1282              (const BlobArray *)&info->cCertEncoded);
1283         if (ret)
1284             ret = CRYPT_ConstructBlobArray(
1285              (BlobArray *)&msg->msg_data.info->cCrlEncoded,
1286              (const BlobArray *)&info->cCrlEncoded);
1287         if (!ret)
1288         {
1289             CSignedEncodeMsg_Close(msg);
1290             msg = NULL;
1291         }
1292     }
1293     return msg;
1294 }
1295
1296 static inline const char *MSG_TYPE_STR(DWORD type)
1297 {
1298     switch (type)
1299     {
1300 #define _x(x) case (x): return #x
1301         _x(CMSG_DATA);
1302         _x(CMSG_SIGNED);
1303         _x(CMSG_ENVELOPED);
1304         _x(CMSG_SIGNED_AND_ENVELOPED);
1305         _x(CMSG_HASHED);
1306         _x(CMSG_ENCRYPTED);
1307 #undef _x
1308         default:
1309             return wine_dbg_sprintf("unknown (%d)", type);
1310     }
1311 }
1312
1313 HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
1314  DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1315  PCMSG_STREAM_INFO pStreamInfo)
1316 {
1317     HCRYPTMSG msg = NULL;
1318
1319     TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
1320      dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
1321
1322     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
1323     {
1324         SetLastError(E_INVALIDARG);
1325         return NULL;
1326     }
1327     switch (dwMsgType)
1328     {
1329     case CMSG_DATA:
1330         msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1331          pszInnerContentObjID, pStreamInfo);
1332         break;
1333     case CMSG_HASHED:
1334         msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1335          pszInnerContentObjID, pStreamInfo);
1336         break;
1337     case CMSG_SIGNED:
1338         msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1339          pszInnerContentObjID, pStreamInfo);
1340         break;
1341     case CMSG_ENVELOPED:
1342         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(dwMsgType));
1343         break;
1344     case CMSG_SIGNED_AND_ENVELOPED:
1345     case CMSG_ENCRYPTED:
1346         /* defined but invalid, fall through */
1347     default:
1348         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1349     }
1350     return msg;
1351 }
1352
1353 typedef struct _CDecodeMsg
1354 {
1355     CryptMsgBase           base;
1356     DWORD                  type;
1357     HCRYPTPROV             crypt_prov;
1358     union {
1359         HCRYPTHASH     hash;
1360         CSignedMsgData signed_data;
1361     } u;
1362     CRYPT_DATA_BLOB        msg_data;
1363     PCONTEXT_PROPERTY_LIST properties;
1364 } CDecodeMsg;
1365
1366 static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
1367 {
1368     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1369
1370     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1371         CryptReleaseContext(msg->crypt_prov, 0);
1372     switch (msg->type)
1373     {
1374     case CMSG_HASHED:
1375         if (msg->u.hash)
1376             CryptDestroyHash(msg->u.hash);
1377         break;
1378     case CMSG_SIGNED:
1379         if (msg->u.signed_data.info)
1380         {
1381             LocalFree(msg->u.signed_data.info);
1382             CSignedMsgData_CloseHandles(&msg->u.signed_data);
1383         }
1384         break;
1385     }
1386     CryptMemFree(msg->msg_data.pbData);
1387     ContextPropertyList_Free(msg->properties);
1388 }
1389
1390 static BOOL CDecodeMsg_CopyData(CDecodeMsg *msg, const BYTE *pbData,
1391  DWORD cbData)
1392 {
1393     BOOL ret = TRUE;
1394
1395     if (cbData)
1396     {
1397         if (msg->msg_data.cbData)
1398             msg->msg_data.pbData = CryptMemRealloc(msg->msg_data.pbData,
1399              msg->msg_data.cbData + cbData);
1400         else
1401             msg->msg_data.pbData = CryptMemAlloc(cbData);
1402         if (msg->msg_data.pbData)
1403         {
1404             memcpy(msg->msg_data.pbData + msg->msg_data.cbData, pbData, cbData);
1405             msg->msg_data.cbData += cbData;
1406         }
1407         else
1408             ret = FALSE;
1409     }
1410     return ret;
1411 }
1412
1413 static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
1414 {
1415     BOOL ret;
1416     CRYPT_DATA_BLOB *data;
1417     DWORD size;
1418
1419     ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1420      blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&data,
1421      &size);
1422     if (ret)
1423     {
1424         ret = ContextPropertyList_SetProperty(msg->properties,
1425          CMSG_CONTENT_PARAM, data->pbData, data->cbData);
1426         LocalFree(data);
1427     }
1428     return ret;
1429 }
1430
1431 static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
1432  const CRYPT_ALGORITHM_IDENTIFIER *id)
1433 {
1434     static const BYTE nullParams[] = { ASN_NULL, 0 };
1435     CRYPT_ALGORITHM_IDENTIFIER *copy;
1436     DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);
1437
1438     /* Linearize algorithm id */
1439     len += strlen(id->pszObjId) + 1;
1440     len += id->Parameters.cbData;
1441     copy = CryptMemAlloc(len);
1442     if (copy)
1443     {
1444         copy->pszObjId =
1445          (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1446         strcpy(copy->pszObjId, id->pszObjId);
1447         copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
1448          + 1;
1449         /* Trick:  omit NULL parameters */
1450         if (id->Parameters.cbData == sizeof(nullParams) &&
1451          !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
1452         {
1453             copy->Parameters.cbData = 0;
1454             len -= sizeof(nullParams);
1455         }
1456         else
1457             copy->Parameters.cbData = id->Parameters.cbData;
1458         if (copy->Parameters.cbData)
1459             memcpy(copy->Parameters.pbData, id->Parameters.pbData,
1460              id->Parameters.cbData);
1461         ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
1462          len);
1463         CryptMemFree(copy);
1464     }
1465 }
1466
1467 static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
1468 {
1469     id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1470     id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
1471 }
1472
1473 static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
1474  CRYPT_DER_BLOB *blob)
1475 {
1476     BOOL ret;
1477     CRYPT_DIGESTED_DATA *digestedData;
1478     DWORD size;
1479
1480     ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
1481      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
1482      &size);
1483     if (ret)
1484     {
1485         ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
1486          (const BYTE *)&digestedData->version, sizeof(digestedData->version));
1487         CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
1488          &digestedData->DigestAlgorithm);
1489         ContextPropertyList_SetProperty(msg->properties,
1490          CMSG_INNER_CONTENT_TYPE_PARAM,
1491          (const BYTE *)digestedData->ContentInfo.pszObjId,
1492          digestedData->ContentInfo.pszObjId ?
1493          strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
1494         if (digestedData->ContentInfo.Content.cbData)
1495             CDecodeMsg_DecodeDataContent(msg,
1496              &digestedData->ContentInfo.Content);
1497         else
1498             ContextPropertyList_SetProperty(msg->properties,
1499              CMSG_CONTENT_PARAM, NULL, 0);
1500         ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
1501          digestedData->hash.pbData, digestedData->hash.cbData);
1502         LocalFree(digestedData);
1503     }
1504     return ret;
1505 }
1506
1507 static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
1508  CRYPT_DER_BLOB *blob)
1509 {
1510     BOOL ret;
1511     CRYPT_SIGNED_INFO *signedInfo;
1512     DWORD size;
1513
1514     ret = CRYPT_AsnDecodePKCSSignedInfo(blob->pbData, blob->cbData,
1515      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
1516      &size);
1517     if (ret)
1518     {
1519         DWORD i;
1520
1521         msg->u.signed_data.info = signedInfo;
1522         ret = CSignedMsgData_AllocateHandles(&msg->u.signed_data);
1523         for (i = 0; ret && i < msg->u.signed_data.info->cSignerInfo; i++)
1524             ret = CSignedMsgData_ConstructSignerHandles(&msg->u.signed_data, i,
1525              msg->crypt_prov);
1526         if (ret)
1527         {
1528             /* Now that we have all the content, update the hash handles with
1529              * it.  Have to decode it if the type is szOID_RSA_data.
1530              */
1531             if (msg->u.signed_data.info->content.Content.cbData)
1532             {
1533                 if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1534                  szOID_RSA_data))
1535                 {
1536                     CRYPT_DATA_BLOB *blob;
1537
1538                     ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
1539                      X509_OCTET_STRING,
1540                      msg->u.signed_data.info->content.Content.pbData,
1541                      msg->u.signed_data.info->content.Content.cbData,
1542                      CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1543                     if (ret)
1544                     {
1545                         ret = CSignedMsgData_Update(&msg->u.signed_data,
1546                          blob->pbData, blob->cbData, TRUE, Verify);
1547                         LocalFree(blob);
1548                     }
1549                 }
1550                 else
1551                     ret = CSignedMsgData_Update(&msg->u.signed_data,
1552                      msg->u.signed_data.info->content.Content.pbData,
1553                      msg->u.signed_data.info->content.Content.cbData, TRUE,
1554                      Verify);
1555             }
1556         }
1557     }
1558     return ret;
1559 }
1560 /* Decodes the content in blob as the type given, and updates the value
1561  * (type, parameters, etc.) of msg based on what blob contains.
1562  * It doesn't just use msg's type, to allow a recursive call from an implicitly
1563  * typed message once the outer content info has been decoded.
1564  */
1565 static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob,
1566  DWORD type)
1567 {
1568     BOOL ret;
1569
1570     switch (type)
1571     {
1572     case CMSG_DATA:
1573         if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
1574             msg->type = CMSG_DATA;
1575         break;
1576     case CMSG_HASHED:
1577         if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
1578             msg->type = CMSG_HASHED;
1579         break;
1580     case CMSG_ENVELOPED:
1581         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(type));
1582         ret = TRUE;
1583         break;
1584     case CMSG_SIGNED:
1585         if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
1586             msg->type = CMSG_SIGNED;
1587         break;
1588     default:
1589     {
1590         CRYPT_CONTENT_INFO *info;
1591         DWORD size;
1592
1593         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
1594          msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
1595          NULL, (LPBYTE)&info, &size);
1596         if (ret)
1597         {
1598             if (!strcmp(info->pszObjId, szOID_RSA_data))
1599                 ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
1600             else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
1601                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1602                  CMSG_HASHED);
1603             else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
1604                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1605                  CMSG_ENVELOPED);
1606             else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
1607                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1608                  CMSG_SIGNED);
1609             else
1610             {
1611                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1612                 ret = FALSE;
1613             }
1614             LocalFree(info);
1615         }
1616     }
1617     }
1618     return ret;
1619 }
1620
1621 static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1622  DWORD cbData, BOOL fFinal)
1623 {
1624     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1625     BOOL ret = FALSE;
1626
1627     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
1628
1629     if (msg->base.streamed)
1630     {
1631         ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1632         FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
1633          cbData, fFinal);
1634     }
1635     else
1636     {
1637         if (!fFinal)
1638             SetLastError(CRYPT_E_MSG_ERROR);
1639         else
1640         {
1641             ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1642             if (ret)
1643                 ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
1644
1645         }
1646     }
1647     return ret;
1648 }
1649
1650 static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1651  DWORD dwIndex, void *pvData, DWORD *pcbData)
1652 {
1653     BOOL ret = FALSE;
1654
1655     switch (dwParamType)
1656     {
1657     case CMSG_TYPE_PARAM:
1658         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1659         break;
1660     case CMSG_HASH_ALGORITHM_PARAM:
1661     {
1662         CRYPT_DATA_BLOB blob;
1663
1664         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1665          &blob);
1666         if (ret)
1667         {
1668             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1669             if (ret && pvData)
1670                 CRYPT_FixUpAlgorithmID((CRYPT_ALGORITHM_IDENTIFIER *)pvData);
1671         }
1672         else
1673             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1674         break;
1675     }
1676     case CMSG_COMPUTED_HASH_PARAM:
1677         if (!msg->u.hash)
1678         {
1679             CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
1680             DWORD size = 0;
1681             ALG_ID algID = 0;
1682
1683             CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
1684             hashAlgoID = CryptMemAlloc(size);
1685             ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0,
1686              hashAlgoID, &size);
1687             if (ret)
1688                 algID = CertOIDToAlgId(hashAlgoID->pszObjId);
1689             ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->u.hash);
1690             if (ret)
1691             {
1692                 CRYPT_DATA_BLOB content;
1693
1694                 ret = ContextPropertyList_FindProperty(msg->properties,
1695                  CMSG_CONTENT_PARAM, &content);
1696                 if (ret)
1697                     ret = CryptHashData(msg->u.hash, content.pbData,
1698                      content.cbData, 0);
1699             }
1700             CryptMemFree(hashAlgoID);
1701         }
1702         else
1703             ret = TRUE;
1704         if (ret)
1705             ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData,
1706              0);
1707         break;
1708     default:
1709     {
1710         CRYPT_DATA_BLOB blob;
1711
1712         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1713          &blob);
1714         if (ret)
1715             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1716         else
1717             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1718     }
1719     }
1720     return ret;
1721 }
1722
1723 /* nextData is an in/out parameter - on input it's the memory location in
1724  * which a copy of in's data should be made, and on output it's the memory
1725  * location immediately after out's copy of in's data.
1726  */
1727 static inline void CRYPT_CopyBlob(CRYPT_DATA_BLOB *out,
1728  const CRYPT_DATA_BLOB *in, LPBYTE *nextData)
1729 {
1730     out->cbData = in->cbData;
1731     if (in->cbData)
1732     {
1733         out->pbData = *nextData;
1734         memcpy(out->pbData, in->pbData, in->cbData);
1735         *nextData += in->cbData;
1736     }
1737 }
1738
1739 static inline void CRYPT_CopyAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
1740  const CRYPT_ALGORITHM_IDENTIFIER *in, LPBYTE *nextData)
1741 {
1742     if (in->pszObjId)
1743     {
1744         out->pszObjId = (LPSTR)*nextData;
1745         strcpy(out->pszObjId, in->pszObjId);
1746         *nextData += strlen(out->pszObjId) + 1;
1747     }
1748     CRYPT_CopyBlob(&out->Parameters, &in->Parameters, nextData);
1749 }
1750
1751 static inline void CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
1752  const CRYPT_ATTRIBUTES *in, LPBYTE *nextData)
1753 {
1754     out->cAttr = in->cAttr;
1755     if (in->cAttr)
1756     {
1757         DWORD i;
1758
1759         if ((*nextData - (LPBYTE)0) % sizeof(DWORD_PTR))
1760             *nextData += (*nextData - (LPBYTE)0) % sizeof(DWORD_PTR);
1761         out->rgAttr = (CRYPT_ATTRIBUTE *)*nextData;
1762         *nextData += in->cAttr * sizeof(CRYPT_ATTRIBUTE);
1763         for (i = 0; i < in->cAttr; i++)
1764         {
1765             if (in->rgAttr[i].pszObjId)
1766             {
1767                 out->rgAttr[i].pszObjId = (LPSTR)*nextData;
1768                 strcpy(out->rgAttr[i].pszObjId, in->rgAttr[i].pszObjId);
1769                 *nextData += strlen(in->rgAttr[i].pszObjId) + 1;
1770             }
1771             if (in->rgAttr[i].cValue)
1772             {
1773                 DWORD j;
1774
1775                 out->rgAttr[i].cValue = in->rgAttr[i].cValue;
1776                 if ((*nextData - (LPBYTE)0) % sizeof(DWORD_PTR))
1777                     *nextData += (*nextData - (LPBYTE)0) % sizeof(DWORD_PTR);
1778                 out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
1779                 for (j = 0; j < in->rgAttr[i].cValue; j++)
1780                     CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
1781                      &in->rgAttr[i].rgValue[j], nextData);
1782             }
1783         }
1784     }
1785 }
1786
1787 static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
1788 {
1789     DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;
1790
1791     for (i = 0; i < attr->cAttr; i++)
1792     {
1793         if (attr->rgAttr[i].pszObjId)
1794             size += strlen(attr->rgAttr[i].pszObjId) + 1;
1795         /* align pointer */
1796         if (size % sizeof(DWORD_PTR))
1797             size += size % sizeof(DWORD_PTR);
1798         size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
1799         for (j = 0; j < attr->rgAttr[i].cValue; j++)
1800             size += attr->rgAttr[i].rgValue[j].cbData;
1801     }
1802     return size;
1803 }
1804
1805 static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
1806  const CMSG_SIGNER_INFO *in)
1807 {
1808     DWORD size = sizeof(CMSG_SIGNER_INFO);
1809     BOOL ret;
1810
1811     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
1812
1813     size += in->Issuer.cbData;
1814     size += in->SerialNumber.cbData;
1815     if (in->HashAlgorithm.pszObjId)
1816         size += strlen(in->HashAlgorithm.pszObjId) + 1;
1817     size += in->HashAlgorithm.Parameters.cbData;
1818     if (in->HashEncryptionAlgorithm.pszObjId)
1819         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
1820     size += in->HashEncryptionAlgorithm.Parameters.cbData;
1821     size += in->EncryptedHash.cbData;
1822     /* align pointer */
1823     if (size % sizeof(DWORD_PTR))
1824         size += size % sizeof(DWORD_PTR);
1825     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
1826     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
1827     if (!pvData)
1828     {
1829         *pcbData = size;
1830         ret = TRUE;
1831     }
1832     else if (*pcbData < size)
1833     {
1834         *pcbData = size;
1835         SetLastError(ERROR_MORE_DATA);
1836         ret = FALSE;
1837     }
1838     else
1839     {
1840         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
1841         CMSG_SIGNER_INFO *out = (CMSG_SIGNER_INFO *)pvData;
1842
1843         out->dwVersion = in->dwVersion;
1844         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1845         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1846         CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
1847          &nextData);
1848         CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
1849          &in->HashEncryptionAlgorithm, &nextData);
1850         CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
1851         /* align pointer */
1852         if ((nextData - (LPBYTE)0) % sizeof(DWORD_PTR))
1853             nextData += (nextData - (LPBYTE)0) % sizeof(DWORD_PTR);
1854         CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
1855         CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
1856         ret = TRUE;
1857     }
1858     TRACE("returning %d\n", ret);
1859     return ret;
1860 }
1861
1862 static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
1863  const CMSG_SIGNER_INFO *in)
1864 {
1865     DWORD size = sizeof(CERT_INFO);
1866     BOOL ret;
1867
1868     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
1869
1870     size += in->Issuer.cbData;
1871     size += in->SerialNumber.cbData;
1872     if (!pvData)
1873     {
1874         *pcbData = size;
1875         ret = TRUE;
1876     }
1877     else if (*pcbData < size)
1878     {
1879         *pcbData = size;
1880         SetLastError(ERROR_MORE_DATA);
1881         ret = FALSE;
1882     }
1883     else
1884     {
1885         LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
1886         CERT_INFO *out = (CERT_INFO *)pvData;
1887
1888         memset(out, 0, sizeof(CERT_INFO));
1889         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1890         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1891         ret = TRUE;
1892     }
1893     TRACE("returning %d\n", ret);
1894     return ret;
1895 }
1896
1897 static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1898  DWORD dwIndex, void *pvData, DWORD *pcbData)
1899 {
1900     BOOL ret = FALSE;
1901
1902     switch (dwParamType)
1903     {
1904     case CMSG_TYPE_PARAM:
1905         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1906         break;
1907     case CMSG_CONTENT_PARAM:
1908         if (msg->u.signed_data.info)
1909         {
1910             if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1911              szOID_RSA_data))
1912             {
1913                 CRYPT_DATA_BLOB *blob;
1914                 DWORD size;
1915
1916                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1917                  msg->u.signed_data.info->content.Content.pbData,
1918                  msg->u.signed_data.info->content.Content.cbData,
1919                  CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1920                 if (ret)
1921                 {
1922                     ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
1923                      blob->cbData);
1924                     LocalFree(blob);
1925                 }
1926             }
1927             else
1928                 ret = CRYPT_CopyParam(pvData, pcbData,
1929                  msg->u.signed_data.info->content.Content.pbData,
1930                  msg->u.signed_data.info->content.Content.cbData);
1931         }
1932         else
1933             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1934         break;
1935     case CMSG_INNER_CONTENT_TYPE_PARAM:
1936         if (msg->u.signed_data.info)
1937             ret = CRYPT_CopyParam(pvData, pcbData,
1938              msg->u.signed_data.info->content.pszObjId,
1939              strlen(msg->u.signed_data.info->content.pszObjId) + 1);
1940         else
1941             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1942         break;
1943     case CMSG_SIGNER_COUNT_PARAM:
1944         if (msg->u.signed_data.info)
1945             ret = CRYPT_CopyParam(pvData, pcbData,
1946              &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
1947         else
1948             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1949         break;
1950     case CMSG_SIGNER_INFO_PARAM:
1951         if (msg->u.signed_data.info)
1952         {
1953             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1954                 SetLastError(CRYPT_E_INVALID_INDEX);
1955             else
1956                 ret = CRYPT_CopySignerInfo(pvData, pcbData,
1957                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1958         }
1959         else
1960             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1961         break;
1962     case CMSG_SIGNER_CERT_INFO_PARAM:
1963         if (msg->u.signed_data.info)
1964         {
1965             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1966                 SetLastError(CRYPT_E_INVALID_INDEX);
1967             else
1968                 ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
1969                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1970         }
1971         else
1972             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1973         break;
1974     case CMSG_CERT_COUNT_PARAM:
1975         if (msg->u.signed_data.info)
1976             ret = CRYPT_CopyParam(pvData, pcbData,
1977              &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
1978         else
1979             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1980         break;
1981     case CMSG_CERT_PARAM:
1982         if (msg->u.signed_data.info)
1983         {
1984             if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
1985                 SetLastError(CRYPT_E_INVALID_INDEX);
1986             else
1987                 ret = CRYPT_CopyParam(pvData, pcbData,
1988                  msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
1989                  msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
1990         }
1991         else
1992             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1993         break;
1994     case CMSG_CRL_COUNT_PARAM:
1995         if (msg->u.signed_data.info)
1996             ret = CRYPT_CopyParam(pvData, pcbData,
1997              &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
1998         else
1999             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2000         break;
2001     case CMSG_CRL_PARAM:
2002         if (msg->u.signed_data.info)
2003         {
2004             if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
2005                 SetLastError(CRYPT_E_INVALID_INDEX);
2006             else
2007                 ret = CRYPT_CopyParam(pvData, pcbData,
2008                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
2009                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
2010         }
2011         else
2012             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2013         break;
2014     case CMSG_COMPUTED_HASH_PARAM:
2015         if (msg->u.signed_data.info)
2016         {
2017             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2018                 SetLastError(CRYPT_E_INVALID_INDEX);
2019             else
2020                 ret = CryptGetHashParam(
2021                  msg->u.signed_data.signerHandles[dwIndex].contentHash,
2022                  HP_HASHVAL, pvData, pcbData, 0);
2023         }
2024         else
2025             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2026         break;
2027     case CMSG_ATTR_CERT_COUNT_PARAM:
2028         if (msg->u.signed_data.info)
2029         {
2030             DWORD attrCertCount = 0;
2031
2032             ret = CRYPT_CopyParam(pvData, pcbData,
2033              &attrCertCount, sizeof(DWORD));
2034         }
2035         else
2036             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2037         break;
2038     case CMSG_ATTR_CERT_PARAM:
2039         if (msg->u.signed_data.info)
2040             SetLastError(CRYPT_E_INVALID_INDEX);
2041         else
2042             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2043         break;
2044     default:
2045         FIXME("unimplemented for %d\n", dwParamType);
2046         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2047     }
2048     return ret;
2049 }
2050
2051 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2052  DWORD dwIndex, void *pvData, DWORD *pcbData)
2053 {
2054     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2055     BOOL ret = FALSE;
2056
2057     switch (msg->type)
2058     {
2059     case CMSG_HASHED:
2060         ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2061          pcbData);
2062         break;
2063     case CMSG_SIGNED:
2064         ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2065          pcbData);
2066         break;
2067     default:
2068         switch (dwParamType)
2069         {
2070         case CMSG_TYPE_PARAM:
2071             ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
2072              sizeof(msg->type));
2073             break;
2074         default:
2075         {
2076             CRYPT_DATA_BLOB blob;
2077
2078             ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2079              &blob);
2080             if (ret)
2081                 ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
2082                  blob.cbData);
2083             else
2084                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2085         }
2086         }
2087     }
2088     return ret;
2089 }
2090
2091 static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
2092 {
2093     BOOL ret;
2094     CRYPT_DATA_BLOB hashBlob;
2095
2096     ret = ContextPropertyList_FindProperty(msg->properties,
2097      CMSG_HASH_DATA_PARAM, &hashBlob);
2098     if (ret)
2099     {
2100         DWORD computedHashSize = 0;
2101
2102         ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
2103          &computedHashSize);
2104         if (hashBlob.cbData == computedHashSize)
2105         {
2106             LPBYTE computedHash = CryptMemAlloc(computedHashSize);
2107
2108             if (computedHash)
2109             {
2110                 ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
2111                  computedHash, &computedHashSize);
2112                 if (ret)
2113                     ret = !memcmp(hashBlob.pbData, computedHash,
2114                      hashBlob.cbData);
2115                 CryptMemFree(computedHash);
2116             }
2117             else
2118                 ret = FALSE;
2119         }
2120     }
2121     return ret;
2122 }
2123
2124 static BOOL CDecodeSignedMsg_VerifySignatureWithKey(CDecodeMsg *msg,
2125  HCRYPTPROV prov, DWORD signerIndex, PCERT_PUBLIC_KEY_INFO keyInfo)
2126 {
2127     HCRYPTKEY key;
2128     BOOL ret;
2129
2130     if (!prov)
2131         prov = msg->crypt_prov;
2132     ret = CryptImportPublicKeyInfo(prov, X509_ASN_ENCODING, keyInfo, &key);
2133     if (ret)
2134     {
2135         HCRYPTHASH hash;
2136         CRYPT_HASH_BLOB reversedHash;
2137
2138         if (msg->u.signed_data.info->rgSignerInfo[signerIndex].AuthAttrs.cAttr)
2139             hash = msg->u.signed_data.signerHandles[signerIndex].authAttrHash;
2140         else
2141             hash = msg->u.signed_data.signerHandles[signerIndex].contentHash;
2142         ret = CRYPT_ConstructBlob(&reversedHash,
2143          &msg->u.signed_data.info->rgSignerInfo[signerIndex].EncryptedHash);
2144         if (ret)
2145         {
2146             CRYPT_ReverseBytes(&reversedHash);
2147             ret = CryptVerifySignatureW(hash, reversedHash.pbData,
2148              reversedHash.cbData, key, NULL, 0);
2149             CryptMemFree(reversedHash.pbData);
2150         }
2151         CryptDestroyKey(key);
2152     }
2153     return ret;
2154 }
2155
2156 static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
2157 {
2158     BOOL ret = FALSE;
2159     DWORD i;
2160
2161     for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
2162     {
2163         ret = CertCompareCertificateName(X509_ASN_ENCODING,
2164          &msg->u.signed_data.info->rgSignerInfo[i].Issuer, &info->Issuer);
2165         if (ret)
2166         {
2167             ret = CertCompareIntegerBlob(
2168              &msg->u.signed_data.info->rgSignerInfo[i].SerialNumber,
2169              &info->SerialNumber);
2170             if (ret)
2171                 break;
2172         }
2173     }
2174     if (ret)
2175         ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, 0, i,
2176          &info->SubjectPublicKeyInfo);
2177     else
2178         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2179
2180     return ret;
2181 }
2182
2183 static BOOL CDecodeSignedMsg_VerifySignatureEx(CDecodeMsg *msg,
2184  PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA para)
2185 {
2186     BOOL ret = FALSE;
2187
2188     if (para->cbSize != sizeof(CMSG_CTRL_VERIFY_SIGNATURE_EX_PARA))
2189         SetLastError(ERROR_INVALID_PARAMETER);
2190     else if (para->dwSignerIndex >= msg->u.signed_data.info->cSignerInfo)
2191         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2192     else
2193     {
2194         switch (para->dwSignerType)
2195         {
2196         case CMSG_VERIFY_SIGNER_PUBKEY:
2197             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg,
2198              para->hCryptProv, para->dwSignerIndex,
2199              (PCERT_PUBLIC_KEY_INFO)para->pvSigner);
2200             break;
2201         case CMSG_VERIFY_SIGNER_CERT:
2202         {
2203             PCCERT_CONTEXT cert = (PCCERT_CONTEXT)para->pvSigner;
2204
2205             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, para->hCryptProv,
2206              para->dwSignerIndex, &cert->pCertInfo->SubjectPublicKeyInfo);
2207             break;
2208         }
2209         default:
2210             FIXME("unimplemented for signer type %d\n", para->dwSignerType);
2211             SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2212         }
2213     }
2214     return ret;
2215 }
2216
2217 static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2218  DWORD dwCtrlType, const void *pvCtrlPara)
2219 {
2220     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2221     BOOL ret = FALSE;
2222
2223     switch (dwCtrlType)
2224     {
2225     case CMSG_CTRL_VERIFY_SIGNATURE:
2226         switch (msg->type)
2227         {
2228         case CMSG_SIGNED:
2229             ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
2230             break;
2231         default:
2232             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2233         }
2234         break;
2235     case CMSG_CTRL_DECRYPT:
2236         switch (msg->type)
2237         {
2238         default:
2239             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2240         }
2241         break;
2242     case CMSG_CTRL_VERIFY_HASH:
2243         switch (msg->type)
2244         {
2245         case CMSG_HASHED:
2246             ret = CDecodeHashMsg_VerifyHash(msg);
2247             break;
2248         default:
2249             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2250         }
2251         break;
2252     case CMSG_CTRL_VERIFY_SIGNATURE_EX:
2253         switch (msg->type)
2254         {
2255         case CMSG_SIGNED:
2256             ret = CDecodeSignedMsg_VerifySignatureEx(msg,
2257              (PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA)pvCtrlPara);
2258             break;
2259         default:
2260             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2261         }
2262         break;
2263     default:
2264         SetLastError(CRYPT_E_CONTROL_TYPE);
2265     }
2266     return ret;
2267 }
2268
2269 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
2270  DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
2271  PCMSG_STREAM_INFO pStreamInfo)
2272 {
2273     CDecodeMsg *msg;
2274
2275     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
2276      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
2277
2278     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
2279     {
2280         SetLastError(E_INVALIDARG);
2281         return NULL;
2282     }
2283     msg = CryptMemAlloc(sizeof(CDecodeMsg));
2284     if (msg)
2285     {
2286         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
2287          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
2288          CDecodeMsg_Control);
2289         msg->type = dwMsgType;
2290         if (hCryptProv)
2291             msg->crypt_prov = hCryptProv;
2292         else
2293         {
2294             msg->crypt_prov = CRYPT_GetDefaultProvider();
2295             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
2296         }
2297         memset(&msg->u, 0, sizeof(msg->u));
2298         msg->msg_data.cbData = 0;
2299         msg->msg_data.pbData = NULL;
2300         msg->properties = ContextPropertyList_Create();
2301     }
2302     return msg;
2303 }
2304
2305 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
2306 {
2307     TRACE("(%p)\n", hCryptMsg);
2308
2309     if (hCryptMsg)
2310     {
2311         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2312
2313         InterlockedIncrement(&msg->ref);
2314     }
2315     return hCryptMsg;
2316 }
2317
2318 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
2319 {
2320     TRACE("(%p)\n", hCryptMsg);
2321
2322     if (hCryptMsg)
2323     {
2324         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2325
2326         if (InterlockedDecrement(&msg->ref) == 0)
2327         {
2328             TRACE("freeing %p\n", msg);
2329             if (msg->close)
2330                 msg->close(msg);
2331             CryptMemFree(msg);
2332         }
2333     }
2334     return TRUE;
2335 }
2336
2337 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
2338  DWORD cbData, BOOL fFinal)
2339 {
2340     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2341     BOOL ret = FALSE;
2342
2343     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
2344
2345     if (msg->state == MsgStateFinalized)
2346         SetLastError(CRYPT_E_MSG_ERROR);
2347     else
2348     {
2349         ret = msg->update(hCryptMsg, pbData, cbData, fFinal);
2350         msg->state = MsgStateUpdated;
2351         if (fFinal)
2352             msg->state = MsgStateFinalized;
2353     }
2354     return ret;
2355 }
2356
2357 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2358  DWORD dwIndex, void *pvData, DWORD *pcbData)
2359 {
2360     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2361
2362     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
2363      pvData, pcbData);
2364     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
2365 }
2366
2367 BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2368  DWORD dwCtrlType, const void *pvCtrlPara)
2369 {
2370     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2371
2372     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
2373      pvCtrlPara);
2374     return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
2375 }
2376
2377 HCERTSTORE WINAPI CryptGetMessageCertificates(DWORD dwMsgAndCertEncodingType,
2378  HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const BYTE* pbSignedBlob,
2379  DWORD cbSignedBlob)
2380 {
2381     CRYPT_DATA_BLOB blob = { cbSignedBlob, (LPBYTE)pbSignedBlob };
2382
2383     TRACE("(%08x, %ld, %d08x %p, %d)\n", dwMsgAndCertEncodingType, hCryptProv,
2384      dwFlags, pbSignedBlob, cbSignedBlob);
2385
2386     return CertOpenStore(CERT_STORE_PROV_PKCS7, dwMsgAndCertEncodingType,
2387      hCryptProv, dwFlags, &blob);
2388 }
2389
2390 LONG WINAPI CryptGetMessageSignerCount(DWORD dwMsgEncodingType,
2391  const BYTE *pbSignedBlob, DWORD cbSignedBlob)
2392 {
2393     HCRYPTMSG msg;
2394     LONG count = -1;
2395
2396     TRACE("(%08x, %p, %d)\n", dwMsgEncodingType, pbSignedBlob, cbSignedBlob);
2397
2398     msg = CryptMsgOpenToDecode(dwMsgEncodingType, 0, 0, 0, NULL, NULL);
2399     if (msg)
2400     {
2401         if (CryptMsgUpdate(msg, pbSignedBlob, cbSignedBlob, TRUE))
2402         {
2403             DWORD size = sizeof(count);
2404
2405             CryptMsgGetParam(msg, CMSG_SIGNER_COUNT_PARAM, 0, &count, &size);
2406         }
2407         CryptMsgClose(msg);
2408     }
2409     return count;
2410 }
2411
2412 static CERT_INFO *CRYPT_GetSignerCertInfoFromMsg(HCRYPTMSG msg,
2413  DWORD dwSignerIndex)
2414 {
2415     CERT_INFO *certInfo = NULL;
2416     DWORD size;
2417
2418     if (CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM, dwSignerIndex, NULL,
2419      &size))
2420     {
2421         certInfo = CryptMemAlloc(size);
2422         if (certInfo)
2423         {
2424             if (!CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM,
2425              dwSignerIndex, certInfo, &size))
2426             {
2427                 CryptMemFree(certInfo);
2428                 certInfo = NULL;
2429             }
2430         }
2431     }
2432     return certInfo;
2433 }
2434
2435 static PCCERT_CONTEXT WINAPI CRYPT_DefaultGetSignerCertificate(void *pvGetArg,
2436  DWORD dwCertEncodingType, PCERT_INFO pSignerId, HCERTSTORE hMsgCertStore)
2437 {
2438     return CertFindCertificateInStore(hMsgCertStore, dwCertEncodingType, 0,
2439      CERT_FIND_SUBJECT_CERT, pSignerId, NULL);
2440 }
2441
2442 static inline PCCERT_CONTEXT CRYPT_GetSignerCertificate(HCRYPTMSG msg,
2443  PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara, PCERT_INFO certInfo, HCERTSTORE store)
2444 {
2445     PFN_CRYPT_GET_SIGNER_CERTIFICATE getCert;
2446
2447     if (pVerifyPara->pfnGetSignerCertificate)
2448         getCert = pVerifyPara->pfnGetSignerCertificate;
2449     else
2450         getCert = CRYPT_DefaultGetSignerCertificate;
2451     return getCert(pVerifyPara->pvGetArg,
2452      pVerifyPara->dwMsgAndCertEncodingType, certInfo, store);
2453 }
2454
2455 BOOL WINAPI CryptVerifyMessageSignature(PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara,
2456  DWORD dwSignerIndex, const BYTE* pbSignedBlob, DWORD cbSignedBlob,
2457  BYTE* pbDecoded, DWORD* pcbDecoded, PCCERT_CONTEXT* ppSignerCert)
2458 {
2459     BOOL ret = FALSE;
2460     DWORD size;
2461     CRYPT_CONTENT_INFO *contentInfo;
2462
2463     TRACE("(%p, %d, %p, %d, %p, %p, %p)\n",
2464      pVerifyPara, dwSignerIndex, pbSignedBlob, cbSignedBlob,
2465      pbDecoded, pcbDecoded, ppSignerCert);
2466
2467     if (ppSignerCert)
2468         *ppSignerCert = NULL;
2469     if (pcbDecoded)
2470         *pcbDecoded = 0;
2471     if (!pVerifyPara ||
2472      pVerifyPara->cbSize != sizeof(CRYPT_VERIFY_MESSAGE_PARA) ||
2473      GET_CMSG_ENCODING_TYPE(pVerifyPara->dwMsgAndCertEncodingType) !=
2474      PKCS_7_ASN_ENCODING)
2475     {
2476         SetLastError(E_INVALIDARG);
2477         return FALSE;
2478     }
2479
2480     ret = CryptDecodeObjectEx(pVerifyPara->dwMsgAndCertEncodingType,
2481      PKCS_CONTENT_INFO, pbSignedBlob, cbSignedBlob,
2482      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2483      (LPBYTE)&contentInfo, &size);
2484     if (ret)
2485     {
2486         if (strcmp(contentInfo->pszObjId, szOID_RSA_signedData))
2487         {
2488             SetLastError(CRYPT_E_UNEXPECTED_MSG_TYPE);
2489             ret = FALSE;
2490         }
2491         else
2492         {
2493             HCRYPTMSG msg = CryptMsgOpenToDecode(
2494              pVerifyPara->dwMsgAndCertEncodingType, 0, CMSG_SIGNED,
2495              pVerifyPara->hCryptProv, NULL, NULL);
2496
2497             if (msg)
2498             {
2499                 ret = CryptMsgUpdate(msg, contentInfo->Content.pbData,
2500                  contentInfo->Content.cbData, TRUE);
2501                 if (ret && pcbDecoded)
2502                     ret = CRYPT_CopyParam(pbDecoded, pcbDecoded,
2503                      contentInfo->Content.pbData, contentInfo->Content.cbData);
2504                 if (ret)
2505                 {
2506                     CERT_INFO *certInfo = CRYPT_GetSignerCertInfoFromMsg(msg,
2507                      dwSignerIndex);
2508
2509                     ret = FALSE;
2510                     if (certInfo)
2511                     {
2512                         HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MSG,
2513                          pVerifyPara->dwMsgAndCertEncodingType,
2514                          pVerifyPara->hCryptProv, 0, msg);
2515
2516                         if (store)
2517                         {
2518                             PCCERT_CONTEXT cert = CRYPT_GetSignerCertificate(
2519                              msg, pVerifyPara, certInfo, store);
2520
2521                             if (cert)
2522                             {
2523                                 ret = CryptMsgControl(msg, 0,
2524                                  CMSG_CTRL_VERIFY_SIGNATURE, cert->pCertInfo);
2525                                 if (ret && ppSignerCert)
2526                                     *ppSignerCert = cert;
2527                                 else
2528                                     CertFreeCertificateContext(cert);
2529                             }
2530                             CertCloseStore(store, 0);
2531                         }
2532                     }
2533                     CryptMemFree(certInfo);
2534                 }
2535                 CryptMsgClose(msg);
2536             }
2537         }
2538         LocalFree(contentInfo);
2539     }
2540     TRACE("returning %d\n", ret);
2541     return ret;
2542 }