crypt32: Correct copying a signer info's attributes.
[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                 *nextData += in->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
1780                 for (j = 0; j < in->rgAttr[i].cValue; j++)
1781                     CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
1782                      &in->rgAttr[i].rgValue[j], nextData);
1783             }
1784         }
1785     }
1786 }
1787
1788 static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
1789 {
1790     DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;
1791
1792     for (i = 0; i < attr->cAttr; i++)
1793     {
1794         if (attr->rgAttr[i].pszObjId)
1795             size += strlen(attr->rgAttr[i].pszObjId) + 1;
1796         /* align pointer */
1797         if (size % sizeof(DWORD_PTR))
1798             size += size % sizeof(DWORD_PTR);
1799         size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
1800         for (j = 0; j < attr->rgAttr[i].cValue; j++)
1801             size += attr->rgAttr[i].rgValue[j].cbData;
1802     }
1803     return size;
1804 }
1805
1806 static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
1807  const CMSG_SIGNER_INFO *in)
1808 {
1809     DWORD size = sizeof(CMSG_SIGNER_INFO);
1810     BOOL ret;
1811
1812     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
1813
1814     size += in->Issuer.cbData;
1815     size += in->SerialNumber.cbData;
1816     if (in->HashAlgorithm.pszObjId)
1817         size += strlen(in->HashAlgorithm.pszObjId) + 1;
1818     size += in->HashAlgorithm.Parameters.cbData;
1819     if (in->HashEncryptionAlgorithm.pszObjId)
1820         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
1821     size += in->HashEncryptionAlgorithm.Parameters.cbData;
1822     size += in->EncryptedHash.cbData;
1823     /* align pointer */
1824     if (size % sizeof(DWORD_PTR))
1825         size += size % sizeof(DWORD_PTR);
1826     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
1827     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
1828     if (!pvData)
1829     {
1830         *pcbData = size;
1831         ret = TRUE;
1832     }
1833     else if (*pcbData < size)
1834     {
1835         *pcbData = size;
1836         SetLastError(ERROR_MORE_DATA);
1837         ret = FALSE;
1838     }
1839     else
1840     {
1841         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
1842         CMSG_SIGNER_INFO *out = (CMSG_SIGNER_INFO *)pvData;
1843
1844         out->dwVersion = in->dwVersion;
1845         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1846         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1847         CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
1848          &nextData);
1849         CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
1850          &in->HashEncryptionAlgorithm, &nextData);
1851         CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
1852         /* align pointer */
1853         if ((nextData - (LPBYTE)0) % sizeof(DWORD_PTR))
1854             nextData += (nextData - (LPBYTE)0) % sizeof(DWORD_PTR);
1855         CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
1856         CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
1857         ret = TRUE;
1858     }
1859     TRACE("returning %d\n", ret);
1860     return ret;
1861 }
1862
1863 static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
1864  const CMSG_SIGNER_INFO *in)
1865 {
1866     DWORD size = sizeof(CERT_INFO);
1867     BOOL ret;
1868
1869     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
1870
1871     size += in->Issuer.cbData;
1872     size += in->SerialNumber.cbData;
1873     if (!pvData)
1874     {
1875         *pcbData = size;
1876         ret = TRUE;
1877     }
1878     else if (*pcbData < size)
1879     {
1880         *pcbData = size;
1881         SetLastError(ERROR_MORE_DATA);
1882         ret = FALSE;
1883     }
1884     else
1885     {
1886         LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
1887         CERT_INFO *out = (CERT_INFO *)pvData;
1888
1889         memset(out, 0, sizeof(CERT_INFO));
1890         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1891         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1892         ret = TRUE;
1893     }
1894     TRACE("returning %d\n", ret);
1895     return ret;
1896 }
1897
1898 static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1899  DWORD dwIndex, void *pvData, DWORD *pcbData)
1900 {
1901     BOOL ret = FALSE;
1902
1903     switch (dwParamType)
1904     {
1905     case CMSG_TYPE_PARAM:
1906         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1907         break;
1908     case CMSG_CONTENT_PARAM:
1909         if (msg->u.signed_data.info)
1910         {
1911             if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1912              szOID_RSA_data))
1913             {
1914                 CRYPT_DATA_BLOB *blob;
1915                 DWORD size;
1916
1917                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1918                  msg->u.signed_data.info->content.Content.pbData,
1919                  msg->u.signed_data.info->content.Content.cbData,
1920                  CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1921                 if (ret)
1922                 {
1923                     ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
1924                      blob->cbData);
1925                     LocalFree(blob);
1926                 }
1927             }
1928             else
1929                 ret = CRYPT_CopyParam(pvData, pcbData,
1930                  msg->u.signed_data.info->content.Content.pbData,
1931                  msg->u.signed_data.info->content.Content.cbData);
1932         }
1933         else
1934             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1935         break;
1936     case CMSG_INNER_CONTENT_TYPE_PARAM:
1937         if (msg->u.signed_data.info)
1938             ret = CRYPT_CopyParam(pvData, pcbData,
1939              msg->u.signed_data.info->content.pszObjId,
1940              strlen(msg->u.signed_data.info->content.pszObjId) + 1);
1941         else
1942             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1943         break;
1944     case CMSG_SIGNER_COUNT_PARAM:
1945         if (msg->u.signed_data.info)
1946             ret = CRYPT_CopyParam(pvData, pcbData,
1947              &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
1948         else
1949             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1950         break;
1951     case CMSG_SIGNER_INFO_PARAM:
1952         if (msg->u.signed_data.info)
1953         {
1954             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1955                 SetLastError(CRYPT_E_INVALID_INDEX);
1956             else
1957                 ret = CRYPT_CopySignerInfo(pvData, pcbData,
1958                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1959         }
1960         else
1961             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1962         break;
1963     case CMSG_SIGNER_CERT_INFO_PARAM:
1964         if (msg->u.signed_data.info)
1965         {
1966             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1967                 SetLastError(CRYPT_E_INVALID_INDEX);
1968             else
1969                 ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
1970                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1971         }
1972         else
1973             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1974         break;
1975     case CMSG_CERT_COUNT_PARAM:
1976         if (msg->u.signed_data.info)
1977             ret = CRYPT_CopyParam(pvData, pcbData,
1978              &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
1979         else
1980             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1981         break;
1982     case CMSG_CERT_PARAM:
1983         if (msg->u.signed_data.info)
1984         {
1985             if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
1986                 SetLastError(CRYPT_E_INVALID_INDEX);
1987             else
1988                 ret = CRYPT_CopyParam(pvData, pcbData,
1989                  msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
1990                  msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
1991         }
1992         else
1993             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1994         break;
1995     case CMSG_CRL_COUNT_PARAM:
1996         if (msg->u.signed_data.info)
1997             ret = CRYPT_CopyParam(pvData, pcbData,
1998              &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
1999         else
2000             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2001         break;
2002     case CMSG_CRL_PARAM:
2003         if (msg->u.signed_data.info)
2004         {
2005             if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
2006                 SetLastError(CRYPT_E_INVALID_INDEX);
2007             else
2008                 ret = CRYPT_CopyParam(pvData, pcbData,
2009                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
2010                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
2011         }
2012         else
2013             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2014         break;
2015     case CMSG_COMPUTED_HASH_PARAM:
2016         if (msg->u.signed_data.info)
2017         {
2018             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2019                 SetLastError(CRYPT_E_INVALID_INDEX);
2020             else
2021                 ret = CryptGetHashParam(
2022                  msg->u.signed_data.signerHandles[dwIndex].contentHash,
2023                  HP_HASHVAL, pvData, pcbData, 0);
2024         }
2025         else
2026             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2027         break;
2028     case CMSG_ATTR_CERT_COUNT_PARAM:
2029         if (msg->u.signed_data.info)
2030         {
2031             DWORD attrCertCount = 0;
2032
2033             ret = CRYPT_CopyParam(pvData, pcbData,
2034              &attrCertCount, sizeof(DWORD));
2035         }
2036         else
2037             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2038         break;
2039     case CMSG_ATTR_CERT_PARAM:
2040         if (msg->u.signed_data.info)
2041             SetLastError(CRYPT_E_INVALID_INDEX);
2042         else
2043             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2044         break;
2045     default:
2046         FIXME("unimplemented for %d\n", dwParamType);
2047         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2048     }
2049     return ret;
2050 }
2051
2052 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2053  DWORD dwIndex, void *pvData, DWORD *pcbData)
2054 {
2055     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2056     BOOL ret = FALSE;
2057
2058     switch (msg->type)
2059     {
2060     case CMSG_HASHED:
2061         ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2062          pcbData);
2063         break;
2064     case CMSG_SIGNED:
2065         ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2066          pcbData);
2067         break;
2068     default:
2069         switch (dwParamType)
2070         {
2071         case CMSG_TYPE_PARAM:
2072             ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
2073              sizeof(msg->type));
2074             break;
2075         default:
2076         {
2077             CRYPT_DATA_BLOB blob;
2078
2079             ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2080              &blob);
2081             if (ret)
2082                 ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
2083                  blob.cbData);
2084             else
2085                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2086         }
2087         }
2088     }
2089     return ret;
2090 }
2091
2092 static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
2093 {
2094     BOOL ret;
2095     CRYPT_DATA_BLOB hashBlob;
2096
2097     ret = ContextPropertyList_FindProperty(msg->properties,
2098      CMSG_HASH_DATA_PARAM, &hashBlob);
2099     if (ret)
2100     {
2101         DWORD computedHashSize = 0;
2102
2103         ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
2104          &computedHashSize);
2105         if (hashBlob.cbData == computedHashSize)
2106         {
2107             LPBYTE computedHash = CryptMemAlloc(computedHashSize);
2108
2109             if (computedHash)
2110             {
2111                 ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
2112                  computedHash, &computedHashSize);
2113                 if (ret)
2114                     ret = !memcmp(hashBlob.pbData, computedHash,
2115                      hashBlob.cbData);
2116                 CryptMemFree(computedHash);
2117             }
2118             else
2119                 ret = FALSE;
2120         }
2121     }
2122     return ret;
2123 }
2124
2125 static BOOL CDecodeSignedMsg_VerifySignatureWithKey(CDecodeMsg *msg,
2126  HCRYPTPROV prov, DWORD signerIndex, PCERT_PUBLIC_KEY_INFO keyInfo)
2127 {
2128     HCRYPTKEY key;
2129     BOOL ret;
2130
2131     if (!prov)
2132         prov = msg->crypt_prov;
2133     ret = CryptImportPublicKeyInfo(prov, X509_ASN_ENCODING, keyInfo, &key);
2134     if (ret)
2135     {
2136         HCRYPTHASH hash;
2137         CRYPT_HASH_BLOB reversedHash;
2138
2139         if (msg->u.signed_data.info->rgSignerInfo[signerIndex].AuthAttrs.cAttr)
2140             hash = msg->u.signed_data.signerHandles[signerIndex].authAttrHash;
2141         else
2142             hash = msg->u.signed_data.signerHandles[signerIndex].contentHash;
2143         ret = CRYPT_ConstructBlob(&reversedHash,
2144          &msg->u.signed_data.info->rgSignerInfo[signerIndex].EncryptedHash);
2145         if (ret)
2146         {
2147             CRYPT_ReverseBytes(&reversedHash);
2148             ret = CryptVerifySignatureW(hash, reversedHash.pbData,
2149              reversedHash.cbData, key, NULL, 0);
2150             CryptMemFree(reversedHash.pbData);
2151         }
2152         CryptDestroyKey(key);
2153     }
2154     return ret;
2155 }
2156
2157 static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
2158 {
2159     BOOL ret = FALSE;
2160     DWORD i;
2161
2162     for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
2163     {
2164         ret = CertCompareCertificateName(X509_ASN_ENCODING,
2165          &msg->u.signed_data.info->rgSignerInfo[i].Issuer, &info->Issuer);
2166         if (ret)
2167         {
2168             ret = CertCompareIntegerBlob(
2169              &msg->u.signed_data.info->rgSignerInfo[i].SerialNumber,
2170              &info->SerialNumber);
2171             if (ret)
2172                 break;
2173         }
2174     }
2175     if (ret)
2176         ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, 0, i,
2177          &info->SubjectPublicKeyInfo);
2178     else
2179         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2180
2181     return ret;
2182 }
2183
2184 static BOOL CDecodeSignedMsg_VerifySignatureEx(CDecodeMsg *msg,
2185  PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA para)
2186 {
2187     BOOL ret = FALSE;
2188
2189     if (para->cbSize != sizeof(CMSG_CTRL_VERIFY_SIGNATURE_EX_PARA))
2190         SetLastError(ERROR_INVALID_PARAMETER);
2191     else if (para->dwSignerIndex >= msg->u.signed_data.info->cSignerInfo)
2192         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2193     else
2194     {
2195         switch (para->dwSignerType)
2196         {
2197         case CMSG_VERIFY_SIGNER_PUBKEY:
2198             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg,
2199              para->hCryptProv, para->dwSignerIndex,
2200              (PCERT_PUBLIC_KEY_INFO)para->pvSigner);
2201             break;
2202         case CMSG_VERIFY_SIGNER_CERT:
2203         {
2204             PCCERT_CONTEXT cert = (PCCERT_CONTEXT)para->pvSigner;
2205
2206             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, para->hCryptProv,
2207              para->dwSignerIndex, &cert->pCertInfo->SubjectPublicKeyInfo);
2208             break;
2209         }
2210         default:
2211             FIXME("unimplemented for signer type %d\n", para->dwSignerType);
2212             SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2213         }
2214     }
2215     return ret;
2216 }
2217
2218 static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2219  DWORD dwCtrlType, const void *pvCtrlPara)
2220 {
2221     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2222     BOOL ret = FALSE;
2223
2224     switch (dwCtrlType)
2225     {
2226     case CMSG_CTRL_VERIFY_SIGNATURE:
2227         switch (msg->type)
2228         {
2229         case CMSG_SIGNED:
2230             ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
2231             break;
2232         default:
2233             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2234         }
2235         break;
2236     case CMSG_CTRL_DECRYPT:
2237         switch (msg->type)
2238         {
2239         default:
2240             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2241         }
2242         break;
2243     case CMSG_CTRL_VERIFY_HASH:
2244         switch (msg->type)
2245         {
2246         case CMSG_HASHED:
2247             ret = CDecodeHashMsg_VerifyHash(msg);
2248             break;
2249         default:
2250             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2251         }
2252         break;
2253     case CMSG_CTRL_VERIFY_SIGNATURE_EX:
2254         switch (msg->type)
2255         {
2256         case CMSG_SIGNED:
2257             ret = CDecodeSignedMsg_VerifySignatureEx(msg,
2258              (PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA)pvCtrlPara);
2259             break;
2260         default:
2261             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2262         }
2263         break;
2264     default:
2265         SetLastError(CRYPT_E_CONTROL_TYPE);
2266     }
2267     return ret;
2268 }
2269
2270 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
2271  DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
2272  PCMSG_STREAM_INFO pStreamInfo)
2273 {
2274     CDecodeMsg *msg;
2275
2276     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
2277      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
2278
2279     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
2280     {
2281         SetLastError(E_INVALIDARG);
2282         return NULL;
2283     }
2284     msg = CryptMemAlloc(sizeof(CDecodeMsg));
2285     if (msg)
2286     {
2287         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
2288          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
2289          CDecodeMsg_Control);
2290         msg->type = dwMsgType;
2291         if (hCryptProv)
2292             msg->crypt_prov = hCryptProv;
2293         else
2294         {
2295             msg->crypt_prov = CRYPT_GetDefaultProvider();
2296             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
2297         }
2298         memset(&msg->u, 0, sizeof(msg->u));
2299         msg->msg_data.cbData = 0;
2300         msg->msg_data.pbData = NULL;
2301         msg->properties = ContextPropertyList_Create();
2302     }
2303     return msg;
2304 }
2305
2306 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
2307 {
2308     TRACE("(%p)\n", hCryptMsg);
2309
2310     if (hCryptMsg)
2311     {
2312         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2313
2314         InterlockedIncrement(&msg->ref);
2315     }
2316     return hCryptMsg;
2317 }
2318
2319 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
2320 {
2321     TRACE("(%p)\n", hCryptMsg);
2322
2323     if (hCryptMsg)
2324     {
2325         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2326
2327         if (InterlockedDecrement(&msg->ref) == 0)
2328         {
2329             TRACE("freeing %p\n", msg);
2330             if (msg->close)
2331                 msg->close(msg);
2332             CryptMemFree(msg);
2333         }
2334     }
2335     return TRUE;
2336 }
2337
2338 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
2339  DWORD cbData, BOOL fFinal)
2340 {
2341     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2342     BOOL ret = FALSE;
2343
2344     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
2345
2346     if (msg->state == MsgStateFinalized)
2347         SetLastError(CRYPT_E_MSG_ERROR);
2348     else
2349     {
2350         ret = msg->update(hCryptMsg, pbData, cbData, fFinal);
2351         msg->state = MsgStateUpdated;
2352         if (fFinal)
2353             msg->state = MsgStateFinalized;
2354     }
2355     return ret;
2356 }
2357
2358 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2359  DWORD dwIndex, void *pvData, DWORD *pcbData)
2360 {
2361     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2362
2363     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
2364      pvData, pcbData);
2365     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
2366 }
2367
2368 BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2369  DWORD dwCtrlType, const void *pvCtrlPara)
2370 {
2371     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2372
2373     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
2374      pvCtrlPara);
2375     return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
2376 }
2377
2378 HCERTSTORE WINAPI CryptGetMessageCertificates(DWORD dwMsgAndCertEncodingType,
2379  HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const BYTE* pbSignedBlob,
2380  DWORD cbSignedBlob)
2381 {
2382     CRYPT_DATA_BLOB blob = { cbSignedBlob, (LPBYTE)pbSignedBlob };
2383
2384     TRACE("(%08x, %ld, %d08x %p, %d)\n", dwMsgAndCertEncodingType, hCryptProv,
2385      dwFlags, pbSignedBlob, cbSignedBlob);
2386
2387     return CertOpenStore(CERT_STORE_PROV_PKCS7, dwMsgAndCertEncodingType,
2388      hCryptProv, dwFlags, &blob);
2389 }
2390
2391 LONG WINAPI CryptGetMessageSignerCount(DWORD dwMsgEncodingType,
2392  const BYTE *pbSignedBlob, DWORD cbSignedBlob)
2393 {
2394     HCRYPTMSG msg;
2395     LONG count = -1;
2396
2397     TRACE("(%08x, %p, %d)\n", dwMsgEncodingType, pbSignedBlob, cbSignedBlob);
2398
2399     msg = CryptMsgOpenToDecode(dwMsgEncodingType, 0, 0, 0, NULL, NULL);
2400     if (msg)
2401     {
2402         if (CryptMsgUpdate(msg, pbSignedBlob, cbSignedBlob, TRUE))
2403         {
2404             DWORD size = sizeof(count);
2405
2406             CryptMsgGetParam(msg, CMSG_SIGNER_COUNT_PARAM, 0, &count, &size);
2407         }
2408         CryptMsgClose(msg);
2409     }
2410     return count;
2411 }
2412
2413 static CERT_INFO *CRYPT_GetSignerCertInfoFromMsg(HCRYPTMSG msg,
2414  DWORD dwSignerIndex)
2415 {
2416     CERT_INFO *certInfo = NULL;
2417     DWORD size;
2418
2419     if (CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM, dwSignerIndex, NULL,
2420      &size))
2421     {
2422         certInfo = CryptMemAlloc(size);
2423         if (certInfo)
2424         {
2425             if (!CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM,
2426              dwSignerIndex, certInfo, &size))
2427             {
2428                 CryptMemFree(certInfo);
2429                 certInfo = NULL;
2430             }
2431         }
2432     }
2433     return certInfo;
2434 }
2435
2436 static PCCERT_CONTEXT WINAPI CRYPT_DefaultGetSignerCertificate(void *pvGetArg,
2437  DWORD dwCertEncodingType, PCERT_INFO pSignerId, HCERTSTORE hMsgCertStore)
2438 {
2439     return CertFindCertificateInStore(hMsgCertStore, dwCertEncodingType, 0,
2440      CERT_FIND_SUBJECT_CERT, pSignerId, NULL);
2441 }
2442
2443 static inline PCCERT_CONTEXT CRYPT_GetSignerCertificate(HCRYPTMSG msg,
2444  PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara, PCERT_INFO certInfo, HCERTSTORE store)
2445 {
2446     PFN_CRYPT_GET_SIGNER_CERTIFICATE getCert;
2447
2448     if (pVerifyPara->pfnGetSignerCertificate)
2449         getCert = pVerifyPara->pfnGetSignerCertificate;
2450     else
2451         getCert = CRYPT_DefaultGetSignerCertificate;
2452     return getCert(pVerifyPara->pvGetArg,
2453      pVerifyPara->dwMsgAndCertEncodingType, certInfo, store);
2454 }
2455
2456 BOOL WINAPI CryptVerifyMessageSignature(PCRYPT_VERIFY_MESSAGE_PARA pVerifyPara,
2457  DWORD dwSignerIndex, const BYTE* pbSignedBlob, DWORD cbSignedBlob,
2458  BYTE* pbDecoded, DWORD* pcbDecoded, PCCERT_CONTEXT* ppSignerCert)
2459 {
2460     BOOL ret = FALSE;
2461     DWORD size;
2462     CRYPT_CONTENT_INFO *contentInfo;
2463
2464     TRACE("(%p, %d, %p, %d, %p, %p, %p)\n",
2465      pVerifyPara, dwSignerIndex, pbSignedBlob, cbSignedBlob,
2466      pbDecoded, pcbDecoded, ppSignerCert);
2467
2468     if (ppSignerCert)
2469         *ppSignerCert = NULL;
2470     if (pcbDecoded)
2471         *pcbDecoded = 0;
2472     if (!pVerifyPara ||
2473      pVerifyPara->cbSize != sizeof(CRYPT_VERIFY_MESSAGE_PARA) ||
2474      GET_CMSG_ENCODING_TYPE(pVerifyPara->dwMsgAndCertEncodingType) !=
2475      PKCS_7_ASN_ENCODING)
2476     {
2477         SetLastError(E_INVALIDARG);
2478         return FALSE;
2479     }
2480
2481     ret = CryptDecodeObjectEx(pVerifyPara->dwMsgAndCertEncodingType,
2482      PKCS_CONTENT_INFO, pbSignedBlob, cbSignedBlob,
2483      CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2484      (LPBYTE)&contentInfo, &size);
2485     if (ret)
2486     {
2487         if (strcmp(contentInfo->pszObjId, szOID_RSA_signedData))
2488         {
2489             SetLastError(CRYPT_E_UNEXPECTED_MSG_TYPE);
2490             ret = FALSE;
2491         }
2492         else
2493         {
2494             HCRYPTMSG msg = CryptMsgOpenToDecode(
2495              pVerifyPara->dwMsgAndCertEncodingType, 0, CMSG_SIGNED,
2496              pVerifyPara->hCryptProv, NULL, NULL);
2497
2498             if (msg)
2499             {
2500                 ret = CryptMsgUpdate(msg, contentInfo->Content.pbData,
2501                  contentInfo->Content.cbData, TRUE);
2502                 if (ret && pcbDecoded)
2503                     ret = CRYPT_CopyParam(pbDecoded, pcbDecoded,
2504                      contentInfo->Content.pbData, contentInfo->Content.cbData);
2505                 if (ret)
2506                 {
2507                     CERT_INFO *certInfo = CRYPT_GetSignerCertInfoFromMsg(msg,
2508                      dwSignerIndex);
2509
2510                     ret = FALSE;
2511                     if (certInfo)
2512                     {
2513                         HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MSG,
2514                          pVerifyPara->dwMsgAndCertEncodingType,
2515                          pVerifyPara->hCryptProv, 0, msg);
2516
2517                         if (store)
2518                         {
2519                             PCCERT_CONTEXT cert = CRYPT_GetSignerCertificate(
2520                              msg, pVerifyPara, certInfo, store);
2521
2522                             if (cert)
2523                             {
2524                                 ret = CryptMsgControl(msg, 0,
2525                                  CMSG_CTRL_VERIFY_SIGNATURE, cert->pCertInfo);
2526                                 if (ret && ppSignerCert)
2527                                     *ppSignerCert = cert;
2528                                 else
2529                                     CertFreeCertificateContext(cert);
2530                             }
2531                             CertCloseStore(store, 0);
2532                         }
2533                     }
2534                     CryptMemFree(certInfo);
2535                 }
2536                 CryptMsgClose(msg);
2537             }
2538         }
2539         LocalFree(contentInfo);
2540     }
2541     TRACE("returning %d\n", ret);
2542     return ret;
2543 }