hlink: Use an iface instead of a vtbl pointer in HlinkBCImpl.
[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
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdarg.h>
23 #define NONAMELESSUNION
24 #include "windef.h"
25 #include "winbase.h"
26 #include "wincrypt.h"
27 #include "snmp.h"
28
29 #include "wine/debug.h"
30 #include "wine/exception.h"
31 #include "crypt32_private.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
34
35 /* Called when a message's ref count reaches zero.  Free any message-specific
36  * data here.
37  */
38 typedef void (*CryptMsgCloseFunc)(HCRYPTMSG msg);
39
40 typedef BOOL (*CryptMsgGetParamFunc)(HCRYPTMSG hCryptMsg, DWORD dwParamType,
41  DWORD dwIndex, void *pvData, DWORD *pcbData);
42
43 typedef BOOL (*CryptMsgUpdateFunc)(HCRYPTMSG hCryptMsg, const BYTE *pbData,
44  DWORD cbData, BOOL fFinal);
45
46 typedef BOOL (*CryptMsgControlFunc)(HCRYPTMSG hCryptMsg, DWORD dwFlags,
47  DWORD dwCtrlType, const void *pvCtrlPara);
48
49 static BOOL CRYPT_DefaultMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
50  DWORD dwCtrlType, const void *pvCtrlPara)
51 {
52     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
53     SetLastError(E_INVALIDARG);
54     return FALSE;
55 }
56
57 typedef enum _CryptMsgState {
58     MsgStateInit,
59     MsgStateUpdated,
60     MsgStateDataFinalized,
61     MsgStateFinalized
62 } CryptMsgState;
63
64 typedef struct _CryptMsgBase
65 {
66     LONG                 ref;
67     DWORD                open_flags;
68     BOOL                 streamed;
69     CMSG_STREAM_INFO     stream_info;
70     CryptMsgState        state;
71     CryptMsgCloseFunc    close;
72     CryptMsgUpdateFunc   update;
73     CryptMsgGetParamFunc get_param;
74     CryptMsgControlFunc  control;
75 } CryptMsgBase;
76
77 static inline void CryptMsgBase_Init(CryptMsgBase *msg, DWORD dwFlags,
78  PCMSG_STREAM_INFO pStreamInfo, CryptMsgCloseFunc close,
79  CryptMsgGetParamFunc get_param, CryptMsgUpdateFunc update,
80  CryptMsgControlFunc control)
81 {
82     msg->ref = 1;
83     msg->open_flags = dwFlags;
84     if (pStreamInfo)
85     {
86         msg->streamed = TRUE;
87         msg->stream_info = *pStreamInfo;
88     }
89     else
90     {
91         msg->streamed = FALSE;
92         memset(&msg->stream_info, 0, sizeof(msg->stream_info));
93     }
94     msg->close = close;
95     msg->get_param = get_param;
96     msg->update = update;
97     msg->control = control;
98     msg->state = MsgStateInit;
99 }
100
101 typedef struct _CDataEncodeMsg
102 {
103     CryptMsgBase base;
104     DWORD        bare_content_len;
105     LPBYTE       bare_content;
106 } CDataEncodeMsg;
107
108 static const BYTE empty_data_content[] = { 0x04,0x00 };
109
110 static void CDataEncodeMsg_Close(HCRYPTMSG hCryptMsg)
111 {
112     CDataEncodeMsg *msg = hCryptMsg;
113
114     if (msg->bare_content != empty_data_content)
115         LocalFree(msg->bare_content);
116 }
117
118 static BOOL WINAPI CRYPT_EncodeContentLength(DWORD dwCertEncodingType,
119  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
120  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
121 {
122     DWORD dataLen = *(DWORD *)pvStructInfo;
123     DWORD lenBytes;
124     BOOL ret = TRUE;
125
126     /* Trick:  report bytes needed based on total message length, even though
127      * the message isn't available yet.  The caller will use the length
128      * reported here to encode its length.
129      */
130     CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
131     if (!pbEncoded)
132         *pcbEncoded = 1 + lenBytes + dataLen;
133     else
134     {
135         if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
136          pcbEncoded, 1 + lenBytes)))
137         {
138             if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
139                 pbEncoded = *(BYTE **)pbEncoded;
140             *pbEncoded++ = ASN_OCTETSTRING;
141             CRYPT_EncodeLen(dataLen, pbEncoded,
142              &lenBytes);
143         }
144     }
145     return ret;
146 }
147
148 static BOOL CRYPT_EncodeDataContentInfoHeader(const CDataEncodeMsg *msg,
149  CRYPT_DATA_BLOB *header)
150 {
151     BOOL ret;
152
153     if (msg->base.streamed && msg->base.stream_info.cbContent == 0xffffffff)
154     {
155         static const BYTE headerValue[] = { 0x30,0x80,0x06,0x09,0x2a,0x86,0x48,
156          0x86,0xf7,0x0d,0x01,0x07,0x01,0xa0,0x80,0x24,0x80 };
157
158         header->pbData = LocalAlloc(0, sizeof(headerValue));
159         if (header->pbData)
160         {
161             header->cbData = sizeof(headerValue);
162             memcpy(header->pbData, headerValue, sizeof(headerValue));
163             ret = TRUE;
164         }
165         else
166             ret = FALSE;
167     }
168     else
169     {
170         struct AsnConstructedItem constructed = { 0,
171          &msg->base.stream_info.cbContent, CRYPT_EncodeContentLength };
172         struct AsnEncodeSequenceItem items[2] = {
173          { szOID_RSA_data, CRYPT_AsnEncodeOid, 0 },
174          { &constructed,   CRYPT_AsnEncodeConstructed, 0 },
175         };
176
177         ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
178          sizeof(items) / sizeof(items[0]), CRYPT_ENCODE_ALLOC_FLAG, NULL,
179          (LPBYTE)&header->pbData, &header->cbData);
180         if (ret)
181         {
182             /* Trick:  subtract the content length from the reported length,
183              * as the actual content hasn't come yet.
184              */
185             header->cbData -= msg->base.stream_info.cbContent;
186         }
187     }
188     return ret;
189 }
190
191 static BOOL CDataEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
192  DWORD cbData, BOOL fFinal)
193 {
194     CDataEncodeMsg *msg = hCryptMsg;
195     BOOL ret = FALSE;
196
197     if (msg->base.state == MsgStateFinalized)
198         SetLastError(CRYPT_E_MSG_ERROR);
199     else if (msg->base.streamed)
200     {
201         __TRY
202         {
203             if (msg->base.state != MsgStateUpdated)
204             {
205                 CRYPT_DATA_BLOB header;
206
207                 ret = CRYPT_EncodeDataContentInfoHeader(msg, &header);
208                 if (ret)
209                 {
210                     ret = msg->base.stream_info.pfnStreamOutput(
211                      msg->base.stream_info.pvArg, header.pbData, header.cbData,
212                      FALSE);
213                     LocalFree(header.pbData);
214                 }
215             }
216             /* Curiously, every indefinite-length streamed update appears to
217              * get its own tag and length, regardless of fFinal.
218              */
219             if (msg->base.stream_info.cbContent == 0xffffffff)
220             {
221                 BYTE *header;
222                 DWORD headerLen;
223
224                 ret = CRYPT_EncodeContentLength(X509_ASN_ENCODING, NULL,
225                  &cbData, CRYPT_ENCODE_ALLOC_FLAG, NULL, (BYTE *)&header,
226                  &headerLen);
227                 if (ret)
228                 {
229                     ret = msg->base.stream_info.pfnStreamOutput(
230                      msg->base.stream_info.pvArg, header, headerLen,
231                      FALSE);
232                     LocalFree(header);
233                 }
234             }
235             if (!fFinal)
236             {
237                 ret = msg->base.stream_info.pfnStreamOutput(
238                  msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
239                  FALSE);
240                 msg->base.state = MsgStateUpdated;
241             }
242             else
243             {
244                 msg->base.state = MsgStateFinalized;
245                 if (msg->base.stream_info.cbContent == 0xffffffff)
246                 {
247                     BYTE indefinite_trailer[6] = { 0 };
248
249                     ret = msg->base.stream_info.pfnStreamOutput(
250                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
251                      FALSE);
252                     if (ret)
253                         ret = msg->base.stream_info.pfnStreamOutput(
254                          msg->base.stream_info.pvArg, indefinite_trailer,
255                          sizeof(indefinite_trailer), TRUE);
256                 }
257                 else
258                     ret = msg->base.stream_info.pfnStreamOutput(
259                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData, TRUE);
260             }
261         }
262         __EXCEPT_PAGE_FAULT
263         {
264             SetLastError(STATUS_ACCESS_VIOLATION);
265             ret = FALSE;
266         }
267         __ENDTRY;
268     }
269     else
270     {
271         if (!fFinal)
272         {
273             if (msg->base.open_flags & CMSG_DETACHED_FLAG)
274                 SetLastError(E_INVALIDARG);
275             else
276                 SetLastError(CRYPT_E_MSG_ERROR);
277         }
278         else
279         {
280             msg->base.state = MsgStateFinalized;
281             if (!cbData)
282                 SetLastError(E_INVALIDARG);
283             else
284             {
285                 CRYPT_DATA_BLOB blob = { cbData, (LPBYTE)pbData };
286
287                 /* non-streamed data messages don't allow non-final updates,
288                  * don't bother checking whether data already exist, they can't.
289                  */
290                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
291                  &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &msg->bare_content,
292                  &msg->bare_content_len);
293             }
294         }
295     }
296     return ret;
297 }
298
299 static BOOL CRYPT_CopyParam(void *pvData, DWORD *pcbData, const void *src,
300  DWORD len)
301 {
302     BOOL ret = TRUE;
303
304     if (!pvData)
305         *pcbData = len;
306     else if (*pcbData < len)
307     {
308         *pcbData = len;
309         SetLastError(ERROR_MORE_DATA);
310         ret = FALSE;
311     }
312     else
313     {
314         *pcbData = len;
315         memcpy(pvData, src, len);
316     }
317     return ret;
318 }
319
320 static BOOL CDataEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
321  DWORD dwIndex, void *pvData, DWORD *pcbData)
322 {
323     CDataEncodeMsg *msg = hCryptMsg;
324     BOOL ret = FALSE;
325
326     switch (dwParamType)
327     {
328     case CMSG_CONTENT_PARAM:
329         if (msg->base.streamed)
330             SetLastError(E_INVALIDARG);
331         else
332         {
333             CRYPT_CONTENT_INFO info;
334             char rsa_data[] = "1.2.840.113549.1.7.1";
335
336             info.pszObjId = rsa_data;
337             info.Content.cbData = msg->bare_content_len;
338             info.Content.pbData = msg->bare_content;
339             ret = CryptEncodeObject(X509_ASN_ENCODING, PKCS_CONTENT_INFO, &info,
340              pvData, pcbData);
341         }
342         break;
343     case CMSG_BARE_CONTENT_PARAM:
344         if (msg->base.streamed)
345             SetLastError(E_INVALIDARG);
346         else
347             ret = CRYPT_CopyParam(pvData, pcbData, msg->bare_content,
348              msg->bare_content_len);
349         break;
350     default:
351         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
352     }
353     return ret;
354 }
355
356 static HCRYPTMSG CDataEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
357  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
358 {
359     CDataEncodeMsg *msg;
360
361     if (pvMsgEncodeInfo)
362     {
363         SetLastError(E_INVALIDARG);
364         return NULL;
365     }
366     msg = CryptMemAlloc(sizeof(CDataEncodeMsg));
367     if (msg)
368     {
369         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
370          CDataEncodeMsg_Close, CDataEncodeMsg_GetParam, CDataEncodeMsg_Update,
371          CRYPT_DefaultMsgControl);
372         msg->bare_content_len = sizeof(empty_data_content);
373         msg->bare_content = (LPBYTE)empty_data_content;
374     }
375     return msg;
376 }
377
378 typedef struct _CHashEncodeMsg
379 {
380     CryptMsgBase    base;
381     HCRYPTPROV      prov;
382     HCRYPTHASH      hash;
383     CRYPT_DATA_BLOB data;
384 } CHashEncodeMsg;
385
386 static void CHashEncodeMsg_Close(HCRYPTMSG hCryptMsg)
387 {
388     CHashEncodeMsg *msg = hCryptMsg;
389
390     CryptMemFree(msg->data.pbData);
391     CryptDestroyHash(msg->hash);
392     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
393         CryptReleaseContext(msg->prov, 0);
394 }
395
396 static BOOL CRYPT_EncodePKCSDigestedData(CHashEncodeMsg *msg, void *pvData,
397  DWORD *pcbData)
398 {
399     BOOL ret;
400     ALG_ID algID;
401     DWORD size = sizeof(algID);
402
403     ret = CryptGetHashParam(msg->hash, HP_ALGID, (BYTE *)&algID, &size, 0);
404     if (ret)
405     {
406         CRYPT_DIGESTED_DATA digestedData = { 0 };
407         char oid_rsa_data[] = szOID_RSA_data;
408
409         digestedData.version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
410         digestedData.DigestAlgorithm.pszObjId = (LPSTR)CertAlgIdToOID(algID);
411         /* FIXME: what about digestedData.DigestAlgorithm.Parameters? */
412         /* Quirk:  OID is only encoded messages if an update has happened */
413         if (msg->base.state != MsgStateInit)
414             digestedData.ContentInfo.pszObjId = oid_rsa_data;
415         if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->data.cbData)
416         {
417             ret = CRYPT_AsnEncodeOctets(0, NULL, &msg->data,
418              CRYPT_ENCODE_ALLOC_FLAG, NULL,
419              (LPBYTE)&digestedData.ContentInfo.Content.pbData,
420              &digestedData.ContentInfo.Content.cbData);
421         }
422         if (msg->base.state == MsgStateFinalized)
423         {
424             size = sizeof(DWORD);
425             ret = CryptGetHashParam(msg->hash, HP_HASHSIZE,
426              (LPBYTE)&digestedData.hash.cbData, &size, 0);
427             if (ret)
428             {
429                 digestedData.hash.pbData = CryptMemAlloc(
430                  digestedData.hash.cbData);
431                 ret = CryptGetHashParam(msg->hash, HP_HASHVAL,
432                  digestedData.hash.pbData, &digestedData.hash.cbData, 0);
433             }
434         }
435         if (ret)
436             ret = CRYPT_AsnEncodePKCSDigestedData(&digestedData, pvData,
437              pcbData);
438         CryptMemFree(digestedData.hash.pbData);
439         LocalFree(digestedData.ContentInfo.Content.pbData);
440     }
441     return ret;
442 }
443
444 static BOOL CHashEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
445  DWORD dwIndex, void *pvData, DWORD *pcbData)
446 {
447     CHashEncodeMsg *msg = hCryptMsg;
448     BOOL ret = FALSE;
449
450     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
451      pvData, pcbData);
452
453     switch (dwParamType)
454     {
455     case CMSG_BARE_CONTENT_PARAM:
456         if (msg->base.streamed)
457             SetLastError(E_INVALIDARG);
458         else
459             ret = CRYPT_EncodePKCSDigestedData(msg, pvData, pcbData);
460         break;
461     case CMSG_CONTENT_PARAM:
462     {
463         CRYPT_CONTENT_INFO info;
464
465         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
466          &info.Content.cbData);
467         if (ret)
468         {
469             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
470             if (info.Content.pbData)
471             {
472                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
473                  info.Content.pbData, &info.Content.cbData);
474                 if (ret)
475                 {
476                     char oid_rsa_hashed[] = szOID_RSA_hashedData;
477
478                     info.pszObjId = oid_rsa_hashed;
479                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
480                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
481                 }
482                 CryptMemFree(info.Content.pbData);
483             }
484             else
485                 ret = FALSE;
486         }
487         break;
488     }
489     case CMSG_COMPUTED_HASH_PARAM:
490         ret = CryptGetHashParam(msg->hash, HP_HASHVAL, pvData, pcbData, 0);
491         break;
492     case CMSG_VERSION_PARAM:
493         if (msg->base.state != MsgStateFinalized)
494             SetLastError(CRYPT_E_MSG_ERROR);
495         else
496         {
497             DWORD version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
498
499             /* Since the data are always encoded as octets, the version is
500              * always 0 (see rfc3852, section 7)
501              */
502             ret = CRYPT_CopyParam(pvData, pcbData, &version, sizeof(version));
503         }
504         break;
505     default:
506         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
507     }
508     return ret;
509 }
510
511 static BOOL CHashEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
512  DWORD cbData, BOOL fFinal)
513 {
514     CHashEncodeMsg *msg = hCryptMsg;
515     BOOL ret = FALSE;
516
517     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
518
519     if (msg->base.state == MsgStateFinalized)
520         SetLastError(CRYPT_E_MSG_ERROR);
521     else if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
522     {
523         /* Doesn't do much, as stream output is never called, and you
524          * can't get the content.
525          */
526         ret = CryptHashData(msg->hash, pbData, cbData, 0);
527         msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
528     }
529     else
530     {
531         if (!fFinal)
532             SetLastError(CRYPT_E_MSG_ERROR);
533         else
534         {
535             ret = CryptHashData(msg->hash, pbData, cbData, 0);
536             if (ret)
537             {
538                 msg->data.pbData = CryptMemAlloc(cbData);
539                 if (msg->data.pbData)
540                 {
541                     memcpy(msg->data.pbData + msg->data.cbData, pbData, cbData);
542                     msg->data.cbData += cbData;
543                 }
544                 else
545                     ret = FALSE;
546             }
547             msg->base.state = MsgStateFinalized;
548         }
549     }
550     return ret;
551 }
552
553 static HCRYPTMSG CHashEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
554  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
555 {
556     CHashEncodeMsg *msg;
557     const CMSG_HASHED_ENCODE_INFO *info = pvMsgEncodeInfo;
558     HCRYPTPROV prov;
559     ALG_ID algID;
560
561     if (info->cbSize != sizeof(CMSG_HASHED_ENCODE_INFO))
562     {
563         SetLastError(E_INVALIDARG);
564         return NULL;
565     }
566     if (!(algID = CertOIDToAlgId(info->HashAlgorithm.pszObjId)))
567     {
568         SetLastError(CRYPT_E_UNKNOWN_ALGO);
569         return NULL;
570     }
571     if (info->hCryptProv)
572         prov = info->hCryptProv;
573     else
574     {
575         prov = CRYPT_GetDefaultProvider();
576         dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
577     }
578     msg = CryptMemAlloc(sizeof(CHashEncodeMsg));
579     if (msg)
580     {
581         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
582          CHashEncodeMsg_Close, CHashEncodeMsg_GetParam, CHashEncodeMsg_Update,
583          CRYPT_DefaultMsgControl);
584         msg->prov = prov;
585         msg->data.cbData = 0;
586         msg->data.pbData = NULL;
587         if (!CryptCreateHash(prov, algID, 0, 0, &msg->hash))
588         {
589             CryptMsgClose(msg);
590             msg = NULL;
591         }
592     }
593     return msg;
594 }
595
596 typedef struct _CMSG_SIGNER_ENCODE_INFO_WITH_CMS
597 {
598     DWORD                      cbSize;
599     PCERT_INFO                 pCertInfo;
600     HCRYPTPROV                 hCryptProv;
601     DWORD                      dwKeySpec;
602     CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
603     void                      *pvHashAuxInfo;
604     DWORD                      cAuthAttr;
605     PCRYPT_ATTRIBUTE           rgAuthAttr;
606     DWORD                      cUnauthAttr;
607     PCRYPT_ATTRIBUTE           rgUnauthAttr;
608     CERT_ID                    SignerId;
609     CRYPT_ALGORITHM_IDENTIFIER HashEncryptionAlgorithm;
610     void                      *pvHashEncryptionAuxInfo;
611 } CMSG_SIGNER_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNER_ENCODE_INFO_WITH_CMS;
612
613 typedef struct _CMSG_SIGNED_ENCODE_INFO_WITH_CMS
614 {
615     DWORD                             cbSize;
616     DWORD                             cSigners;
617     PCMSG_SIGNER_ENCODE_INFO_WITH_CMS rgSigners;
618     DWORD                             cCertEncoded;
619     PCERT_BLOB                        rgCertEncoded;
620     DWORD                             cCrlEncoded;
621     PCRL_BLOB                         rgCrlEncoded;
622     DWORD                             cAttrCertEncoded;
623     PCERT_BLOB                        rgAttrCertEncoded;
624 } CMSG_SIGNED_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNED_ENCODE_INFO_WITH_CMS;
625
626 static BOOL CRYPT_IsValidSigner(const CMSG_SIGNER_ENCODE_INFO_WITH_CMS *signer)
627 {
628     if (signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO) &&
629      signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
630     {
631         SetLastError(E_INVALIDARG);
632         return FALSE;
633     }
634     if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO))
635     {
636         if (!signer->pCertInfo->SerialNumber.cbData)
637         {
638             SetLastError(E_INVALIDARG);
639             return FALSE;
640         }
641         if (!signer->pCertInfo->Issuer.cbData)
642         {
643             SetLastError(E_INVALIDARG);
644             return FALSE;
645         }
646     }
647     else if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
648     {
649         switch (signer->SignerId.dwIdChoice)
650         {
651         case 0:
652             if (!signer->pCertInfo->SerialNumber.cbData)
653             {
654                 SetLastError(E_INVALIDARG);
655                 return FALSE;
656             }
657             if (!signer->pCertInfo->Issuer.cbData)
658             {
659                 SetLastError(E_INVALIDARG);
660                 return FALSE;
661             }
662             break;
663         case CERT_ID_ISSUER_SERIAL_NUMBER:
664             if (!signer->SignerId.u.IssuerSerialNumber.SerialNumber.cbData)
665             {
666                 SetLastError(E_INVALIDARG);
667                 return FALSE;
668             }
669             if (!signer->SignerId.u.IssuerSerialNumber.Issuer.cbData)
670             {
671                 SetLastError(E_INVALIDARG);
672                 return FALSE;
673             }
674             break;
675         case CERT_ID_KEY_IDENTIFIER:
676             if (!signer->SignerId.u.KeyId.cbData)
677             {
678                 SetLastError(E_INVALIDARG);
679                 return FALSE;
680             }
681             break;
682         default:
683             SetLastError(E_INVALIDARG);
684         }
685         if (signer->HashEncryptionAlgorithm.pszObjId)
686         {
687             FIXME("CMSG_SIGNER_ENCODE_INFO with CMS fields unsupported\n");
688             return FALSE;
689         }
690     }
691     if (!signer->hCryptProv)
692     {
693         SetLastError(E_INVALIDARG);
694         return FALSE;
695     }
696     if (!CertOIDToAlgId(signer->HashAlgorithm.pszObjId))
697     {
698         SetLastError(CRYPT_E_UNKNOWN_ALGO);
699         return FALSE;
700     }
701     return TRUE;
702 }
703
704 static BOOL CRYPT_ConstructBlob(CRYPT_DATA_BLOB *out, const CRYPT_DATA_BLOB *in)
705 {
706     BOOL ret = TRUE;
707
708     out->cbData = in->cbData;
709     if (out->cbData)
710     {
711         out->pbData = CryptMemAlloc(out->cbData);
712         if (out->pbData)
713             memcpy(out->pbData, in->pbData, out->cbData);
714         else
715             ret = FALSE;
716     }
717     else
718         out->pbData = NULL;
719     return ret;
720 }
721
722 static BOOL CRYPT_ConstructBlobArray(DWORD *outCBlobs,
723  PCRYPT_DATA_BLOB *outPBlobs, DWORD cBlobs, const CRYPT_DATA_BLOB *pBlobs)
724 {
725     BOOL ret = TRUE;
726
727     *outCBlobs = cBlobs;
728     if (cBlobs)
729     {
730         *outPBlobs = CryptMemAlloc(cBlobs * sizeof(CRYPT_DATA_BLOB));
731         if (*outPBlobs)
732         {
733             DWORD i;
734
735             memset(*outPBlobs, 0, cBlobs * sizeof(CRYPT_DATA_BLOB));
736             for (i = 0; ret && i < cBlobs; i++)
737                 ret = CRYPT_ConstructBlob(&(*outPBlobs)[i], &pBlobs[i]);
738         }
739         else
740             ret = FALSE;
741     }
742     return ret;
743 }
744
745 static void CRYPT_FreeBlobArray(DWORD cBlobs, PCRYPT_DATA_BLOB blobs)
746 {
747     DWORD i;
748
749     for (i = 0; i < cBlobs; i++)
750         CryptMemFree(blobs[i].pbData);
751     CryptMemFree(blobs);
752 }
753
754 static BOOL CRYPT_ConstructAttribute(CRYPT_ATTRIBUTE *out,
755  const CRYPT_ATTRIBUTE *in)
756 {
757     BOOL ret;
758
759     out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
760     if (out->pszObjId)
761     {
762         strcpy(out->pszObjId, in->pszObjId);
763         ret = CRYPT_ConstructBlobArray(&out->cValue, &out->rgValue,
764          in->cValue, in->rgValue);
765     }
766     else
767         ret = FALSE;
768     return ret;
769 }
770
771 static BOOL CRYPT_ConstructAttributes(CRYPT_ATTRIBUTES *out,
772  const CRYPT_ATTRIBUTES *in)
773 {
774     BOOL ret = TRUE;
775
776     out->cAttr = in->cAttr;
777     if (out->cAttr)
778     {
779         out->rgAttr = CryptMemAlloc(out->cAttr * sizeof(CRYPT_ATTRIBUTE));
780         if (out->rgAttr)
781         {
782             DWORD i;
783
784             memset(out->rgAttr, 0, out->cAttr * sizeof(CRYPT_ATTRIBUTE));
785             for (i = 0; ret && i < out->cAttr; i++)
786                 ret = CRYPT_ConstructAttribute(&out->rgAttr[i], &in->rgAttr[i]);
787         }
788         else
789             ret = FALSE;
790     }
791     else
792         out->rgAttr = NULL;
793     return ret;
794 }
795
796 /* Constructs a CMSG_CMS_SIGNER_INFO from a CMSG_SIGNER_ENCODE_INFO_WITH_CMS. */
797 static BOOL CSignerInfo_Construct(CMSG_CMS_SIGNER_INFO *info,
798  const CMSG_SIGNER_ENCODE_INFO_WITH_CMS *in)
799 {
800     BOOL ret;
801
802     if (in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO))
803     {
804         info->dwVersion = CMSG_SIGNER_INFO_V1;
805         ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
806          &in->pCertInfo->Issuer);
807         if (ret)
808             ret = CRYPT_ConstructBlob(
809              &info->SignerId.u.IssuerSerialNumber.SerialNumber,
810              &in->pCertInfo->SerialNumber);
811         info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
812         info->HashEncryptionAlgorithm.pszObjId =
813          in->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId;
814         if (ret)
815             ret = CRYPT_ConstructBlob(&info->HashEncryptionAlgorithm.Parameters,
816              &in->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters);
817     }
818     else
819     {
820         const CRYPT_ALGORITHM_IDENTIFIER *pEncrAlg;
821
822         /* Implicitly in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS).
823          * See CRYPT_IsValidSigner.
824          */
825         if (!in->SignerId.dwIdChoice)
826         {
827             info->dwVersion = CMSG_SIGNER_INFO_V1;
828             ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
829              &in->pCertInfo->Issuer);
830             if (ret)
831                 ret = CRYPT_ConstructBlob(
832                  &info->SignerId.u.IssuerSerialNumber.SerialNumber,
833                  &in->pCertInfo->SerialNumber);
834             info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
835         }
836         else if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
837         {
838             info->dwVersion = CMSG_SIGNER_INFO_V1;
839             info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
840             ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
841              &in->SignerId.u.IssuerSerialNumber.Issuer);
842             if (ret)
843                 ret = CRYPT_ConstructBlob(
844                  &info->SignerId.u.IssuerSerialNumber.SerialNumber,
845                  &in->SignerId.u.IssuerSerialNumber.SerialNumber);
846         }
847         else
848         {
849             /* Implicitly dwIdChoice == CERT_ID_KEY_IDENTIFIER */
850             info->dwVersion = CMSG_SIGNER_INFO_V3;
851             info->SignerId.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
852             ret = CRYPT_ConstructBlob(&info->SignerId.u.KeyId,
853              &in->SignerId.u.KeyId);
854         }
855         pEncrAlg = in->HashEncryptionAlgorithm.pszObjId ?
856          &in->HashEncryptionAlgorithm :
857          &in->pCertInfo->SubjectPublicKeyInfo.Algorithm;
858         info->HashEncryptionAlgorithm.pszObjId = pEncrAlg->pszObjId;
859         if (ret)
860             ret = CRYPT_ConstructBlob(&info->HashEncryptionAlgorithm.Parameters,
861              &pEncrAlg->Parameters);
862     }
863     /* Assumption:  algorithm IDs will point to static strings, not
864      * stack-based ones, so copying the pointer values is safe.
865      */
866     info->HashAlgorithm.pszObjId = in->HashAlgorithm.pszObjId;
867     if (ret)
868         ret = CRYPT_ConstructBlob(&info->HashAlgorithm.Parameters,
869          &in->HashAlgorithm.Parameters);
870     if (ret)
871         ret = CRYPT_ConstructAttributes(&info->AuthAttrs,
872          (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
873     if (ret)
874         ret = CRYPT_ConstructAttributes(&info->UnauthAttrs,
875          (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
876     return ret;
877 }
878
879 static void CSignerInfo_Free(CMSG_CMS_SIGNER_INFO *info)
880 {
881     DWORD i, j;
882
883     if (info->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
884     {
885         CryptMemFree(info->SignerId.u.IssuerSerialNumber.Issuer.pbData);
886         CryptMemFree(info->SignerId.u.IssuerSerialNumber.SerialNumber.pbData);
887     }
888     else
889         CryptMemFree(info->SignerId.u.KeyId.pbData);
890     CryptMemFree(info->HashAlgorithm.Parameters.pbData);
891     CryptMemFree(info->HashEncryptionAlgorithm.Parameters.pbData);
892     CryptMemFree(info->EncryptedHash.pbData);
893     for (i = 0; i < info->AuthAttrs.cAttr; i++)
894     {
895         for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
896             CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
897         CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
898         CryptMemFree(info->AuthAttrs.rgAttr[i].pszObjId);
899     }
900     CryptMemFree(info->AuthAttrs.rgAttr);
901     for (i = 0; i < info->UnauthAttrs.cAttr; i++)
902     {
903         for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
904             CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
905         CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
906         CryptMemFree(info->UnauthAttrs.rgAttr[i].pszObjId);
907     }
908     CryptMemFree(info->UnauthAttrs.rgAttr);
909 }
910
911 typedef struct _CSignerHandles
912 {
913     HCRYPTHASH contentHash;
914     HCRYPTHASH authAttrHash;
915 } CSignerHandles;
916
917 typedef struct _CSignedMsgData
918 {
919     CRYPT_SIGNED_INFO *info;
920     DWORD              cSignerHandle;
921     CSignerHandles    *signerHandles;
922 } CSignedMsgData;
923
924 /* Constructs the signer handles for the signerIndex'th signer of msg_data.
925  * Assumes signerIndex is a valid idnex, and that msg_data's info has already
926  * been constructed.
927  */
928 static BOOL CSignedMsgData_ConstructSignerHandles(CSignedMsgData *msg_data,
929  DWORD signerIndex, HCRYPTPROV crypt_prov)
930 {
931     ALG_ID algID;
932     BOOL ret;
933
934     algID = CertOIDToAlgId(
935      msg_data->info->rgSignerInfo[signerIndex].HashAlgorithm.pszObjId);
936     ret = CryptCreateHash(crypt_prov, algID, 0, 0,
937      &msg_data->signerHandles->contentHash);
938     if (ret && msg_data->info->rgSignerInfo[signerIndex].AuthAttrs.cAttr > 0)
939         ret = CryptCreateHash(crypt_prov, algID, 0, 0,
940          &msg_data->signerHandles->authAttrHash);
941     return ret;
942 }
943
944 /* Allocates a CSignedMsgData's handles.  Assumes its info has already been
945  * constructed.
946  */
947 static BOOL CSignedMsgData_AllocateHandles(CSignedMsgData *msg_data)
948 {
949     BOOL ret = TRUE;
950
951     if (msg_data->info->cSignerInfo)
952     {
953         msg_data->signerHandles =
954          CryptMemAlloc(msg_data->info->cSignerInfo * sizeof(CSignerHandles));
955         if (msg_data->signerHandles)
956         {
957             msg_data->cSignerHandle = msg_data->info->cSignerInfo;
958             memset(msg_data->signerHandles, 0,
959              msg_data->info->cSignerInfo * sizeof(CSignerHandles));
960         }
961         else
962         {
963             msg_data->cSignerHandle = 0;
964             ret = FALSE;
965         }
966     }
967     else
968     {
969         msg_data->cSignerHandle = 0;
970         msg_data->signerHandles = NULL;
971     }
972     return ret;
973 }
974
975 static void CSignedMsgData_CloseHandles(CSignedMsgData *msg_data)
976 {
977     DWORD i;
978
979     for (i = 0; i < msg_data->cSignerHandle; i++)
980     {
981         if (msg_data->signerHandles[i].contentHash)
982             CryptDestroyHash(msg_data->signerHandles[i].contentHash);
983         if (msg_data->signerHandles[i].authAttrHash)
984             CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
985     }
986     CryptMemFree(msg_data->signerHandles);
987     msg_data->signerHandles = NULL;
988     msg_data->cSignerHandle = 0;
989 }
990
991 static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
992  const BYTE *pbData, DWORD cbData)
993 {
994     DWORD i;
995     BOOL ret = TRUE;
996
997     for (i = 0; ret && i < msg_data->cSignerHandle; i++)
998         ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
999          cbData, 0);
1000     return ret;
1001 }
1002
1003 static BOOL CRYPT_AppendAttribute(CRYPT_ATTRIBUTES *out,
1004  const CRYPT_ATTRIBUTE *in)
1005 {
1006     BOOL ret = FALSE;
1007
1008     out->rgAttr = CryptMemRealloc(out->rgAttr,
1009      (out->cAttr + 1) * sizeof(CRYPT_ATTRIBUTE));
1010     if (out->rgAttr)
1011     {
1012         ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
1013         if (ret)
1014             out->cAttr++;
1015     }
1016     return ret;
1017 }
1018
1019 static BOOL CSignedMsgData_AppendMessageDigestAttribute(
1020  CSignedMsgData *msg_data, DWORD signerIndex)
1021 {
1022     BOOL ret;
1023     DWORD size;
1024     CRYPT_HASH_BLOB hash = { 0, NULL }, encodedHash = { 0, NULL };
1025     char messageDigest[] = szOID_RSA_messageDigest;
1026     CRYPT_ATTRIBUTE messageDigestAttr = { messageDigest, 1, &encodedHash };
1027
1028     size = sizeof(DWORD);
1029     ret = CryptGetHashParam(
1030      msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
1031      (LPBYTE)&hash.cbData, &size, 0);
1032     if (ret)
1033     {
1034         hash.pbData = CryptMemAlloc(hash.cbData);
1035         ret = CryptGetHashParam(
1036          msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
1037          hash.pbData, &hash.cbData, 0);
1038         if (ret)
1039         {
1040             ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
1041              NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
1042             if (ret)
1043             {
1044                 ret = CRYPT_AppendAttribute(
1045                  &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
1046                  &messageDigestAttr);
1047                 LocalFree(encodedHash.pbData);
1048             }
1049         }
1050         CryptMemFree(hash.pbData);
1051     }
1052     return ret;
1053 }
1054
1055 typedef enum {
1056     Sign,
1057     Verify
1058 } SignOrVerify;
1059
1060 static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
1061  CSignedMsgData *msg_data, SignOrVerify flag)
1062 {
1063     DWORD i;
1064     BOOL ret = TRUE;
1065
1066     TRACE("(%p)\n", msg_data);
1067
1068     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1069     {
1070         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1071         {
1072             if (flag == Sign)
1073             {
1074                 BYTE oid_rsa_data_encoded[] = { 0x06,0x09,0x2a,0x86,0x48,0x86,
1075                  0xf7,0x0d,0x01,0x07,0x01 };
1076                 CRYPT_DATA_BLOB content = { sizeof(oid_rsa_data_encoded),
1077                  oid_rsa_data_encoded };
1078                 char contentType[] = szOID_RSA_contentType;
1079                 CRYPT_ATTRIBUTE contentTypeAttr = { contentType, 1, &content };
1080
1081                 /* FIXME: does this depend on inner OID? */
1082                 ret = CRYPT_AppendAttribute(
1083                  &msg_data->info->rgSignerInfo[i].AuthAttrs, &contentTypeAttr);
1084                 if (ret)
1085                     ret = CSignedMsgData_AppendMessageDigestAttribute(msg_data,
1086                      i);
1087             }
1088             if (ret)
1089             {
1090                 LPBYTE encodedAttrs;
1091                 DWORD size;
1092
1093                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
1094                  &msg_data->info->rgSignerInfo[i].AuthAttrs,
1095                  CRYPT_ENCODE_ALLOC_FLAG, NULL, &encodedAttrs, &size);
1096                 if (ret)
1097                 {
1098                     ret = CryptHashData(
1099                      msg_data->signerHandles[i].authAttrHash, encodedAttrs,
1100                      size, 0);
1101                     LocalFree(encodedAttrs);
1102                 }
1103             }
1104         }
1105     }
1106     TRACE("returning %d\n", ret);
1107     return ret;
1108 }
1109
1110 static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
1111 {
1112     DWORD i;
1113     BYTE tmp;
1114
1115     for (i = 0; i < hash->cbData / 2; i++)
1116     {
1117         tmp = hash->pbData[hash->cbData - i - 1];
1118         hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
1119         hash->pbData[i] = tmp;
1120     }
1121 }
1122
1123 static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
1124 {
1125     DWORD i;
1126     BOOL ret = TRUE;
1127
1128     TRACE("(%p)\n", msg_data);
1129
1130     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1131     {
1132         HCRYPTHASH hash;
1133
1134         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1135             hash = msg_data->signerHandles[i].authAttrHash;
1136         else
1137             hash = msg_data->signerHandles[i].contentHash;
1138         ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
1139          &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1140         if (ret)
1141         {
1142             msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
1143              CryptMemAlloc(
1144              msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1145             if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
1146             {
1147                 ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
1148                  msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
1149                  &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1150                 if (ret)
1151                     CRYPT_ReverseBytes(
1152                      &msg_data->info->rgSignerInfo[i].EncryptedHash);
1153             }
1154             else
1155                 ret = FALSE;
1156         }
1157     }
1158     return ret;
1159 }
1160
1161 static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1162  const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1163 {
1164     BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);
1165
1166     if (ret && fFinal)
1167     {
1168         ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
1169         if (ret && flag == Sign)
1170             ret = CSignedMsgData_Sign(msg_data);
1171     }
1172     return ret;
1173 }
1174
1175 typedef struct _CSignedEncodeMsg
1176 {
1177     CryptMsgBase    base;
1178     LPSTR           innerOID;
1179     CRYPT_DATA_BLOB data;
1180     CSignedMsgData  msg_data;
1181 } CSignedEncodeMsg;
1182
1183 static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
1184 {
1185     CSignedEncodeMsg *msg = hCryptMsg;
1186     DWORD i;
1187
1188     CryptMemFree(msg->innerOID);
1189     CryptMemFree(msg->data.pbData);
1190     CRYPT_FreeBlobArray(msg->msg_data.info->cCertEncoded,
1191      msg->msg_data.info->rgCertEncoded);
1192     CRYPT_FreeBlobArray(msg->msg_data.info->cCrlEncoded,
1193      msg->msg_data.info->rgCrlEncoded);
1194     for (i = 0; i < msg->msg_data.info->cSignerInfo; i++)
1195         CSignerInfo_Free(&msg->msg_data.info->rgSignerInfo[i]);
1196     CSignedMsgData_CloseHandles(&msg->msg_data);
1197     CryptMemFree(msg->msg_data.info->rgSignerInfo);
1198     CryptMemFree(msg->msg_data.info);
1199 }
1200
1201 static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1202  DWORD dwIndex, void *pvData, DWORD *pcbData)
1203 {
1204     CSignedEncodeMsg *msg = hCryptMsg;
1205     BOOL ret = FALSE;
1206
1207     switch (dwParamType)
1208     {
1209     case CMSG_CONTENT_PARAM:
1210     {
1211         CRYPT_CONTENT_INFO info;
1212
1213         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
1214          &info.Content.cbData);
1215         if (ret)
1216         {
1217             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
1218             if (info.Content.pbData)
1219             {
1220                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
1221                  info.Content.pbData, &info.Content.cbData);
1222                 if (ret)
1223                 {
1224                     char oid_rsa_signed[] = szOID_RSA_signedData;
1225
1226                     info.pszObjId = oid_rsa_signed;
1227                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
1228                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
1229                 }
1230                 CryptMemFree(info.Content.pbData);
1231             }
1232             else
1233                 ret = FALSE;
1234         }
1235         break;
1236     }
1237     case CMSG_BARE_CONTENT_PARAM:
1238     {
1239         CRYPT_SIGNED_INFO info;
1240         BOOL freeContent = FALSE;
1241
1242         info = *msg->msg_data.info;
1243         if (!msg->innerOID || !strcmp(msg->innerOID, szOID_RSA_data))
1244         {
1245             char oid_rsa_data[] = szOID_RSA_data;
1246
1247             /* Quirk:  OID is only encoded messages if an update has happened */
1248             if (msg->base.state != MsgStateInit)
1249                 info.content.pszObjId = oid_rsa_data;
1250             else
1251                 info.content.pszObjId = NULL;
1252             if (msg->data.cbData)
1253             {
1254                 CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
1255
1256                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1257                  &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1258                  &info.content.Content.pbData, &info.content.Content.cbData);
1259                 freeContent = TRUE;
1260             }
1261             else
1262             {
1263                 info.content.Content.cbData = 0;
1264                 info.content.Content.pbData = NULL;
1265                 ret = TRUE;
1266             }
1267         }
1268         else
1269         {
1270             info.content.pszObjId = msg->innerOID;
1271             info.content.Content.cbData = msg->data.cbData;
1272             info.content.Content.pbData = msg->data.pbData;
1273             ret = TRUE;
1274         }
1275         if (ret)
1276         {
1277             ret = CRYPT_AsnEncodeCMSSignedInfo(&info, pvData, pcbData);
1278             if (freeContent)
1279                 LocalFree(info.content.Content.pbData);
1280         }
1281         break;
1282     }
1283     case CMSG_COMPUTED_HASH_PARAM:
1284         if (dwIndex >= msg->msg_data.cSignerHandle)
1285             SetLastError(CRYPT_E_INVALID_INDEX);
1286         else
1287             ret = CryptGetHashParam(
1288              msg->msg_data.signerHandles[dwIndex].contentHash, HP_HASHVAL,
1289              pvData, pcbData, 0);
1290         break;
1291     case CMSG_ENCODED_SIGNER:
1292         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1293             SetLastError(CRYPT_E_INVALID_INDEX);
1294         else
1295             ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1296              CMS_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1297              NULL, pvData, pcbData);
1298         break;
1299     case CMSG_VERSION_PARAM:
1300         ret = CRYPT_CopyParam(pvData, pcbData, &msg->msg_data.info->version,
1301          sizeof(msg->msg_data.info->version));
1302         break;
1303     default:
1304         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1305     }
1306     return ret;
1307 }
1308
1309 static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1310  DWORD cbData, BOOL fFinal)
1311 {
1312     CSignedEncodeMsg *msg = hCryptMsg;
1313     BOOL ret = FALSE;
1314
1315     if (msg->base.state == MsgStateFinalized)
1316         SetLastError(CRYPT_E_MSG_ERROR);
1317     else if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1318     {
1319         ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
1320          Sign);
1321         if (msg->base.streamed)
1322             FIXME("streamed partial stub\n");
1323         msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
1324     }
1325     else
1326     {
1327         if (!fFinal)
1328             SetLastError(CRYPT_E_MSG_ERROR);
1329         else
1330         {
1331             if (cbData)
1332             {
1333                 msg->data.pbData = CryptMemAlloc(cbData);
1334                 if (msg->data.pbData)
1335                 {
1336                     memcpy(msg->data.pbData, pbData, cbData);
1337                     msg->data.cbData = cbData;
1338                     ret = TRUE;
1339                 }
1340             }
1341             else
1342                 ret = TRUE;
1343             if (ret)
1344                 ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1345                  fFinal, Sign);
1346             msg->base.state = MsgStateFinalized;
1347         }
1348     }
1349     return ret;
1350 }
1351
1352 static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1353  const void *pvMsgEncodeInfo, LPCSTR pszInnerContentObjID,
1354  PCMSG_STREAM_INFO pStreamInfo)
1355 {
1356     const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info = pvMsgEncodeInfo;
1357     DWORD i;
1358     CSignedEncodeMsg *msg;
1359
1360     if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
1361      info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1362     {
1363         SetLastError(E_INVALIDARG);
1364         return NULL;
1365     }
1366     if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS) &&
1367      info->cAttrCertEncoded)
1368     {
1369         FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
1370         return NULL;
1371     }
1372     for (i = 0; i < info->cSigners; i++)
1373         if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
1374             return NULL;
1375     msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
1376     if (msg)
1377     {
1378         BOOL ret = TRUE;
1379
1380         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1381          CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1382          CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1383         if (pszInnerContentObjID)
1384         {
1385             msg->innerOID = CryptMemAlloc(strlen(pszInnerContentObjID) + 1);
1386             if (msg->innerOID)
1387                 strcpy(msg->innerOID, pszInnerContentObjID);
1388             else
1389                 ret = FALSE;
1390         }
1391         else
1392             msg->innerOID = NULL;
1393         msg->data.cbData = 0;
1394         msg->data.pbData = NULL;
1395         if (ret)
1396             msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
1397         else
1398             msg->msg_data.info = NULL;
1399         if (msg->msg_data.info)
1400         {
1401             memset(msg->msg_data.info, 0, sizeof(CRYPT_SIGNED_INFO));
1402             msg->msg_data.info->version = CMSG_SIGNED_DATA_V1;
1403         }
1404         else
1405             ret = FALSE;
1406         if (ret)
1407         {
1408             if (info->cSigners)
1409             {
1410                 msg->msg_data.info->rgSignerInfo =
1411                  CryptMemAlloc(info->cSigners * sizeof(CMSG_CMS_SIGNER_INFO));
1412                 if (msg->msg_data.info->rgSignerInfo)
1413                 {
1414                     msg->msg_data.info->cSignerInfo = info->cSigners;
1415                     memset(msg->msg_data.info->rgSignerInfo, 0,
1416                      msg->msg_data.info->cSignerInfo *
1417                      sizeof(CMSG_CMS_SIGNER_INFO));
1418                     ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
1419                     for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1420                     {
1421                         if (info->rgSigners[i].SignerId.dwIdChoice ==
1422                          CERT_ID_KEY_IDENTIFIER)
1423                             msg->msg_data.info->version = CMSG_SIGNED_DATA_V3;
1424                         ret = CSignerInfo_Construct(
1425                          &msg->msg_data.info->rgSignerInfo[i],
1426                          &info->rgSigners[i]);
1427                         if (ret)
1428                         {
1429                             ret = CSignedMsgData_ConstructSignerHandles(
1430                              &msg->msg_data, i, info->rgSigners[i].hCryptProv);
1431                             if (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1432                                 CryptReleaseContext(info->rgSigners[i].hCryptProv,
1433                                  0);
1434                         }
1435                     }
1436                 }
1437                 else
1438                     ret = FALSE;
1439             }
1440             else
1441             {
1442                 msg->msg_data.info->cSignerInfo = 0;
1443                 msg->msg_data.signerHandles = NULL;
1444                 msg->msg_data.cSignerHandle = 0;
1445             }
1446         }
1447         if (ret)
1448             ret = CRYPT_ConstructBlobArray(&msg->msg_data.info->cCertEncoded,
1449              &msg->msg_data.info->rgCertEncoded, info->cCertEncoded,
1450              info->rgCertEncoded);
1451         if (ret)
1452             ret = CRYPT_ConstructBlobArray(&msg->msg_data.info->cCrlEncoded,
1453              &msg->msg_data.info->rgCrlEncoded, info->cCrlEncoded,
1454              info->rgCrlEncoded);
1455         if (!ret)
1456         {
1457             CSignedEncodeMsg_Close(msg);
1458             msg = NULL;
1459         }
1460     }
1461     return msg;
1462 }
1463
1464 typedef struct _CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS
1465 {
1466     DWORD                       cbSize;
1467     HCRYPTPROV_LEGACY           hCryptProv;
1468     CRYPT_ALGORITHM_IDENTIFIER  ContentEncryptionAlgorithm;
1469     void                       *pvEncryptionAuxInfo;
1470     DWORD                       cRecipients;
1471     PCERT_INFO                 *rgpRecipientCert;
1472     PCMSG_RECIPIENT_ENCODE_INFO rgCmsRecipients;
1473     DWORD                       cCertEncoded;
1474     PCERT_BLOB                  rgCertEncoded;
1475     DWORD                       cCrlEncoded;
1476     PCRL_BLOB                   rgCrlEncoded;
1477     DWORD                       cAttrCertEncoded;
1478     PCERT_BLOB                  rgAttrCertEncoded;
1479     DWORD                       cUnprotectedAttr;
1480     PCRYPT_ATTRIBUTE            rgUnprotectedAttr;
1481 } CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS, *PCMSG_ENVELOPED_ENCODE_INFO_WITH_CMS;
1482
1483 typedef struct _CEnvelopedEncodeMsg
1484 {
1485     CryptMsgBase                   base;
1486     CRYPT_ALGORITHM_IDENTIFIER     algo;
1487     HCRYPTPROV                     prov;
1488     HCRYPTKEY                      key;
1489     DWORD                          cRecipientInfo;
1490     CMSG_KEY_TRANS_RECIPIENT_INFO *recipientInfo;
1491     CRYPT_DATA_BLOB                data;
1492 } CEnvelopedEncodeMsg;
1493
1494 static BOOL CRYPT_ConstructAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
1495  const CRYPT_ALGORITHM_IDENTIFIER *in)
1496 {
1497     out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
1498     if (out->pszObjId)
1499     {
1500         strcpy(out->pszObjId, in->pszObjId);
1501         return CRYPT_ConstructBlob(&out->Parameters, &in->Parameters);
1502     }
1503     else
1504         return FALSE;
1505 }
1506
1507 static BOOL CRYPT_ConstructBitBlob(CRYPT_BIT_BLOB *out, const CRYPT_BIT_BLOB *in)
1508 {
1509     out->cbData = in->cbData;
1510     out->cUnusedBits = in->cUnusedBits;
1511     if (out->cbData)
1512     {
1513         out->pbData = CryptMemAlloc(out->cbData);
1514         if (out->pbData)
1515             memcpy(out->pbData, in->pbData, out->cbData);
1516         else
1517             return FALSE;
1518     }
1519     else
1520         out->pbData = NULL;
1521     return TRUE;
1522 }
1523
1524 static BOOL CRYPT_GenKey(CMSG_CONTENT_ENCRYPT_INFO *info, ALG_ID algID)
1525 {
1526     static HCRYPTOIDFUNCSET set = NULL;
1527     PFN_CMSG_GEN_CONTENT_ENCRYPT_KEY genKeyFunc = NULL;
1528     HCRYPTOIDFUNCADDR hFunc;
1529     BOOL ret;
1530
1531     if (!set)
1532         set = CryptInitOIDFunctionSet(CMSG_OID_GEN_CONTENT_ENCRYPT_KEY_FUNC, 0);
1533     CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING,
1534      info->ContentEncryptionAlgorithm.pszObjId, 0, (void **)&genKeyFunc, &hFunc);
1535     if (genKeyFunc)
1536     {
1537         ret = genKeyFunc(info, 0, NULL);
1538         CryptFreeOIDFunctionAddress(hFunc, 0);
1539     }
1540     else
1541         ret = CryptGenKey(info->hCryptProv, algID, CRYPT_EXPORTABLE,
1542          &info->hContentEncryptKey);
1543     return ret;
1544 }
1545
1546 static BOOL WINAPI CRYPT_ExportKeyTrans(
1547  PCMSG_CONTENT_ENCRYPT_INFO pContentEncryptInfo,
1548  PCMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO pKeyTransEncodeInfo,
1549  PCMSG_KEY_TRANS_ENCRYPT_INFO pKeyTransEncryptInfo,
1550  DWORD dwFlags, void *pvReserved)
1551 {
1552     CERT_PUBLIC_KEY_INFO keyInfo;
1553     HCRYPTKEY expKey;
1554     BOOL ret;
1555
1556     ret = CRYPT_ConstructAlgorithmId(&keyInfo.Algorithm,
1557         &pKeyTransEncodeInfo->KeyEncryptionAlgorithm);
1558     if (ret)
1559         CRYPT_ConstructBitBlob(&keyInfo.PublicKey,
1560          &pKeyTransEncodeInfo->RecipientPublicKey);
1561
1562     if (ret)
1563         ret = CryptImportPublicKeyInfo(pKeyTransEncodeInfo->hCryptProv,
1564          X509_ASN_ENCODING, &keyInfo, &expKey);
1565     if (ret)
1566     {
1567         BYTE *keyBlob;
1568         DWORD size;
1569
1570         ret = CryptExportKey(pContentEncryptInfo->hContentEncryptKey, expKey,
1571          SIMPLEBLOB, 0, NULL, &size);
1572         keyBlob = CryptMemAlloc(size);
1573         if (keyBlob)
1574         {
1575             ret = CryptExportKey(pContentEncryptInfo->hContentEncryptKey,
1576              expKey, SIMPLEBLOB, 0, keyBlob, &size);
1577             if (ret)
1578             {
1579                 DWORD head = sizeof(BLOBHEADER) + sizeof(ALG_ID);
1580
1581                 pKeyTransEncryptInfo->EncryptedKey.pbData =
1582                  CryptMemAlloc(size - head);
1583                 if (pKeyTransEncryptInfo->EncryptedKey.pbData)
1584                 {
1585                     DWORD i, k = 0;
1586
1587                     pKeyTransEncryptInfo->EncryptedKey.cbData = size - head;
1588                     for (i = size - 1; i >= head; --i, ++k)
1589                         pKeyTransEncryptInfo->EncryptedKey.pbData[k] =
1590                          keyBlob[i];
1591                 }
1592                 else
1593                     ret = FALSE;
1594             }
1595             CryptMemFree(keyBlob);
1596         }
1597         else
1598             ret = FALSE;
1599         CryptDestroyKey(expKey);
1600     }
1601
1602     CryptMemFree(keyInfo.Algorithm.pszObjId);
1603     CryptMemFree(keyInfo.Algorithm.Parameters.pbData);
1604     return ret;
1605 }
1606
1607 static BOOL CRYPT_ExportEncryptedKey(CMSG_CONTENT_ENCRYPT_INFO *info, DWORD i,
1608  CRYPT_DATA_BLOB *key)
1609 {
1610     static HCRYPTOIDFUNCSET set = NULL;
1611     PFN_CMSG_EXPORT_KEY_TRANS exportKeyFunc = NULL;
1612     HCRYPTOIDFUNCADDR hFunc = NULL;
1613     CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO *encodeInfo =
1614      info->rgCmsRecipients[i].u.pKeyTrans;
1615     CMSG_KEY_TRANS_ENCRYPT_INFO encryptInfo;
1616     BOOL ret;
1617
1618     memset(&encryptInfo, 0, sizeof(encryptInfo));
1619     encryptInfo.cbSize = sizeof(encryptInfo);
1620     encryptInfo.dwRecipientIndex = i;
1621     ret = CRYPT_ConstructAlgorithmId(&encryptInfo.KeyEncryptionAlgorithm,
1622      &encodeInfo->KeyEncryptionAlgorithm);
1623
1624     if (!set)
1625         set = CryptInitOIDFunctionSet(CMSG_OID_EXPORT_KEY_TRANS_FUNC, 0);
1626     CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING,
1627      encryptInfo.KeyEncryptionAlgorithm.pszObjId, 0, (void **)&exportKeyFunc,
1628      &hFunc);
1629     if (!exportKeyFunc)
1630         exportKeyFunc = CRYPT_ExportKeyTrans;
1631     if (ret)
1632     {
1633         ret = exportKeyFunc(info, encodeInfo, &encryptInfo, 0, NULL);
1634         if (ret)
1635         {
1636             key->cbData = encryptInfo.EncryptedKey.cbData;
1637             key->pbData = encryptInfo.EncryptedKey.pbData;
1638         }
1639     }
1640     if (hFunc)
1641         CryptFreeOIDFunctionAddress(hFunc, 0);
1642
1643     CryptMemFree(encryptInfo.KeyEncryptionAlgorithm.pszObjId);
1644     CryptMemFree(encryptInfo.KeyEncryptionAlgorithm.Parameters.pbData);
1645     return ret;
1646 }
1647
1648 static BOOL CContentEncryptInfo_Construct(CMSG_CONTENT_ENCRYPT_INFO *info,
1649  const CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS *in, HCRYPTPROV prov)
1650 {
1651     BOOL ret;
1652
1653     info->cbSize = sizeof(CMSG_CONTENT_ENCRYPT_INFO);
1654     info->hCryptProv = prov;
1655     ret = CRYPT_ConstructAlgorithmId(&info->ContentEncryptionAlgorithm,
1656      &in->ContentEncryptionAlgorithm);
1657     info->pvEncryptionAuxInfo = in->pvEncryptionAuxInfo;
1658     info->cRecipients = in->cRecipients;
1659     if (ret)
1660     {
1661         info->rgCmsRecipients = CryptMemAlloc(in->cRecipients *
1662          sizeof(CMSG_RECIPIENT_ENCODE_INFO));
1663         if (info->rgCmsRecipients)
1664         {
1665             DWORD i;
1666
1667             for (i = 0; ret && i < in->cRecipients; ++i)
1668             {
1669                 CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO *encodeInfo;
1670                 CERT_INFO *cert = in->rgpRecipientCert[i];
1671
1672                 info->rgCmsRecipients[i].dwRecipientChoice =
1673                  CMSG_KEY_TRANS_RECIPIENT;
1674                 encodeInfo = CryptMemAlloc(sizeof(*encodeInfo));
1675                 info->rgCmsRecipients[i].u.pKeyTrans = encodeInfo;
1676                 if (encodeInfo)
1677                 {
1678                     encodeInfo->cbSize = sizeof(*encodeInfo);
1679                     ret = CRYPT_ConstructAlgorithmId(
1680                      &encodeInfo->KeyEncryptionAlgorithm,
1681                      &cert->SubjectPublicKeyInfo.Algorithm);
1682                     encodeInfo->pvKeyEncryptionAuxInfo = NULL;
1683                     encodeInfo->hCryptProv = prov;
1684                     if (ret)
1685                         ret = CRYPT_ConstructBitBlob(
1686                          &encodeInfo->RecipientPublicKey,
1687                          &cert->SubjectPublicKeyInfo.PublicKey);
1688                     if (ret)
1689                         ret = CRYPT_ConstructBlob(
1690                          &encodeInfo->RecipientId.u.IssuerSerialNumber.Issuer,
1691                          &cert->Issuer);
1692                     if (ret)
1693                         ret = CRYPT_ConstructBlob(
1694                          &encodeInfo->RecipientId.u.IssuerSerialNumber.SerialNumber,
1695                          &cert->SerialNumber);
1696                 }
1697                 else
1698                     ret = FALSE;
1699             }
1700         }
1701         else
1702             ret = FALSE;
1703     }
1704     info->pfnAlloc = CryptMemAlloc;
1705     info->pfnFree = CryptMemFree;
1706     return ret;
1707 }
1708
1709 static void CContentEncryptInfo_Free(CMSG_CONTENT_ENCRYPT_INFO *info)
1710 {
1711     CryptMemFree(info->ContentEncryptionAlgorithm.pszObjId);
1712     CryptMemFree(info->ContentEncryptionAlgorithm.Parameters.pbData);
1713     if (info->rgCmsRecipients)
1714     {
1715         DWORD i;
1716
1717         for (i = 0; i < info->cRecipients; ++i)
1718         {
1719             CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO *encodeInfo =
1720              info->rgCmsRecipients[i].u.pKeyTrans;
1721
1722             CryptMemFree(encodeInfo->KeyEncryptionAlgorithm.pszObjId);
1723             CryptMemFree(encodeInfo->KeyEncryptionAlgorithm.Parameters.pbData);
1724             CryptMemFree(encodeInfo->RecipientPublicKey.pbData);
1725             CryptMemFree(
1726              encodeInfo->RecipientId.u.IssuerSerialNumber.Issuer.pbData);
1727             CryptMemFree(
1728              encodeInfo->RecipientId.u.IssuerSerialNumber.SerialNumber.pbData);
1729             CryptMemFree(encodeInfo);
1730         }
1731         CryptMemFree(info->rgCmsRecipients);
1732     }
1733 }
1734
1735 static BOOL CRecipientInfo_Construct(CMSG_KEY_TRANS_RECIPIENT_INFO *info,
1736  const CERT_INFO *cert, CRYPT_DATA_BLOB *key)
1737 {
1738     BOOL ret;
1739
1740     info->dwVersion = CMSG_KEY_TRANS_PKCS_1_5_VERSION;
1741     info->RecipientId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1742     ret = CRYPT_ConstructBlob(&info->RecipientId.u.IssuerSerialNumber.Issuer,
1743      &cert->Issuer);
1744     if (ret)
1745         ret = CRYPT_ConstructBlob(
1746          &info->RecipientId.u.IssuerSerialNumber.SerialNumber,
1747          &cert->SerialNumber);
1748     if (ret)
1749         ret = CRYPT_ConstructAlgorithmId(&info->KeyEncryptionAlgorithm,
1750          &cert->SubjectPublicKeyInfo.Algorithm);
1751     info->EncryptedKey.cbData = key->cbData;
1752     info->EncryptedKey.pbData = key->pbData;
1753     return ret;
1754 }
1755
1756 static void CRecipientInfo_Free(CMSG_KEY_TRANS_RECIPIENT_INFO *info)
1757 {
1758     CryptMemFree(info->RecipientId.u.IssuerSerialNumber.Issuer.pbData);
1759     CryptMemFree(info->RecipientId.u.IssuerSerialNumber.SerialNumber.pbData);
1760     CryptMemFree(info->KeyEncryptionAlgorithm.pszObjId);
1761     CryptMemFree(info->KeyEncryptionAlgorithm.Parameters.pbData);
1762     CryptMemFree(info->EncryptedKey.pbData);
1763 }
1764
1765 static void CEnvelopedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
1766 {
1767     CEnvelopedEncodeMsg *msg = hCryptMsg;
1768
1769     CryptMemFree(msg->algo.pszObjId);
1770     CryptMemFree(msg->algo.Parameters.pbData);
1771     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1772         CryptReleaseContext(msg->prov, 0);
1773     CryptDestroyKey(msg->key);
1774     if (msg->recipientInfo)
1775     {
1776         DWORD i;
1777
1778         for (i = 0; i < msg->cRecipientInfo; ++i)
1779             CRecipientInfo_Free(&msg->recipientInfo[i]);
1780         CryptMemFree(msg->recipientInfo);
1781     }
1782     CryptMemFree(msg->data.pbData);
1783 }
1784
1785 static BOOL CEnvelopedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1786  DWORD dwIndex, void *pvData, DWORD *pcbData)
1787 {
1788     CEnvelopedEncodeMsg *msg = hCryptMsg;
1789     BOOL ret = FALSE;
1790
1791     switch (dwParamType)
1792     {
1793     case CMSG_BARE_CONTENT_PARAM:
1794         if (msg->base.streamed)
1795             SetLastError(E_INVALIDARG);
1796         else
1797         {
1798             char oid_rsa_data[] = szOID_RSA_data;
1799             CRYPT_ENVELOPED_DATA envelopedData = {
1800              CMSG_ENVELOPED_DATA_PKCS_1_5_VERSION, msg->cRecipientInfo,
1801              msg->recipientInfo, { oid_rsa_data, msg->algo, msg->data }
1802             };
1803
1804             ret = CRYPT_AsnEncodePKCSEnvelopedData(&envelopedData, pvData,
1805              pcbData);
1806         }
1807         break;
1808     case CMSG_CONTENT_PARAM:
1809     {
1810         CRYPT_CONTENT_INFO info;
1811
1812         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
1813          &info.Content.cbData);
1814         if (ret)
1815         {
1816             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
1817             if (info.Content.pbData)
1818             {
1819                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
1820                  info.Content.pbData, &info.Content.cbData);
1821                 if (ret)
1822                 {
1823                     char oid_rsa_enveloped[] = szOID_RSA_envelopedData;
1824
1825                     info.pszObjId = oid_rsa_enveloped;
1826                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
1827                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
1828                 }
1829                 CryptMemFree(info.Content.pbData);
1830             }
1831             else
1832                 ret = FALSE;
1833         }
1834         break;
1835     }
1836     default:
1837         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1838     }
1839     return ret;
1840 }
1841
1842 static BOOL CEnvelopedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1843  DWORD cbData, BOOL fFinal)
1844 {
1845     CEnvelopedEncodeMsg *msg = hCryptMsg;
1846     BOOL ret = FALSE;
1847
1848     if (msg->base.state == MsgStateFinalized)
1849         SetLastError(CRYPT_E_MSG_ERROR);
1850     else if (msg->base.streamed)
1851     {
1852         FIXME("streamed stub\n");
1853         msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
1854         ret = TRUE;
1855     }
1856     else
1857     {
1858         if (!fFinal)
1859         {
1860             if (msg->base.open_flags & CMSG_DETACHED_FLAG)
1861                 SetLastError(E_INVALIDARG);
1862             else
1863                 SetLastError(CRYPT_E_MSG_ERROR);
1864         }
1865         else
1866         {
1867             if (cbData)
1868             {
1869                 DWORD dataLen = cbData;
1870
1871                 msg->data.cbData = cbData;
1872                 msg->data.pbData = CryptMemAlloc(cbData);
1873                 if (msg->data.pbData)
1874                 {
1875                     memcpy(msg->data.pbData, pbData, cbData);
1876                     ret = CryptEncrypt(msg->key, 0, TRUE, 0, msg->data.pbData,
1877                      &dataLen, msg->data.cbData);
1878                     msg->data.cbData = dataLen;
1879                     if (dataLen > cbData)
1880                     {
1881                         msg->data.pbData = CryptMemRealloc(msg->data.pbData,
1882                          dataLen);
1883                         if (msg->data.pbData)
1884                         {
1885                             dataLen = cbData;
1886                             ret = CryptEncrypt(msg->key, 0, TRUE, 0,
1887                              msg->data.pbData, &dataLen, msg->data.cbData);
1888                         }
1889                         else
1890                             ret = FALSE;
1891                     }
1892                     if (!ret)
1893                         CryptMemFree(msg->data.pbData);
1894                 }
1895                 else
1896                     ret = FALSE;
1897                 if (!ret)
1898                 {
1899                     msg->data.cbData = 0;
1900                     msg->data.pbData = NULL;
1901                 }
1902             }
1903             else
1904                 ret = TRUE;
1905             msg->base.state = MsgStateFinalized;
1906         }
1907     }
1908     return ret;
1909 }
1910
1911 static HCRYPTMSG CEnvelopedEncodeMsg_Open(DWORD dwFlags,
1912  const void *pvMsgEncodeInfo, LPCSTR pszInnerContentObjID,
1913  PCMSG_STREAM_INFO pStreamInfo)
1914 {
1915     CEnvelopedEncodeMsg *msg;
1916     const CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS *info = pvMsgEncodeInfo;
1917     HCRYPTPROV prov;
1918     ALG_ID algID;
1919
1920     if (info->cbSize != sizeof(CMSG_ENVELOPED_ENCODE_INFO) &&
1921      info->cbSize != sizeof(CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS))
1922     {
1923         SetLastError(E_INVALIDARG);
1924         return NULL;
1925     }
1926     if (info->cbSize == sizeof(CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS))
1927         FIXME("CMS fields unsupported\n");
1928     if (!(algID = CertOIDToAlgId(info->ContentEncryptionAlgorithm.pszObjId)))
1929     {
1930         SetLastError(CRYPT_E_UNKNOWN_ALGO);
1931         return NULL;
1932     }
1933     if (info->cRecipients && !info->rgpRecipientCert)
1934     {
1935         SetLastError(E_INVALIDARG);
1936         return NULL;
1937     }
1938     if (info->hCryptProv)
1939         prov = info->hCryptProv;
1940     else
1941     {
1942         prov = CRYPT_GetDefaultProvider();
1943         dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
1944     }
1945     msg = CryptMemAlloc(sizeof(CEnvelopedEncodeMsg));
1946     if (msg)
1947     {
1948         CRYPT_DATA_BLOB encryptedKey = { 0, NULL };
1949         CMSG_CONTENT_ENCRYPT_INFO encryptInfo;
1950         BOOL ret;
1951         DWORD i;
1952
1953         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1954          CEnvelopedEncodeMsg_Close, CEnvelopedEncodeMsg_GetParam,
1955          CEnvelopedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1956         ret = CRYPT_ConstructAlgorithmId(&msg->algo,
1957          &info->ContentEncryptionAlgorithm);
1958         msg->prov = prov;
1959         msg->data.cbData = 0;
1960         msg->data.pbData = NULL;
1961         msg->cRecipientInfo = info->cRecipients;
1962         msg->recipientInfo = CryptMemAlloc(info->cRecipients *
1963          sizeof(CMSG_KEY_TRANS_RECIPIENT_INFO));
1964         if (!msg->recipientInfo)
1965             ret = FALSE;
1966         memset(&encryptInfo, 0, sizeof(encryptInfo));
1967         if (ret)
1968         {
1969             ret = CContentEncryptInfo_Construct(&encryptInfo, info, prov);
1970             if (ret)
1971             {
1972                 ret = CRYPT_GenKey(&encryptInfo, algID);
1973                 if (ret)
1974                     msg->key = encryptInfo.hContentEncryptKey;
1975             }
1976         }
1977         for (i = 0; ret && i < msg->cRecipientInfo; ++i)
1978         {
1979             ret = CRYPT_ExportEncryptedKey(&encryptInfo, i, &encryptedKey);
1980             if (ret)
1981                 ret = CRecipientInfo_Construct(&msg->recipientInfo[i],
1982                  info->rgpRecipientCert[i], &encryptedKey);
1983         }
1984         CContentEncryptInfo_Free(&encryptInfo);
1985         if (!ret)
1986         {
1987             CryptMsgClose(msg);
1988             msg = NULL;
1989         }
1990     }
1991     if (!msg && (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG))
1992         CryptReleaseContext(prov, 0);
1993     return msg;
1994 }
1995
1996 HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
1997  DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1998  PCMSG_STREAM_INFO pStreamInfo)
1999 {
2000     HCRYPTMSG msg = NULL;
2001
2002     TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
2003      dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
2004
2005     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
2006     {
2007         SetLastError(E_INVALIDARG);
2008         return NULL;
2009     }
2010     switch (dwMsgType)
2011     {
2012     case CMSG_DATA:
2013         msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
2014          pszInnerContentObjID, pStreamInfo);
2015         break;
2016     case CMSG_HASHED:
2017         msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
2018          pszInnerContentObjID, pStreamInfo);
2019         break;
2020     case CMSG_SIGNED:
2021         msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
2022          pszInnerContentObjID, pStreamInfo);
2023         break;
2024     case CMSG_ENVELOPED:
2025         msg = CEnvelopedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
2026          pszInnerContentObjID, pStreamInfo);
2027         break;
2028     case CMSG_SIGNED_AND_ENVELOPED:
2029     case CMSG_ENCRYPTED:
2030         /* defined but invalid, fall through */
2031     default:
2032         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2033     }
2034     return msg;
2035 }
2036
2037 typedef struct _CDecodeMsg
2038 {
2039     CryptMsgBase           base;
2040     DWORD                  type;
2041     HCRYPTPROV             crypt_prov;
2042     union {
2043         HCRYPTHASH     hash;
2044         CSignedMsgData signed_data;
2045     } u;
2046     CRYPT_DATA_BLOB        msg_data;
2047     CRYPT_DATA_BLOB        detached_data;
2048     PCONTEXT_PROPERTY_LIST properties;
2049 } CDecodeMsg;
2050
2051 static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
2052 {
2053     CDecodeMsg *msg = hCryptMsg;
2054
2055     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
2056         CryptReleaseContext(msg->crypt_prov, 0);
2057     switch (msg->type)
2058     {
2059     case CMSG_HASHED:
2060         if (msg->u.hash)
2061             CryptDestroyHash(msg->u.hash);
2062         break;
2063     case CMSG_SIGNED:
2064         if (msg->u.signed_data.info)
2065         {
2066             LocalFree(msg->u.signed_data.info);
2067             CSignedMsgData_CloseHandles(&msg->u.signed_data);
2068         }
2069         break;
2070     }
2071     CryptMemFree(msg->msg_data.pbData);
2072     CryptMemFree(msg->detached_data.pbData);
2073     ContextPropertyList_Free(msg->properties);
2074 }
2075
2076 static BOOL CDecodeMsg_CopyData(CRYPT_DATA_BLOB *blob, const BYTE *pbData,
2077  DWORD cbData)
2078 {
2079     BOOL ret = TRUE;
2080
2081     if (cbData)
2082     {
2083         if (blob->cbData)
2084             blob->pbData = CryptMemRealloc(blob->pbData,
2085              blob->cbData + cbData);
2086         else
2087             blob->pbData = CryptMemAlloc(cbData);
2088         if (blob->pbData)
2089         {
2090             memcpy(blob->pbData + blob->cbData, pbData, cbData);
2091             blob->cbData += cbData;
2092         }
2093         else
2094             ret = FALSE;
2095     }
2096     return ret;
2097 }
2098
2099 static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, const CRYPT_DER_BLOB *blob)
2100 {
2101     BOOL ret;
2102     CRYPT_DATA_BLOB *data;
2103     DWORD size;
2104
2105     ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
2106      blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &data, &size);
2107     if (ret)
2108     {
2109         ret = ContextPropertyList_SetProperty(msg->properties,
2110          CMSG_CONTENT_PARAM, data->pbData, data->cbData);
2111         LocalFree(data);
2112     }
2113     return ret;
2114 }
2115
2116 static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
2117  const CRYPT_ALGORITHM_IDENTIFIER *id)
2118 {
2119     static const BYTE nullParams[] = { ASN_NULL, 0 };
2120     CRYPT_ALGORITHM_IDENTIFIER *copy;
2121     DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);
2122
2123     /* Linearize algorithm id */
2124     len += strlen(id->pszObjId) + 1;
2125     len += id->Parameters.cbData;
2126     copy = CryptMemAlloc(len);
2127     if (copy)
2128     {
2129         copy->pszObjId =
2130          (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
2131         strcpy(copy->pszObjId, id->pszObjId);
2132         copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
2133          + 1;
2134         /* Trick:  omit NULL parameters */
2135         if (id->Parameters.cbData == sizeof(nullParams) &&
2136          !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
2137         {
2138             copy->Parameters.cbData = 0;
2139             len -= sizeof(nullParams);
2140         }
2141         else
2142             copy->Parameters.cbData = id->Parameters.cbData;
2143         if (copy->Parameters.cbData)
2144             memcpy(copy->Parameters.pbData, id->Parameters.pbData,
2145              id->Parameters.cbData);
2146         ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
2147          len);
2148         CryptMemFree(copy);
2149     }
2150 }
2151
2152 static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
2153 {
2154     id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
2155     id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
2156 }
2157
2158 static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
2159  const CRYPT_DER_BLOB *blob)
2160 {
2161     BOOL ret;
2162     CRYPT_DIGESTED_DATA *digestedData;
2163     DWORD size;
2164
2165     ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
2166      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
2167      &size);
2168     if (ret)
2169     {
2170         ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
2171          (const BYTE *)&digestedData->version, sizeof(digestedData->version));
2172         CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
2173          &digestedData->DigestAlgorithm);
2174         ContextPropertyList_SetProperty(msg->properties,
2175          CMSG_INNER_CONTENT_TYPE_PARAM,
2176          (const BYTE *)digestedData->ContentInfo.pszObjId,
2177          digestedData->ContentInfo.pszObjId ?
2178          strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
2179         if (!(msg->base.open_flags & CMSG_DETACHED_FLAG))
2180         {
2181             if (digestedData->ContentInfo.Content.cbData)
2182                 CDecodeMsg_DecodeDataContent(msg,
2183                  &digestedData->ContentInfo.Content);
2184             else
2185                 ContextPropertyList_SetProperty(msg->properties,
2186                  CMSG_CONTENT_PARAM, NULL, 0);
2187         }
2188         ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
2189          digestedData->hash.pbData, digestedData->hash.cbData);
2190         LocalFree(digestedData);
2191     }
2192     return ret;
2193 }
2194
2195 static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
2196  const CRYPT_DER_BLOB *blob)
2197 {
2198     BOOL ret;
2199     CRYPT_SIGNED_INFO *signedInfo;
2200     DWORD size;
2201
2202     ret = CRYPT_AsnDecodeCMSSignedInfo(blob->pbData, blob->cbData,
2203      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
2204      &size);
2205     if (ret)
2206         msg->u.signed_data.info = signedInfo;
2207     return ret;
2208 }
2209
2210 /* Decodes the content in blob as the type given, and updates the value
2211  * (type, parameters, etc.) of msg based on what blob contains.
2212  * It doesn't just use msg's type, to allow a recursive call from an implicitly
2213  * typed message once the outer content info has been decoded.
2214  */
2215 static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, const CRYPT_DER_BLOB *blob,
2216  DWORD type)
2217 {
2218     BOOL ret;
2219
2220     switch (type)
2221     {
2222     case CMSG_DATA:
2223         if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
2224             msg->type = CMSG_DATA;
2225         break;
2226     case CMSG_HASHED:
2227         if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
2228             msg->type = CMSG_HASHED;
2229         break;
2230     case CMSG_ENVELOPED:
2231         FIXME("unimplemented for type CMSG_ENVELOPED\n");
2232         ret = TRUE;
2233         break;
2234     case CMSG_SIGNED:
2235         if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
2236             msg->type = CMSG_SIGNED;
2237         break;
2238     default:
2239     {
2240         CRYPT_CONTENT_INFO *info;
2241         DWORD size;
2242
2243         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
2244          msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
2245          NULL, &info, &size);
2246         if (ret)
2247         {
2248             if (!strcmp(info->pszObjId, szOID_RSA_data))
2249                 ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
2250             else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
2251                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
2252                  CMSG_HASHED);
2253             else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
2254                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
2255                  CMSG_ENVELOPED);
2256             else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
2257                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
2258                  CMSG_SIGNED);
2259             else
2260             {
2261                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2262                 ret = FALSE;
2263             }
2264             LocalFree(info);
2265         }
2266     }
2267     }
2268     return ret;
2269 }
2270
2271 static BOOL CDecodeMsg_FinalizeHashedContent(CDecodeMsg *msg,
2272  CRYPT_DER_BLOB *blob)
2273 {
2274     CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
2275     DWORD size = 0;
2276     ALG_ID algID = 0;
2277     BOOL ret;
2278
2279     CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
2280     hashAlgoID = CryptMemAlloc(size);
2281     ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, hashAlgoID,
2282      &size);
2283     if (ret)
2284         algID = CertOIDToAlgId(hashAlgoID->pszObjId);
2285     ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->u.hash);
2286     if (ret)
2287     {
2288         CRYPT_DATA_BLOB content;
2289
2290         if (msg->base.open_flags & CMSG_DETACHED_FLAG)
2291         {
2292             /* Unlike for non-detached messages, the data were never stored as
2293              * the content param, but were saved in msg->detached_data instead.
2294              */
2295             content.pbData = msg->detached_data.pbData;
2296             content.cbData = msg->detached_data.cbData;
2297         }
2298         else
2299             ret = ContextPropertyList_FindProperty(msg->properties,
2300              CMSG_CONTENT_PARAM, &content);
2301         if (ret)
2302             ret = CryptHashData(msg->u.hash, content.pbData, content.cbData, 0);
2303     }
2304     CryptMemFree(hashAlgoID);
2305     return ret;
2306 }
2307
2308 static BOOL CDecodeMsg_FinalizeSignedContent(CDecodeMsg *msg,
2309  CRYPT_DER_BLOB *blob)
2310 {
2311     BOOL ret;
2312     DWORD i, size;
2313
2314     ret = CSignedMsgData_AllocateHandles(&msg->u.signed_data);
2315     for (i = 0; ret && i < msg->u.signed_data.info->cSignerInfo; i++)
2316         ret = CSignedMsgData_ConstructSignerHandles(&msg->u.signed_data, i,
2317          msg->crypt_prov);
2318     if (ret)
2319     {
2320         CRYPT_DATA_BLOB *content;
2321
2322         /* Now that we have all the content, update the hash handles with
2323          * it.  If the message is a detached message, the content is stored
2324          * in msg->detached_data rather than in the signed message's
2325          * content.
2326          */
2327         if (msg->base.open_flags & CMSG_DETACHED_FLAG)
2328             content = &msg->detached_data;
2329         else
2330             content = &msg->u.signed_data.info->content.Content;
2331         if (content->cbData)
2332         {
2333             /* If the message is not detached, have to decode the message's
2334              * content if the type is szOID_RSA_data.
2335              */
2336             if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) &&
2337              !strcmp(msg->u.signed_data.info->content.pszObjId,
2338              szOID_RSA_data))
2339             {
2340                 CRYPT_DATA_BLOB *blob;
2341
2342                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
2343                  X509_OCTET_STRING, content->pbData, content->cbData,
2344                  CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
2345                 if (ret)
2346                 {
2347                     ret = CSignedMsgData_Update(&msg->u.signed_data,
2348                      blob->pbData, blob->cbData, TRUE, Verify);
2349                     LocalFree(blob);
2350                 }
2351             }
2352             else
2353                 ret = CSignedMsgData_Update(&msg->u.signed_data,
2354                  content->pbData, content->cbData, TRUE, Verify);
2355         }
2356     }
2357     return ret;
2358 }
2359
2360 static BOOL CDecodeMsg_FinalizeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
2361 {
2362     BOOL ret = FALSE;
2363
2364     switch (msg->type)
2365     {
2366     case CMSG_HASHED:
2367         ret = CDecodeMsg_FinalizeHashedContent(msg, blob);
2368         break;
2369     case CMSG_SIGNED:
2370         ret = CDecodeMsg_FinalizeSignedContent(msg, blob);
2371         break;
2372     default:
2373         ret = TRUE;
2374     }
2375     return ret;
2376 }
2377
2378 static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
2379  DWORD cbData, BOOL fFinal)
2380 {
2381     CDecodeMsg *msg = hCryptMsg;
2382     BOOL ret = FALSE;
2383
2384     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
2385
2386     if (msg->base.state == MsgStateFinalized)
2387         SetLastError(CRYPT_E_MSG_ERROR);
2388     else if (msg->base.streamed)
2389     {
2390         FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
2391          cbData, fFinal);
2392         switch (msg->base.state)
2393         {
2394         case MsgStateInit:
2395             ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
2396             if (fFinal)
2397             {
2398                 if (msg->base.open_flags & CMSG_DETACHED_FLAG)
2399                     msg->base.state = MsgStateDataFinalized;
2400                 else
2401                     msg->base.state = MsgStateFinalized;
2402             }
2403             else
2404                 msg->base.state = MsgStateUpdated;
2405             break;
2406         case MsgStateUpdated:
2407             ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
2408             if (fFinal)
2409             {
2410                 if (msg->base.open_flags & CMSG_DETACHED_FLAG)
2411                     msg->base.state = MsgStateDataFinalized;
2412                 else
2413                     msg->base.state = MsgStateFinalized;
2414             }
2415             break;
2416         case MsgStateDataFinalized:
2417             ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
2418             if (fFinal)
2419                 msg->base.state = MsgStateFinalized;
2420             break;
2421         default:
2422             SetLastError(CRYPT_E_MSG_ERROR);
2423             break;
2424         }
2425     }
2426     else
2427     {
2428         if (!fFinal)
2429             SetLastError(CRYPT_E_MSG_ERROR);
2430         else
2431         {
2432             switch (msg->base.state)
2433             {
2434             case MsgStateInit:
2435                 ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
2436                 if (msg->base.open_flags & CMSG_DETACHED_FLAG)
2437                     msg->base.state = MsgStateDataFinalized;
2438                 else
2439                     msg->base.state = MsgStateFinalized;
2440                 break;
2441             case MsgStateDataFinalized:
2442                 ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
2443                 msg->base.state = MsgStateFinalized;
2444                 break;
2445             default:
2446                 SetLastError(CRYPT_E_MSG_ERROR);
2447             }
2448         }
2449     }
2450     if (ret && fFinal &&
2451      ((msg->base.open_flags & CMSG_DETACHED_FLAG && msg->base.state ==
2452      MsgStateDataFinalized) ||
2453      (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->base.state ==
2454      MsgStateFinalized)))
2455         ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
2456     if (ret && msg->base.state == MsgStateFinalized)
2457         ret = CDecodeMsg_FinalizeContent(msg, &msg->msg_data);
2458     return ret;
2459 }
2460
2461 static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
2462  DWORD dwIndex, void *pvData, DWORD *pcbData)
2463 {
2464     BOOL ret = FALSE;
2465
2466     switch (dwParamType)
2467     {
2468     case CMSG_TYPE_PARAM:
2469         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
2470         break;
2471     case CMSG_HASH_ALGORITHM_PARAM:
2472     {
2473         CRYPT_DATA_BLOB blob;
2474
2475         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2476          &blob);
2477         if (ret)
2478         {
2479             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
2480             if (ret && pvData)
2481                 CRYPT_FixUpAlgorithmID(pvData);
2482         }
2483         else
2484             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2485         break;
2486     }
2487     case CMSG_COMPUTED_HASH_PARAM:
2488         ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData, 0);
2489         break;
2490     default:
2491     {
2492         CRYPT_DATA_BLOB blob;
2493
2494         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2495          &blob);
2496         if (ret)
2497             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
2498         else
2499             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2500     }
2501     }
2502     return ret;
2503 }
2504
2505 /* nextData is an in/out parameter - on input it's the memory location in
2506  * which a copy of in's data should be made, and on output it's the memory
2507  * location immediately after out's copy of in's data.
2508  */
2509 static inline void CRYPT_CopyBlob(CRYPT_DATA_BLOB *out,
2510  const CRYPT_DATA_BLOB *in, LPBYTE *nextData)
2511 {
2512     out->cbData = in->cbData;
2513     if (in->cbData)
2514     {
2515         out->pbData = *nextData;
2516         memcpy(out->pbData, in->pbData, in->cbData);
2517         *nextData += in->cbData;
2518     }
2519 }
2520
2521 static inline void CRYPT_CopyAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
2522  const CRYPT_ALGORITHM_IDENTIFIER *in, LPBYTE *nextData)
2523 {
2524     if (in->pszObjId)
2525     {
2526         out->pszObjId = (LPSTR)*nextData;
2527         strcpy(out->pszObjId, in->pszObjId);
2528         *nextData += strlen(out->pszObjId) + 1;
2529     }
2530     CRYPT_CopyBlob(&out->Parameters, &in->Parameters, nextData);
2531 }
2532
2533 static inline void CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
2534  const CRYPT_ATTRIBUTES *in, LPBYTE *nextData)
2535 {
2536     out->cAttr = in->cAttr;
2537     if (in->cAttr)
2538     {
2539         DWORD i;
2540
2541         *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
2542         out->rgAttr = (CRYPT_ATTRIBUTE *)*nextData;
2543         *nextData += in->cAttr * sizeof(CRYPT_ATTRIBUTE);
2544         for (i = 0; i < in->cAttr; i++)
2545         {
2546             if (in->rgAttr[i].pszObjId)
2547             {
2548                 out->rgAttr[i].pszObjId = (LPSTR)*nextData;
2549                 strcpy(out->rgAttr[i].pszObjId, in->rgAttr[i].pszObjId);
2550                 *nextData += strlen(in->rgAttr[i].pszObjId) + 1;
2551             }
2552             if (in->rgAttr[i].cValue)
2553             {
2554                 DWORD j;
2555
2556                 out->rgAttr[i].cValue = in->rgAttr[i].cValue;
2557                 *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
2558                 out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
2559                 *nextData += in->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
2560                 for (j = 0; j < in->rgAttr[i].cValue; j++)
2561                     CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
2562                      &in->rgAttr[i].rgValue[j], nextData);
2563             }
2564         }
2565     }
2566 }
2567
2568 static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
2569 {
2570     DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;
2571
2572     for (i = 0; i < attr->cAttr; i++)
2573     {
2574         if (attr->rgAttr[i].pszObjId)
2575             size += strlen(attr->rgAttr[i].pszObjId) + 1;
2576         /* align pointer */
2577         size = ALIGN_DWORD_PTR(size);
2578         size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
2579         for (j = 0; j < attr->rgAttr[i].cValue; j++)
2580             size += attr->rgAttr[i].rgValue[j].cbData;
2581     }
2582     /* align pointer again to be conservative */
2583     size = ALIGN_DWORD_PTR(size);
2584     return size;
2585 }
2586
2587 static DWORD CRYPT_SizeOfKeyIdAsIssuerAndSerial(const CRYPT_DATA_BLOB *keyId)
2588 {
2589     static char oid_key_rdn[] = szOID_KEYID_RDN;
2590     DWORD size = 0;
2591     CERT_RDN_ATTR attr;
2592     CERT_RDN rdn = { 1, &attr };
2593     CERT_NAME_INFO name = { 1, &rdn };
2594
2595     attr.pszObjId = oid_key_rdn;
2596     attr.dwValueType = CERT_RDN_OCTET_STRING;
2597     attr.Value.cbData = keyId->cbData;
2598     attr.Value.pbData = keyId->pbData;
2599     if (CryptEncodeObject(X509_ASN_ENCODING, X509_NAME, &name, NULL, &size))
2600         size++; /* Only include size of special zero serial number on success */
2601     return size;
2602 }
2603
2604 static BOOL CRYPT_CopyKeyIdAsIssuerAndSerial(CERT_NAME_BLOB *issuer,
2605  CRYPT_INTEGER_BLOB *serialNumber, const CRYPT_DATA_BLOB *keyId, DWORD encodedLen,
2606  LPBYTE *nextData)
2607 {
2608     static char oid_key_rdn[] = szOID_KEYID_RDN;
2609     CERT_RDN_ATTR attr;
2610     CERT_RDN rdn = { 1, &attr };
2611     CERT_NAME_INFO name = { 1, &rdn };
2612     BOOL ret;
2613
2614     /* Encode special zero serial number */
2615     serialNumber->cbData = 1;
2616     serialNumber->pbData = *nextData;
2617     **nextData = 0;
2618     (*nextData)++;
2619     /* Encode issuer */
2620     issuer->pbData = *nextData;
2621     attr.pszObjId = oid_key_rdn;
2622     attr.dwValueType = CERT_RDN_OCTET_STRING;
2623     attr.Value.cbData = keyId->cbData;
2624     attr.Value.pbData = keyId->pbData;
2625     ret = CryptEncodeObject(X509_ASN_ENCODING, X509_NAME, &name, *nextData,
2626      &encodedLen);
2627     if (ret)
2628     {
2629         *nextData += encodedLen;
2630         issuer->cbData = encodedLen;
2631     }
2632     return ret;
2633 }
2634
2635 static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
2636  const CMSG_CMS_SIGNER_INFO *in)
2637 {
2638     DWORD size = sizeof(CMSG_SIGNER_INFO), rdnSize = 0;
2639     BOOL ret;
2640
2641     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
2642
2643     if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2644     {
2645         size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
2646         size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2647     }
2648     else
2649     {
2650         rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2651         size += rdnSize;
2652     }
2653     if (in->HashAlgorithm.pszObjId)
2654         size += strlen(in->HashAlgorithm.pszObjId) + 1;
2655     size += in->HashAlgorithm.Parameters.cbData;
2656     if (in->HashEncryptionAlgorithm.pszObjId)
2657         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
2658     size += in->HashEncryptionAlgorithm.Parameters.cbData;
2659     size += in->EncryptedHash.cbData;
2660     /* align pointer */
2661     size = ALIGN_DWORD_PTR(size);
2662     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
2663     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
2664     if (!pvData)
2665     {
2666         *pcbData = size;
2667         ret = TRUE;
2668     }
2669     else if (*pcbData < size)
2670     {
2671         *pcbData = size;
2672         SetLastError(ERROR_MORE_DATA);
2673         ret = FALSE;
2674     }
2675     else
2676     {
2677         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
2678         CMSG_SIGNER_INFO *out = pvData;
2679
2680         ret = TRUE;
2681         out->dwVersion = in->dwVersion;
2682         if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2683         {
2684             CRYPT_CopyBlob(&out->Issuer,
2685              &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2686             CRYPT_CopyBlob(&out->SerialNumber,
2687              &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2688         }
2689         else
2690             ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2691              &in->SignerId.u.KeyId, rdnSize, &nextData);
2692         if (ret)
2693         {
2694             CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
2695              &nextData);
2696             CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
2697              &in->HashEncryptionAlgorithm, &nextData);
2698             CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2699             nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2700             CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
2701             CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
2702         }
2703     }
2704     TRACE("returning %d\n", ret);
2705     return ret;
2706 }
2707
2708 static BOOL CRYPT_CopyCMSSignerInfo(void *pvData, DWORD *pcbData,
2709  const CMSG_CMS_SIGNER_INFO *in)
2710 {
2711     DWORD size = sizeof(CMSG_CMS_SIGNER_INFO);
2712     BOOL ret;
2713
2714     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
2715
2716     if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2717     {
2718         size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
2719         size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2720     }
2721     else
2722         size += in->SignerId.u.KeyId.cbData;
2723     if (in->HashAlgorithm.pszObjId)
2724         size += strlen(in->HashAlgorithm.pszObjId) + 1;
2725     size += in->HashAlgorithm.Parameters.cbData;
2726     if (in->HashEncryptionAlgorithm.pszObjId)
2727         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
2728     size += in->HashEncryptionAlgorithm.Parameters.cbData;
2729     size += in->EncryptedHash.cbData;
2730     /* align pointer */
2731     size = ALIGN_DWORD_PTR(size);
2732     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
2733     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
2734     if (!pvData)
2735     {
2736         *pcbData = size;
2737         ret = TRUE;
2738     }
2739     else if (*pcbData < size)
2740     {
2741         *pcbData = size;
2742         SetLastError(ERROR_MORE_DATA);
2743         ret = FALSE;
2744     }
2745     else
2746     {
2747         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_CMS_SIGNER_INFO);
2748         CMSG_CMS_SIGNER_INFO *out = pvData;
2749
2750         out->dwVersion = in->dwVersion;
2751         out->SignerId.dwIdChoice = in->SignerId.dwIdChoice;
2752         if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2753         {
2754             CRYPT_CopyBlob(&out->SignerId.u.IssuerSerialNumber.Issuer,
2755              &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2756             CRYPT_CopyBlob(&out->SignerId.u.IssuerSerialNumber.SerialNumber,
2757              &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2758         }
2759         else
2760             CRYPT_CopyBlob(&out->SignerId.u.KeyId, &in->SignerId.u.KeyId, &nextData);
2761         CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
2762          &nextData);
2763         CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
2764          &in->HashEncryptionAlgorithm, &nextData);
2765         CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2766         nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2767         CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
2768         CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
2769         ret = TRUE;
2770     }
2771     TRACE("returning %d\n", ret);
2772     return ret;
2773 }
2774
2775 static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
2776  const CMSG_CMS_SIGNER_INFO *in)
2777 {
2778     DWORD size = sizeof(CERT_INFO), rdnSize = 0;
2779     BOOL ret;
2780
2781     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
2782
2783     if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2784     {
2785         size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
2786         size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2787     }
2788     else
2789     {
2790         rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2791         size += rdnSize;
2792     }
2793     if (!pvData)
2794     {
2795         *pcbData = size;
2796         ret = TRUE;
2797     }
2798     else if (*pcbData < size)
2799     {
2800         *pcbData = size;
2801         SetLastError(ERROR_MORE_DATA);
2802         ret = FALSE;
2803     }
2804     else
2805     {
2806         LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
2807         CERT_INFO *out = pvData;
2808
2809         memset(out, 0, sizeof(CERT_INFO));
2810         if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2811         {
2812             CRYPT_CopyBlob(&out->Issuer,
2813              &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2814             CRYPT_CopyBlob(&out->SerialNumber,
2815              &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2816             ret = TRUE;
2817         }
2818         else
2819             ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2820              &in->SignerId.u.KeyId, rdnSize, &nextData);
2821     }
2822     TRACE("returning %d\n", ret);
2823     return ret;
2824 }
2825
2826 static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
2827  DWORD dwIndex, void *pvData, DWORD *pcbData)
2828 {
2829     BOOL ret = FALSE;
2830
2831     switch (dwParamType)
2832     {
2833     case CMSG_TYPE_PARAM:
2834         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
2835         break;
2836     case CMSG_CONTENT_PARAM:
2837         if (msg->u.signed_data.info)
2838         {
2839             if (!strcmp(msg->u.signed_data.info->content.pszObjId,
2840              szOID_RSA_data))
2841             {
2842                 CRYPT_DATA_BLOB *blob;
2843                 DWORD size;
2844
2845                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
2846                  msg->u.signed_data.info->content.Content.pbData,
2847                  msg->u.signed_data.info->content.Content.cbData,
2848                  CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
2849                 if (ret)
2850                 {
2851                     ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
2852                      blob->cbData);
2853                     LocalFree(blob);
2854                 }
2855             }
2856             else
2857                 ret = CRYPT_CopyParam(pvData, pcbData,
2858                  msg->u.signed_data.info->content.Content.pbData,
2859                  msg->u.signed_data.info->content.Content.cbData);
2860         }
2861         else
2862             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2863         break;
2864     case CMSG_INNER_CONTENT_TYPE_PARAM:
2865         if (msg->u.signed_data.info)
2866             ret = CRYPT_CopyParam(pvData, pcbData,
2867              msg->u.signed_data.info->content.pszObjId,
2868              strlen(msg->u.signed_data.info->content.pszObjId) + 1);
2869         else
2870             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2871         break;
2872     case CMSG_SIGNER_COUNT_PARAM:
2873         if (msg->u.signed_data.info)
2874             ret = CRYPT_CopyParam(pvData, pcbData,
2875              &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
2876         else
2877             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2878         break;
2879     case CMSG_SIGNER_INFO_PARAM:
2880         if (msg->u.signed_data.info)
2881         {
2882             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2883                 SetLastError(CRYPT_E_INVALID_INDEX);
2884             else
2885                 ret = CRYPT_CopySignerInfo(pvData, pcbData,
2886                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2887         }
2888         else
2889             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2890         break;
2891     case CMSG_SIGNER_CERT_INFO_PARAM:
2892         if (msg->u.signed_data.info)
2893         {
2894             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2895                 SetLastError(CRYPT_E_INVALID_INDEX);
2896             else
2897                 ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
2898                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2899         }
2900         else
2901             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2902         break;
2903     case CMSG_CERT_COUNT_PARAM:
2904         if (msg->u.signed_data.info)
2905             ret = CRYPT_CopyParam(pvData, pcbData,
2906              &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
2907         else
2908             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2909         break;
2910     case CMSG_CERT_PARAM:
2911         if (msg->u.signed_data.info)
2912         {
2913             if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
2914                 SetLastError(CRYPT_E_INVALID_INDEX);
2915             else
2916                 ret = CRYPT_CopyParam(pvData, pcbData,
2917                  msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
2918                  msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
2919         }
2920         else
2921             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2922         break;
2923     case CMSG_CRL_COUNT_PARAM:
2924         if (msg->u.signed_data.info)
2925             ret = CRYPT_CopyParam(pvData, pcbData,
2926              &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
2927         else
2928             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2929         break;
2930     case CMSG_CRL_PARAM:
2931         if (msg->u.signed_data.info)
2932         {
2933             if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
2934                 SetLastError(CRYPT_E_INVALID_INDEX);
2935             else
2936                 ret = CRYPT_CopyParam(pvData, pcbData,
2937                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
2938                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
2939         }
2940         else
2941             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2942         break;
2943     case CMSG_COMPUTED_HASH_PARAM:
2944         if (msg->u.signed_data.info)
2945         {
2946             if (dwIndex >= msg->u.signed_data.cSignerHandle)
2947                 SetLastError(CRYPT_E_INVALID_INDEX);
2948             else
2949                 ret = CryptGetHashParam(
2950                  msg->u.signed_data.signerHandles[dwIndex].contentHash,
2951                  HP_HASHVAL, pvData, pcbData, 0);
2952         }
2953         else
2954             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2955         break;
2956     case CMSG_ENCODED_SIGNER:
2957         if (msg->u.signed_data.info)
2958         {
2959             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2960                 SetLastError(CRYPT_E_INVALID_INDEX);
2961             else
2962                 ret = CryptEncodeObjectEx(
2963                  X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CMS_SIGNER_INFO,
2964                  &msg->u.signed_data.info->rgSignerInfo[dwIndex], 0, NULL,
2965                  pvData, pcbData);
2966         }
2967         else
2968             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2969         break;
2970     case CMSG_ATTR_CERT_COUNT_PARAM:
2971         if (msg->u.signed_data.info)
2972         {
2973             DWORD attrCertCount = 0;
2974
2975             ret = CRYPT_CopyParam(pvData, pcbData,
2976              &attrCertCount, sizeof(DWORD));
2977         }
2978         else
2979             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2980         break;
2981     case CMSG_ATTR_CERT_PARAM:
2982         if (msg->u.signed_data.info)
2983             SetLastError(CRYPT_E_INVALID_INDEX);
2984         else
2985             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2986         break;
2987     case CMSG_CMS_SIGNER_INFO_PARAM:
2988         if (msg->u.signed_data.info)
2989         {
2990             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2991                 SetLastError(CRYPT_E_INVALID_INDEX);
2992             else
2993                 ret = CRYPT_CopyCMSSignerInfo(pvData, pcbData,
2994                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2995         }
2996         else
2997             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2998         break;
2999     default:
3000         FIXME("unimplemented for %d\n", dwParamType);
3001         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3002     }
3003     return ret;
3004 }
3005
3006 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
3007  DWORD dwIndex, void *pvData, DWORD *pcbData)
3008 {
3009     CDecodeMsg *msg = hCryptMsg;
3010     BOOL ret = FALSE;
3011
3012     switch (msg->type)
3013     {
3014     case CMSG_HASHED:
3015         ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
3016          pcbData);
3017         break;
3018     case CMSG_SIGNED:
3019         ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
3020          pcbData);
3021         break;
3022     default:
3023         switch (dwParamType)
3024         {
3025         case CMSG_TYPE_PARAM:
3026             ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
3027              sizeof(msg->type));
3028             break;
3029         default:
3030         {
3031             CRYPT_DATA_BLOB blob;
3032
3033             ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
3034              &blob);
3035             if (ret)
3036                 ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
3037                  blob.cbData);
3038             else
3039                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3040         }
3041         }
3042     }
3043     return ret;
3044 }
3045
3046 static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
3047 {
3048     BOOL ret;
3049     CRYPT_DATA_BLOB hashBlob;
3050
3051     ret = ContextPropertyList_FindProperty(msg->properties,
3052      CMSG_HASH_DATA_PARAM, &hashBlob);
3053     if (ret)
3054     {
3055         DWORD computedHashSize = 0;
3056
3057         ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
3058          &computedHashSize);
3059         if (hashBlob.cbData == computedHashSize)
3060         {
3061             LPBYTE computedHash = CryptMemAlloc(computedHashSize);
3062
3063             if (computedHash)
3064             {
3065                 ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
3066                  computedHash, &computedHashSize);
3067                 if (ret)
3068                 {
3069                     if (memcmp(hashBlob.pbData, computedHash, hashBlob.cbData))
3070                     {
3071                         SetLastError(CRYPT_E_HASH_VALUE);
3072                         ret = FALSE;
3073                     }
3074                 }
3075                 CryptMemFree(computedHash);
3076             }
3077             else
3078             {
3079                 SetLastError(ERROR_OUTOFMEMORY);
3080                 ret = FALSE;
3081             }
3082         }
3083         else
3084         {
3085             SetLastError(CRYPT_E_HASH_VALUE);
3086             ret = FALSE;
3087         }
3088     }
3089     return ret;
3090 }
3091
3092 static BOOL CDecodeSignedMsg_VerifySignatureWithKey(CDecodeMsg *msg,
3093  HCRYPTPROV prov, DWORD signerIndex, PCERT_PUBLIC_KEY_INFO keyInfo)
3094 {
3095     HCRYPTKEY key;
3096     BOOL ret;
3097
3098     if (!prov)
3099         prov = msg->crypt_prov;
3100     ret = CryptImportPublicKeyInfo(prov, X509_ASN_ENCODING, keyInfo, &key);
3101     if (ret)
3102     {
3103         HCRYPTHASH hash;
3104         CRYPT_HASH_BLOB reversedHash;
3105
3106         if (msg->u.signed_data.info->rgSignerInfo[signerIndex].AuthAttrs.cAttr)
3107             hash = msg->u.signed_data.signerHandles[signerIndex].authAttrHash;
3108         else
3109             hash = msg->u.signed_data.signerHandles[signerIndex].contentHash;
3110         ret = CRYPT_ConstructBlob(&reversedHash,
3111          &msg->u.signed_data.info->rgSignerInfo[signerIndex].EncryptedHash);
3112         if (ret)
3113         {
3114             CRYPT_ReverseBytes(&reversedHash);
3115             ret = CryptVerifySignatureW(hash, reversedHash.pbData,
3116              reversedHash.cbData, key, NULL, 0);
3117             CryptMemFree(reversedHash.pbData);
3118         }
3119         CryptDestroyKey(key);
3120     }
3121     return ret;
3122 }
3123
3124 static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
3125 {
3126     BOOL ret = FALSE;
3127     DWORD i;
3128
3129     if (!msg->u.signed_data.signerHandles)
3130     {
3131         SetLastError(NTE_BAD_SIGNATURE);
3132         return FALSE;
3133     }
3134     for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
3135     {
3136         PCMSG_CMS_SIGNER_INFO signerInfo =
3137          &msg->u.signed_data.info->rgSignerInfo[i];
3138
3139         if (signerInfo->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
3140         {
3141             ret = CertCompareCertificateName(X509_ASN_ENCODING,
3142              &signerInfo->SignerId.u.IssuerSerialNumber.Issuer,
3143              &info->Issuer);
3144             if (ret)
3145             {
3146                 ret = CertCompareIntegerBlob(
3147                  &signerInfo->SignerId.u.IssuerSerialNumber.SerialNumber,
3148                  &info->SerialNumber);
3149                 if (ret)
3150                     break;
3151             }
3152         }
3153         else
3154         {
3155             FIXME("signer %d: unimplemented for key id\n", i);
3156         }
3157     }
3158     if (ret)
3159         ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, 0, i,
3160          &info->SubjectPublicKeyInfo);
3161     else
3162         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
3163
3164     return ret;
3165 }
3166
3167 static BOOL CDecodeSignedMsg_VerifySignatureEx(CDecodeMsg *msg,
3168  PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA para)
3169 {
3170     BOOL ret = FALSE;
3171
3172     if (para->cbSize != sizeof(CMSG_CTRL_VERIFY_SIGNATURE_EX_PARA))
3173         SetLastError(ERROR_INVALID_PARAMETER);
3174     else if (para->dwSignerIndex >= msg->u.signed_data.info->cSignerInfo)
3175         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
3176     else if (!msg->u.signed_data.signerHandles)
3177         SetLastError(NTE_BAD_SIGNATURE);
3178     else
3179     {
3180         switch (para->dwSignerType)
3181         {
3182         case CMSG_VERIFY_SIGNER_PUBKEY:
3183             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg,
3184              para->hCryptProv, para->dwSignerIndex, para->pvSigner);
3185             break;
3186         case CMSG_VERIFY_SIGNER_CERT:
3187         {
3188             PCCERT_CONTEXT cert = para->pvSigner;
3189
3190             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, para->hCryptProv,
3191              para->dwSignerIndex, &cert->pCertInfo->SubjectPublicKeyInfo);
3192             break;
3193         }
3194         default:
3195             FIXME("unimplemented for signer type %d\n", para->dwSignerType);
3196             SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
3197         }
3198     }
3199     return ret;
3200 }
3201
3202 static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
3203  DWORD dwCtrlType, const void *pvCtrlPara)
3204 {
3205     CDecodeMsg *msg = hCryptMsg;
3206     BOOL ret = FALSE;
3207
3208     switch (dwCtrlType)
3209     {
3210     case CMSG_CTRL_VERIFY_SIGNATURE:
3211         switch (msg->type)
3212         {
3213         case CMSG_SIGNED:
3214             ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
3215             break;
3216         default:
3217             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3218         }
3219         break;
3220     case CMSG_CTRL_DECRYPT:
3221         switch (msg->type)
3222         {
3223         default:
3224             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3225         }
3226         break;
3227     case CMSG_CTRL_VERIFY_HASH:
3228         switch (msg->type)
3229         {
3230         case CMSG_HASHED:
3231             ret = CDecodeHashMsg_VerifyHash(msg);
3232             break;
3233         default:
3234             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3235         }
3236         break;
3237     case CMSG_CTRL_VERIFY_SIGNATURE_EX:
3238         switch (msg->type)
3239         {
3240         case CMSG_SIGNED:
3241             ret = CDecodeSignedMsg_VerifySignatureEx(msg,
3242              (PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA)pvCtrlPara);
3243             break;
3244         default:
3245             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3246         }
3247         break;
3248     default:
3249         SetLastError(CRYPT_E_CONTROL_TYPE);
3250     }
3251     return ret;
3252 }
3253
3254 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
3255  DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
3256  PCMSG_STREAM_INFO pStreamInfo)
3257 {
3258     CDecodeMsg *msg;
3259
3260     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
3261      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
3262
3263     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
3264     {
3265         SetLastError(E_INVALIDARG);
3266         return NULL;
3267     }
3268     msg = CryptMemAlloc(sizeof(CDecodeMsg));
3269     if (msg)
3270     {
3271         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
3272          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
3273          CDecodeMsg_Control);
3274         msg->type = dwMsgType;
3275         if (hCryptProv)
3276             msg->crypt_prov = hCryptProv;
3277         else
3278         {
3279             msg->crypt_prov = CRYPT_GetDefaultProvider();
3280             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
3281         }
3282         memset(&msg->u, 0, sizeof(msg->u));
3283         msg->msg_data.cbData = 0;
3284         msg->msg_data.pbData = NULL;
3285         msg->detached_data.cbData = 0;
3286         msg->detached_data.pbData = NULL;
3287         msg->properties = ContextPropertyList_Create();
3288     }
3289     return msg;
3290 }
3291
3292 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
3293 {
3294     TRACE("(%p)\n", hCryptMsg);
3295
3296     if (hCryptMsg)
3297     {
3298         CryptMsgBase *msg = hCryptMsg;
3299
3300         InterlockedIncrement(&msg->ref);
3301     }
3302     return hCryptMsg;
3303 }
3304
3305 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
3306 {
3307     TRACE("(%p)\n", hCryptMsg);
3308
3309     if (hCryptMsg)
3310     {
3311         CryptMsgBase *msg = hCryptMsg;
3312
3313         if (InterlockedDecrement(&msg->ref) == 0)
3314         {
3315             TRACE("freeing %p\n", msg);
3316             if (msg->close)
3317                 msg->close(msg);
3318             CryptMemFree(msg);
3319         }
3320     }
3321     return TRUE;
3322 }
3323
3324 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
3325  DWORD cbData, BOOL fFinal)
3326 {
3327     CryptMsgBase *msg = hCryptMsg;
3328
3329     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
3330
3331     return msg->update(hCryptMsg, pbData, cbData, fFinal);
3332 }
3333
3334 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
3335  DWORD dwIndex, void *pvData, DWORD *pcbData)
3336 {
3337     CryptMsgBase *msg = hCryptMsg;
3338
3339     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
3340      pvData, pcbData);
3341     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
3342 }
3343
3344 BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
3345  DWORD dwCtrlType, const void *pvCtrlPara)
3346 {
3347     CryptMsgBase *msg = hCryptMsg;
3348
3349     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
3350      pvCtrlPara);
3351     return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
3352 }
3353
3354 static CERT_INFO *CRYPT_GetSignerCertInfoFromMsg(HCRYPTMSG msg,
3355  DWORD dwSignerIndex)
3356 {
3357     CERT_INFO *certInfo = NULL;
3358     DWORD size;
3359
3360     if (CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM, dwSignerIndex, NULL,
3361      &size))
3362     {
3363         certInfo = CryptMemAlloc(size);
3364         if (certInfo)
3365         {
3366             if (!CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM,
3367              dwSignerIndex, certInfo, &size))
3368             {
3369                 CryptMemFree(certInfo);
3370                 certInfo = NULL;
3371             }
3372         }
3373     }
3374     return certInfo;
3375 }
3376
3377 BOOL WINAPI CryptMsgGetAndVerifySigner(HCRYPTMSG hCryptMsg, DWORD cSignerStore,
3378  HCERTSTORE *rghSignerStore, DWORD dwFlags, PCCERT_CONTEXT *ppSigner,
3379  DWORD *pdwSignerIndex)
3380 {
3381     HCERTSTORE store;
3382     DWORD i, signerIndex = 0;
3383     PCCERT_CONTEXT signerCert = NULL;
3384     BOOL ret = FALSE;
3385
3386     TRACE("(%p, %d, %p, %08x, %p, %p)\n", hCryptMsg, cSignerStore,
3387      rghSignerStore, dwFlags, ppSigner, pdwSignerIndex);
3388
3389     /* Clear output parameters */
3390     if (ppSigner)
3391         *ppSigner = NULL;
3392     if (pdwSignerIndex && !(dwFlags & CMSG_USE_SIGNER_INDEX_FLAG))
3393         *pdwSignerIndex = 0;
3394
3395     /* Create store to search for signer certificates */
3396     store = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
3397      CERT_STORE_CREATE_NEW_FLAG, NULL);
3398     if (!(dwFlags & CMSG_TRUSTED_SIGNER_FLAG))
3399     {
3400         HCERTSTORE msgStore = CertOpenStore(CERT_STORE_PROV_MSG, 0, 0, 0,
3401          hCryptMsg);
3402
3403         CertAddStoreToCollection(store, msgStore, 0, 0);
3404         CertCloseStore(msgStore, 0);
3405     }
3406     for (i = 0; i < cSignerStore; i++)
3407         CertAddStoreToCollection(store, rghSignerStore[i], 0, 0);
3408
3409     /* Find signer cert */
3410     if (dwFlags & CMSG_USE_SIGNER_INDEX_FLAG)
3411     {
3412         CERT_INFO *signer = CRYPT_GetSignerCertInfoFromMsg(hCryptMsg,
3413          *pdwSignerIndex);
3414
3415         if (signer)
3416         {
3417             signerIndex = *pdwSignerIndex;
3418             signerCert = CertFindCertificateInStore(store, X509_ASN_ENCODING,
3419              0, CERT_FIND_SUBJECT_CERT, signer, NULL);
3420             CryptMemFree(signer);
3421         }
3422     }
3423     else
3424     {
3425         DWORD count, size = sizeof(count);
3426
3427         if (CryptMsgGetParam(hCryptMsg, CMSG_SIGNER_COUNT_PARAM, 0, &count,
3428          &size))
3429         {
3430             for (i = 0; !signerCert && i < count; i++)
3431             {
3432                 CERT_INFO *signer = CRYPT_GetSignerCertInfoFromMsg(hCryptMsg,
3433                  i);
3434
3435                 if (signer)
3436                 {
3437                     signerCert = CertFindCertificateInStore(store,
3438                      X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, signer,
3439                      NULL);
3440                     if (signerCert)
3441                         signerIndex = i;
3442                     CryptMemFree(signer);
3443                 }
3444             }
3445         }
3446         if (!signerCert)
3447             SetLastError(CRYPT_E_NO_TRUSTED_SIGNER);
3448     }
3449     if (signerCert)
3450     {
3451         if (!(dwFlags & CMSG_SIGNER_ONLY_FLAG))
3452             ret = CryptMsgControl(hCryptMsg, 0, CMSG_CTRL_VERIFY_SIGNATURE,
3453              signerCert->pCertInfo);
3454         else
3455             ret = TRUE;
3456         if (ret)
3457         {
3458             if (ppSigner)
3459                 *ppSigner = CertDuplicateCertificateContext(signerCert);
3460             if (pdwSignerIndex)
3461                 *pdwSignerIndex = signerIndex;
3462         }
3463         CertFreeCertificateContext(signerCert);
3464     }
3465
3466     CertCloseStore(store, 0);
3467     return ret;
3468 }
3469
3470 BOOL WINAPI CryptMsgVerifyCountersignatureEncodedEx(HCRYPTPROV_LEGACY hCryptProv,
3471  DWORD dwEncodingType, PBYTE pbSignerInfo, DWORD cbSignerInfo,
3472  PBYTE pbSignerInfoCountersignature, DWORD cbSignerInfoCountersignature,
3473  DWORD dwSignerType, void *pvSigner, DWORD dwFlags, void *pvReserved)
3474 {
3475     FIXME("(%08lx, %08x, %p, %d, %p, %d, %d, %p, %08x, %p): stub\n", hCryptProv,
3476      dwEncodingType, pbSignerInfo, cbSignerInfo, pbSignerInfoCountersignature,
3477      cbSignerInfoCountersignature, dwSignerType, pvSigner, dwFlags, pvReserved);
3478     return FALSE;
3479 }
3480
3481 BOOL WINAPI CryptMsgEncodeAndSignCTL(DWORD dwMsgEncodingType,
3482  PCTL_INFO pCtlInfo, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
3483  BYTE *pbEncoded, DWORD *pcbEncoded)
3484 {
3485     BOOL ret;
3486     BYTE *pbCtlContent;
3487     DWORD cbCtlContent;
3488
3489     TRACE("(%08x, %p, %p, %08x, %p, %p)\n", dwMsgEncodingType, pCtlInfo,
3490      pSignInfo, dwFlags, pbEncoded, pcbEncoded);
3491
3492     if (dwFlags)
3493     {
3494         FIXME("unimplemented for flags %08x\n", dwFlags);
3495         return FALSE;
3496     }
3497     if ((ret = CryptEncodeObjectEx(dwMsgEncodingType, PKCS_CTL, pCtlInfo,
3498      CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbCtlContent, &cbCtlContent)))
3499     {
3500         ret = CryptMsgSignCTL(dwMsgEncodingType, pbCtlContent, cbCtlContent,
3501          pSignInfo, dwFlags, pbEncoded, pcbEncoded);
3502         LocalFree(pbCtlContent);
3503     }
3504     return ret;
3505 }
3506
3507 BOOL WINAPI CryptMsgSignCTL(DWORD dwMsgEncodingType, BYTE *pbCtlContent,
3508  DWORD cbCtlContent, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
3509  BYTE *pbEncoded, DWORD *pcbEncoded)
3510 {
3511     static char oid_ctl[] = szOID_CTL;
3512     BOOL ret;
3513     HCRYPTMSG msg;
3514
3515     TRACE("(%08x, %p, %d, %p, %08x, %p, %p)\n", dwMsgEncodingType,
3516      pbCtlContent, cbCtlContent, pSignInfo, dwFlags, pbEncoded, pcbEncoded);
3517
3518     if (dwFlags)
3519     {
3520         FIXME("unimplemented for flags %08x\n", dwFlags);
3521         return FALSE;
3522     }
3523     msg = CryptMsgOpenToEncode(dwMsgEncodingType, 0, CMSG_SIGNED, pSignInfo,
3524      oid_ctl, NULL);
3525     if (msg)
3526     {
3527         ret = CryptMsgUpdate(msg, pbCtlContent, cbCtlContent, TRUE);
3528         if (ret)
3529             ret = CryptMsgGetParam(msg, CMSG_CONTENT_PARAM, 0, pbEncoded,
3530              pcbEncoded);
3531         CryptMsgClose(msg);
3532     }
3533     else
3534         ret = FALSE;
3535     return ret;
3536 }