ole32: Remove superfluous pointer casts.
[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(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(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 typedef struct _BlobArray
723 {
724     DWORD            cBlobs;
725     PCRYPT_DATA_BLOB blobs;
726 } BlobArray;
727
728 static BOOL CRYPT_ConstructBlobArray(BlobArray *out, const BlobArray *in)
729 {
730     BOOL ret = TRUE;
731
732     out->cBlobs = in->cBlobs;
733     if (out->cBlobs)
734     {
735         out->blobs = CryptMemAlloc(out->cBlobs * sizeof(CRYPT_DATA_BLOB));
736         if (out->blobs)
737         {
738             DWORD i;
739
740             memset(out->blobs, 0, out->cBlobs * sizeof(CRYPT_DATA_BLOB));
741             for (i = 0; ret && i < out->cBlobs; i++)
742                 ret = CRYPT_ConstructBlob(&out->blobs[i], &in->blobs[i]);
743         }
744         else
745             ret = FALSE;
746     }
747     return ret;
748 }
749
750 static void CRYPT_FreeBlobArray(BlobArray *array)
751 {
752     DWORD i;
753
754     for (i = 0; i < array->cBlobs; i++)
755         CryptMemFree(array->blobs[i].pbData);
756     CryptMemFree(array->blobs);
757 }
758
759 static BOOL CRYPT_ConstructAttribute(CRYPT_ATTRIBUTE *out,
760  const CRYPT_ATTRIBUTE *in)
761 {
762     BOOL ret;
763
764     out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
765     if (out->pszObjId)
766     {
767         strcpy(out->pszObjId, in->pszObjId);
768         ret = CRYPT_ConstructBlobArray((BlobArray *)&out->cValue,
769          (const BlobArray *)&in->cValue);
770     }
771     else
772         ret = FALSE;
773     return ret;
774 }
775
776 static BOOL CRYPT_ConstructAttributes(CRYPT_ATTRIBUTES *out,
777  const CRYPT_ATTRIBUTES *in)
778 {
779     BOOL ret = TRUE;
780
781     out->cAttr = in->cAttr;
782     if (out->cAttr)
783     {
784         out->rgAttr = CryptMemAlloc(out->cAttr * sizeof(CRYPT_ATTRIBUTE));
785         if (out->rgAttr)
786         {
787             DWORD i;
788
789             memset(out->rgAttr, 0, out->cAttr * sizeof(CRYPT_ATTRIBUTE));
790             for (i = 0; ret && i < out->cAttr; i++)
791                 ret = CRYPT_ConstructAttribute(&out->rgAttr[i], &in->rgAttr[i]);
792         }
793         else
794             ret = FALSE;
795     }
796     else
797         out->rgAttr = NULL;
798     return ret;
799 }
800
801 /* Constructs a CMSG_CMS_SIGNER_INFO from a CMSG_SIGNER_ENCODE_INFO_WITH_CMS. */
802 static BOOL CSignerInfo_Construct(CMSG_CMS_SIGNER_INFO *info,
803  const CMSG_SIGNER_ENCODE_INFO_WITH_CMS *in)
804 {
805     BOOL ret;
806
807     if (in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO))
808     {
809         info->dwVersion = CMSG_SIGNER_INFO_V1;
810         ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
811          &in->pCertInfo->Issuer);
812         if (ret)
813             ret = CRYPT_ConstructBlob(
814              &info->SignerId.u.IssuerSerialNumber.SerialNumber,
815              &in->pCertInfo->SerialNumber);
816         info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
817     }
818     else
819     {
820         /* Implicitly in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS).
821          * See CRYPT_IsValidSigner.
822          */
823         if (!in->SignerId.dwIdChoice)
824         {
825             info->dwVersion = CMSG_SIGNER_INFO_V1;
826             ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
827              &in->pCertInfo->Issuer);
828             if (ret)
829                 ret = CRYPT_ConstructBlob(
830                  &info->SignerId.u.IssuerSerialNumber.SerialNumber,
831                  &in->pCertInfo->SerialNumber);
832             info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
833         }
834         else if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
835         {
836             info->dwVersion = CMSG_SIGNER_INFO_V1;
837             info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
838             ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
839              &in->SignerId.u.IssuerSerialNumber.Issuer);
840             if (ret)
841                 ret = CRYPT_ConstructBlob(
842                  &info->SignerId.u.IssuerSerialNumber.SerialNumber,
843                  &in->SignerId.u.IssuerSerialNumber.SerialNumber);
844         }
845         else
846         {
847             /* Implicitly dwIdChoice == CERT_ID_KEY_IDENTIFIER */
848             info->dwVersion = CMSG_SIGNER_INFO_V3;
849             info->SignerId.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
850             ret = CRYPT_ConstructBlob(&info->SignerId.u.KeyId,
851              &in->SignerId.u.KeyId);
852         }
853     }
854     /* Assumption:  algorithm IDs will point to static strings, not
855      * stack-based ones, so copying the pointer values is safe.
856      */
857     info->HashAlgorithm.pszObjId = in->HashAlgorithm.pszObjId;
858     if (ret)
859         ret = CRYPT_ConstructBlob(&info->HashAlgorithm.Parameters,
860          &in->HashAlgorithm.Parameters);
861     memset(&info->HashEncryptionAlgorithm, 0,
862      sizeof(info->HashEncryptionAlgorithm));
863     if (ret)
864         ret = CRYPT_ConstructAttributes(&info->AuthAttrs,
865          (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
866     if (ret)
867         ret = CRYPT_ConstructAttributes(&info->UnauthAttrs,
868          (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
869     return ret;
870 }
871
872 static void CSignerInfo_Free(CMSG_CMS_SIGNER_INFO *info)
873 {
874     DWORD i, j;
875
876     if (info->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
877     {
878         CryptMemFree(info->SignerId.u.IssuerSerialNumber.Issuer.pbData);
879         CryptMemFree(info->SignerId.u.IssuerSerialNumber.SerialNumber.pbData);
880     }
881     else
882         CryptMemFree(info->SignerId.u.KeyId.pbData);
883     CryptMemFree(info->HashAlgorithm.Parameters.pbData);
884     CryptMemFree(info->EncryptedHash.pbData);
885     for (i = 0; i < info->AuthAttrs.cAttr; i++)
886     {
887         for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
888             CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
889         CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
890         CryptMemFree(info->AuthAttrs.rgAttr[i].pszObjId);
891     }
892     CryptMemFree(info->AuthAttrs.rgAttr);
893     for (i = 0; i < info->UnauthAttrs.cAttr; i++)
894     {
895         for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
896             CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
897         CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
898         CryptMemFree(info->UnauthAttrs.rgAttr[i].pszObjId);
899     }
900     CryptMemFree(info->UnauthAttrs.rgAttr);
901 }
902
903 typedef struct _CSignerHandles
904 {
905     HCRYPTHASH contentHash;
906     HCRYPTHASH authAttrHash;
907 } CSignerHandles;
908
909 typedef struct _CSignedMsgData
910 {
911     CRYPT_SIGNED_INFO *info;
912     DWORD              cSignerHandle;
913     CSignerHandles    *signerHandles;
914 } CSignedMsgData;
915
916 /* Constructs the signer handles for the signerIndex'th signer of msg_data.
917  * Assumes signerIndex is a valid idnex, and that msg_data's info has already
918  * been constructed.
919  */
920 static BOOL CSignedMsgData_ConstructSignerHandles(CSignedMsgData *msg_data,
921  DWORD signerIndex, HCRYPTPROV crypt_prov)
922 {
923     ALG_ID algID;
924     BOOL ret;
925
926     algID = CertOIDToAlgId(
927      msg_data->info->rgSignerInfo[signerIndex].HashAlgorithm.pszObjId);
928     ret = CryptCreateHash(crypt_prov, algID, 0, 0,
929      &msg_data->signerHandles->contentHash);
930     if (ret && msg_data->info->rgSignerInfo[signerIndex].AuthAttrs.cAttr > 0)
931         ret = CryptCreateHash(crypt_prov, algID, 0, 0,
932          &msg_data->signerHandles->authAttrHash);
933     return ret;
934 }
935
936 /* Allocates a CSignedMsgData's handles.  Assumes its info has already been
937  * constructed.
938  */
939 static BOOL CSignedMsgData_AllocateHandles(CSignedMsgData *msg_data)
940 {
941     BOOL ret = TRUE;
942
943     if (msg_data->info->cSignerInfo)
944     {
945         msg_data->signerHandles =
946          CryptMemAlloc(msg_data->info->cSignerInfo * sizeof(CSignerHandles));
947         if (msg_data->signerHandles)
948         {
949             msg_data->cSignerHandle = msg_data->info->cSignerInfo;
950             memset(msg_data->signerHandles, 0,
951              msg_data->info->cSignerInfo * sizeof(CSignerHandles));
952         }
953         else
954         {
955             msg_data->cSignerHandle = 0;
956             ret = FALSE;
957         }
958     }
959     else
960     {
961         msg_data->cSignerHandle = 0;
962         msg_data->signerHandles = NULL;
963     }
964     return ret;
965 }
966
967 static void CSignedMsgData_CloseHandles(CSignedMsgData *msg_data)
968 {
969     DWORD i;
970
971     for (i = 0; i < msg_data->cSignerHandle; i++)
972     {
973         if (msg_data->signerHandles[i].contentHash)
974             CryptDestroyHash(msg_data->signerHandles[i].contentHash);
975         if (msg_data->signerHandles[i].authAttrHash)
976             CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
977     }
978     CryptMemFree(msg_data->signerHandles);
979     msg_data->signerHandles = NULL;
980     msg_data->cSignerHandle = 0;
981 }
982
983 static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
984  const BYTE *pbData, DWORD cbData)
985 {
986     DWORD i;
987     BOOL ret = TRUE;
988
989     for (i = 0; ret && i < msg_data->cSignerHandle; i++)
990         ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
991          cbData, 0);
992     return ret;
993 }
994
995 static BOOL CRYPT_AppendAttribute(CRYPT_ATTRIBUTES *out,
996  const CRYPT_ATTRIBUTE *in)
997 {
998     BOOL ret = FALSE;
999
1000     out->rgAttr = CryptMemRealloc(out->rgAttr,
1001      (out->cAttr + 1) * sizeof(CRYPT_ATTRIBUTE));
1002     if (out->rgAttr)
1003     {
1004         ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
1005         if (ret)
1006             out->cAttr++;
1007     }
1008     return ret;
1009 }
1010
1011 static BOOL CSignedMsgData_AppendMessageDigestAttribute(
1012  CSignedMsgData *msg_data, DWORD signerIndex)
1013 {
1014     BOOL ret;
1015     DWORD size;
1016     CRYPT_HASH_BLOB hash = { 0, NULL }, encodedHash = { 0, NULL };
1017     char messageDigest[] = szOID_RSA_messageDigest;
1018     CRYPT_ATTRIBUTE messageDigestAttr = { messageDigest, 1, &encodedHash };
1019
1020     size = sizeof(DWORD);
1021     ret = CryptGetHashParam(
1022      msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
1023      (LPBYTE)&hash.cbData, &size, 0);
1024     if (ret)
1025     {
1026         hash.pbData = CryptMemAlloc(hash.cbData);
1027         ret = CryptGetHashParam(
1028          msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
1029          hash.pbData, &hash.cbData, 0);
1030         if (ret)
1031         {
1032             ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
1033              NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
1034             if (ret)
1035             {
1036                 ret = CRYPT_AppendAttribute(
1037                  &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
1038                  &messageDigestAttr);
1039                 LocalFree(encodedHash.pbData);
1040             }
1041         }
1042         CryptMemFree(hash.pbData);
1043     }
1044     return ret;
1045 }
1046
1047 typedef enum {
1048     Sign,
1049     Verify
1050 } SignOrVerify;
1051
1052 static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
1053  CSignedMsgData *msg_data, SignOrVerify flag)
1054 {
1055     DWORD i;
1056     BOOL ret = TRUE;
1057
1058     TRACE("(%p)\n", msg_data);
1059
1060     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1061     {
1062         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1063         {
1064             if (flag == Sign)
1065             {
1066                 BYTE oid_rsa_data_encoded[] = { 0x06,0x09,0x2a,0x86,0x48,0x86,
1067                  0xf7,0x0d,0x01,0x07,0x01 };
1068                 CRYPT_DATA_BLOB content = { sizeof(oid_rsa_data_encoded),
1069                  oid_rsa_data_encoded };
1070                 char contentType[] = szOID_RSA_contentType;
1071                 CRYPT_ATTRIBUTE contentTypeAttr = { contentType, 1, &content };
1072
1073                 /* FIXME: does this depend on inner OID? */
1074                 ret = CRYPT_AppendAttribute(
1075                  &msg_data->info->rgSignerInfo[i].AuthAttrs, &contentTypeAttr);
1076                 if (ret)
1077                     ret = CSignedMsgData_AppendMessageDigestAttribute(msg_data,
1078                      i);
1079             }
1080             if (ret)
1081             {
1082                 LPBYTE encodedAttrs;
1083                 DWORD size;
1084
1085                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
1086                  &msg_data->info->rgSignerInfo[i].AuthAttrs,
1087                  CRYPT_ENCODE_ALLOC_FLAG, NULL, &encodedAttrs, &size);
1088                 if (ret)
1089                 {
1090                     ret = CryptHashData(
1091                      msg_data->signerHandles[i].authAttrHash, encodedAttrs,
1092                      size, 0);
1093                     LocalFree(encodedAttrs);
1094                 }
1095             }
1096         }
1097     }
1098     TRACE("returning %d\n", ret);
1099     return ret;
1100 }
1101
1102 static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
1103 {
1104     DWORD i;
1105     BYTE tmp;
1106
1107     for (i = 0; i < hash->cbData / 2; i++)
1108     {
1109         tmp = hash->pbData[hash->cbData - i - 1];
1110         hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
1111         hash->pbData[i] = tmp;
1112     }
1113 }
1114
1115 static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
1116 {
1117     DWORD i;
1118     BOOL ret = TRUE;
1119
1120     TRACE("(%p)\n", msg_data);
1121
1122     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1123     {
1124         HCRYPTHASH hash;
1125
1126         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1127             hash = msg_data->signerHandles[i].authAttrHash;
1128         else
1129             hash = msg_data->signerHandles[i].contentHash;
1130         ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
1131          &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1132         if (ret)
1133         {
1134             msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
1135              CryptMemAlloc(
1136              msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1137             if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
1138             {
1139                 ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
1140                  msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
1141                  &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1142                 if (ret)
1143                     CRYPT_ReverseBytes(
1144                      &msg_data->info->rgSignerInfo[i].EncryptedHash);
1145             }
1146             else
1147                 ret = FALSE;
1148         }
1149     }
1150     return ret;
1151 }
1152
1153 static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1154  const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1155 {
1156     BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);
1157
1158     if (ret && fFinal)
1159     {
1160         ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
1161         if (ret && flag == Sign)
1162             ret = CSignedMsgData_Sign(msg_data);
1163     }
1164     return ret;
1165 }
1166
1167 typedef struct _CSignedEncodeMsg
1168 {
1169     CryptMsgBase    base;
1170     LPSTR           innerOID;
1171     CRYPT_DATA_BLOB data;
1172     CSignedMsgData  msg_data;
1173 } CSignedEncodeMsg;
1174
1175 static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
1176 {
1177     CSignedEncodeMsg *msg = hCryptMsg;
1178     DWORD i;
1179
1180     CryptMemFree(msg->innerOID);
1181     CryptMemFree(msg->data.pbData);
1182     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCertEncoded);
1183     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCrlEncoded);
1184     for (i = 0; i < msg->msg_data.info->cSignerInfo; i++)
1185         CSignerInfo_Free(&msg->msg_data.info->rgSignerInfo[i]);
1186     CSignedMsgData_CloseHandles(&msg->msg_data);
1187     CryptMemFree(msg->msg_data.info->rgSignerInfo);
1188     CryptMemFree(msg->msg_data.info);
1189 }
1190
1191 static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1192  DWORD dwIndex, void *pvData, DWORD *pcbData)
1193 {
1194     CSignedEncodeMsg *msg = hCryptMsg;
1195     BOOL ret = FALSE;
1196
1197     switch (dwParamType)
1198     {
1199     case CMSG_CONTENT_PARAM:
1200     {
1201         CRYPT_CONTENT_INFO info;
1202
1203         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
1204          &info.Content.cbData);
1205         if (ret)
1206         {
1207             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
1208             if (info.Content.pbData)
1209             {
1210                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
1211                  info.Content.pbData, &info.Content.cbData);
1212                 if (ret)
1213                 {
1214                     char oid_rsa_signed[] = szOID_RSA_signedData;
1215
1216                     info.pszObjId = oid_rsa_signed;
1217                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
1218                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
1219                 }
1220                 CryptMemFree(info.Content.pbData);
1221             }
1222             else
1223                 ret = FALSE;
1224         }
1225         break;
1226     }
1227     case CMSG_BARE_CONTENT_PARAM:
1228     {
1229         CRYPT_SIGNED_INFO info;
1230         BOOL freeContent = FALSE;
1231
1232         info = *msg->msg_data.info;
1233         if (!msg->innerOID || !strcmp(msg->innerOID, szOID_RSA_data))
1234         {
1235             char oid_rsa_data[] = szOID_RSA_data;
1236
1237             /* Quirk:  OID is only encoded messages if an update has happened */
1238             if (msg->base.state != MsgStateInit)
1239                 info.content.pszObjId = oid_rsa_data;
1240             else
1241                 info.content.pszObjId = NULL;
1242             if (msg->data.cbData)
1243             {
1244                 CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
1245
1246                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1247                  &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1248                  &info.content.Content.pbData, &info.content.Content.cbData);
1249                 freeContent = TRUE;
1250             }
1251             else
1252             {
1253                 info.content.Content.cbData = 0;
1254                 info.content.Content.pbData = NULL;
1255                 ret = TRUE;
1256             }
1257         }
1258         else
1259         {
1260             info.content.pszObjId = msg->innerOID;
1261             info.content.Content.cbData = msg->data.cbData;
1262             info.content.Content.pbData = msg->data.pbData;
1263             ret = TRUE;
1264         }
1265         if (ret)
1266         {
1267             ret = CRYPT_AsnEncodeCMSSignedInfo(&info, pvData, pcbData);
1268             if (freeContent)
1269                 LocalFree(info.content.Content.pbData);
1270         }
1271         break;
1272     }
1273     case CMSG_COMPUTED_HASH_PARAM:
1274         if (dwIndex >= msg->msg_data.cSignerHandle)
1275             SetLastError(CRYPT_E_INVALID_INDEX);
1276         else
1277             ret = CryptGetHashParam(
1278              msg->msg_data.signerHandles[dwIndex].contentHash, HP_HASHVAL,
1279              pvData, pcbData, 0);
1280         break;
1281     case CMSG_ENCODED_SIGNER:
1282         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1283             SetLastError(CRYPT_E_INVALID_INDEX);
1284         else
1285             ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1286              CMS_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1287              NULL, pvData, pcbData);
1288         break;
1289     case CMSG_VERSION_PARAM:
1290         ret = CRYPT_CopyParam(pvData, pcbData, &msg->msg_data.info->version,
1291          sizeof(msg->msg_data.info->version));
1292         break;
1293     default:
1294         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1295     }
1296     return ret;
1297 }
1298
1299 static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1300  DWORD cbData, BOOL fFinal)
1301 {
1302     CSignedEncodeMsg *msg = hCryptMsg;
1303     BOOL ret = FALSE;
1304
1305     if (msg->base.state == MsgStateFinalized)
1306         SetLastError(CRYPT_E_MSG_ERROR);
1307     else if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1308     {
1309         ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
1310          Sign);
1311         if (msg->base.streamed)
1312             FIXME("streamed partial stub\n");
1313         msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
1314     }
1315     else
1316     {
1317         if (!fFinal)
1318             SetLastError(CRYPT_E_MSG_ERROR);
1319         else
1320         {
1321             if (cbData)
1322             {
1323                 msg->data.pbData = CryptMemAlloc(cbData);
1324                 if (msg->data.pbData)
1325                 {
1326                     memcpy(msg->data.pbData, pbData, cbData);
1327                     msg->data.cbData = cbData;
1328                     ret = TRUE;
1329                 }
1330             }
1331             else
1332                 ret = TRUE;
1333             if (ret)
1334                 ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1335                  fFinal, Sign);
1336             msg->base.state = MsgStateFinalized;
1337         }
1338     }
1339     return ret;
1340 }
1341
1342 static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1343  const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1344  PCMSG_STREAM_INFO pStreamInfo)
1345 {
1346     const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info = pvMsgEncodeInfo;
1347     DWORD i;
1348     CSignedEncodeMsg *msg;
1349
1350     if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
1351      info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1352     {
1353         SetLastError(E_INVALIDARG);
1354         return NULL;
1355     }
1356     if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS) &&
1357      info->cAttrCertEncoded)
1358     {
1359         FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
1360         return NULL;
1361     }
1362     for (i = 0; i < info->cSigners; i++)
1363         if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
1364             return NULL;
1365     msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
1366     if (msg)
1367     {
1368         BOOL ret = TRUE;
1369
1370         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1371          CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1372          CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1373         if (pszInnerContentObjID)
1374         {
1375             msg->innerOID = CryptMemAlloc(strlen(pszInnerContentObjID) + 1);
1376             if (msg->innerOID)
1377                 strcpy(msg->innerOID, pszInnerContentObjID);
1378             else
1379                 ret = FALSE;
1380         }
1381         else
1382             msg->innerOID = NULL;
1383         msg->data.cbData = 0;
1384         msg->data.pbData = NULL;
1385         if (ret)
1386             msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
1387         else
1388             msg->msg_data.info = NULL;
1389         if (msg->msg_data.info)
1390         {
1391             memset(msg->msg_data.info, 0, sizeof(CRYPT_SIGNED_INFO));
1392             msg->msg_data.info->version = CMSG_SIGNED_DATA_V1;
1393         }
1394         else
1395             ret = FALSE;
1396         if (ret)
1397         {
1398             if (info->cSigners)
1399             {
1400                 msg->msg_data.info->rgSignerInfo =
1401                  CryptMemAlloc(info->cSigners * sizeof(CMSG_CMS_SIGNER_INFO));
1402                 if (msg->msg_data.info->rgSignerInfo)
1403                 {
1404                     msg->msg_data.info->cSignerInfo = info->cSigners;
1405                     memset(msg->msg_data.info->rgSignerInfo, 0,
1406                      msg->msg_data.info->cSignerInfo *
1407                      sizeof(CMSG_CMS_SIGNER_INFO));
1408                     ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
1409                     for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1410                     {
1411                         if (info->rgSigners[i].SignerId.dwIdChoice ==
1412                          CERT_ID_KEY_IDENTIFIER)
1413                             msg->msg_data.info->version = CMSG_SIGNED_DATA_V3;
1414                         ret = CSignerInfo_Construct(
1415                          &msg->msg_data.info->rgSignerInfo[i],
1416                          &info->rgSigners[i]);
1417                         if (ret)
1418                         {
1419                             ret = CSignedMsgData_ConstructSignerHandles(
1420                              &msg->msg_data, i, info->rgSigners[i].hCryptProv);
1421                             if (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1422                                 CryptReleaseContext(info->rgSigners[i].hCryptProv,
1423                                  0);
1424                         }
1425                     }
1426                 }
1427                 else
1428                     ret = FALSE;
1429             }
1430             else
1431             {
1432                 msg->msg_data.info->cSignerInfo = 0;
1433                 msg->msg_data.signerHandles = NULL;
1434                 msg->msg_data.cSignerHandle = 0;
1435             }
1436         }
1437         if (ret)
1438             ret = CRYPT_ConstructBlobArray(
1439              (BlobArray *)&msg->msg_data.info->cCertEncoded,
1440              (const BlobArray *)&info->cCertEncoded);
1441         if (ret)
1442             ret = CRYPT_ConstructBlobArray(
1443              (BlobArray *)&msg->msg_data.info->cCrlEncoded,
1444              (const BlobArray *)&info->cCrlEncoded);
1445         if (!ret)
1446         {
1447             CSignedEncodeMsg_Close(msg);
1448             msg = NULL;
1449         }
1450     }
1451     return msg;
1452 }
1453
1454 HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
1455  DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1456  PCMSG_STREAM_INFO pStreamInfo)
1457 {
1458     HCRYPTMSG msg = NULL;
1459
1460     TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
1461      dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
1462
1463     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
1464     {
1465         SetLastError(E_INVALIDARG);
1466         return NULL;
1467     }
1468     switch (dwMsgType)
1469     {
1470     case CMSG_DATA:
1471         msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1472          pszInnerContentObjID, pStreamInfo);
1473         break;
1474     case CMSG_HASHED:
1475         msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1476          pszInnerContentObjID, pStreamInfo);
1477         break;
1478     case CMSG_SIGNED:
1479         msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1480          pszInnerContentObjID, pStreamInfo);
1481         break;
1482     case CMSG_ENVELOPED:
1483         FIXME("unimplemented for type CMSG_ENVELOPED\n");
1484         break;
1485     case CMSG_SIGNED_AND_ENVELOPED:
1486     case CMSG_ENCRYPTED:
1487         /* defined but invalid, fall through */
1488     default:
1489         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1490     }
1491     return msg;
1492 }
1493
1494 typedef struct _CDecodeMsg
1495 {
1496     CryptMsgBase           base;
1497     DWORD                  type;
1498     HCRYPTPROV             crypt_prov;
1499     union {
1500         HCRYPTHASH     hash;
1501         CSignedMsgData signed_data;
1502     } u;
1503     CRYPT_DATA_BLOB        msg_data;
1504     CRYPT_DATA_BLOB        detached_data;
1505     PCONTEXT_PROPERTY_LIST properties;
1506 } CDecodeMsg;
1507
1508 static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
1509 {
1510     CDecodeMsg *msg = hCryptMsg;
1511
1512     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1513         CryptReleaseContext(msg->crypt_prov, 0);
1514     switch (msg->type)
1515     {
1516     case CMSG_HASHED:
1517         if (msg->u.hash)
1518             CryptDestroyHash(msg->u.hash);
1519         break;
1520     case CMSG_SIGNED:
1521         if (msg->u.signed_data.info)
1522         {
1523             LocalFree(msg->u.signed_data.info);
1524             CSignedMsgData_CloseHandles(&msg->u.signed_data);
1525         }
1526         break;
1527     }
1528     CryptMemFree(msg->msg_data.pbData);
1529     CryptMemFree(msg->detached_data.pbData);
1530     ContextPropertyList_Free(msg->properties);
1531 }
1532
1533 static BOOL CDecodeMsg_CopyData(CRYPT_DATA_BLOB *blob, const BYTE *pbData,
1534  DWORD cbData)
1535 {
1536     BOOL ret = TRUE;
1537
1538     if (cbData)
1539     {
1540         if (blob->cbData)
1541             blob->pbData = CryptMemRealloc(blob->pbData,
1542              blob->cbData + cbData);
1543         else
1544             blob->pbData = CryptMemAlloc(cbData);
1545         if (blob->pbData)
1546         {
1547             memcpy(blob->pbData + blob->cbData, pbData, cbData);
1548             blob->cbData += cbData;
1549         }
1550         else
1551             ret = FALSE;
1552     }
1553     return ret;
1554 }
1555
1556 static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
1557 {
1558     BOOL ret;
1559     CRYPT_DATA_BLOB *data;
1560     DWORD size;
1561
1562     ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1563      blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &data, &size);
1564     if (ret)
1565     {
1566         ret = ContextPropertyList_SetProperty(msg->properties,
1567          CMSG_CONTENT_PARAM, data->pbData, data->cbData);
1568         LocalFree(data);
1569     }
1570     return ret;
1571 }
1572
1573 static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
1574  const CRYPT_ALGORITHM_IDENTIFIER *id)
1575 {
1576     static const BYTE nullParams[] = { ASN_NULL, 0 };
1577     CRYPT_ALGORITHM_IDENTIFIER *copy;
1578     DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);
1579
1580     /* Linearize algorithm id */
1581     len += strlen(id->pszObjId) + 1;
1582     len += id->Parameters.cbData;
1583     copy = CryptMemAlloc(len);
1584     if (copy)
1585     {
1586         copy->pszObjId =
1587          (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1588         strcpy(copy->pszObjId, id->pszObjId);
1589         copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
1590          + 1;
1591         /* Trick:  omit NULL parameters */
1592         if (id->Parameters.cbData == sizeof(nullParams) &&
1593          !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
1594         {
1595             copy->Parameters.cbData = 0;
1596             len -= sizeof(nullParams);
1597         }
1598         else
1599             copy->Parameters.cbData = id->Parameters.cbData;
1600         if (copy->Parameters.cbData)
1601             memcpy(copy->Parameters.pbData, id->Parameters.pbData,
1602              id->Parameters.cbData);
1603         ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
1604          len);
1605         CryptMemFree(copy);
1606     }
1607 }
1608
1609 static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
1610 {
1611     id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1612     id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
1613 }
1614
1615 static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
1616  CRYPT_DER_BLOB *blob)
1617 {
1618     BOOL ret;
1619     CRYPT_DIGESTED_DATA *digestedData;
1620     DWORD size;
1621
1622     ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
1623      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
1624      &size);
1625     if (ret)
1626     {
1627         ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
1628          (const BYTE *)&digestedData->version, sizeof(digestedData->version));
1629         CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
1630          &digestedData->DigestAlgorithm);
1631         ContextPropertyList_SetProperty(msg->properties,
1632          CMSG_INNER_CONTENT_TYPE_PARAM,
1633          (const BYTE *)digestedData->ContentInfo.pszObjId,
1634          digestedData->ContentInfo.pszObjId ?
1635          strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
1636         if (!(msg->base.open_flags & CMSG_DETACHED_FLAG))
1637         {
1638             if (digestedData->ContentInfo.Content.cbData)
1639                 CDecodeMsg_DecodeDataContent(msg,
1640                  &digestedData->ContentInfo.Content);
1641             else
1642                 ContextPropertyList_SetProperty(msg->properties,
1643                  CMSG_CONTENT_PARAM, NULL, 0);
1644         }
1645         ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
1646          digestedData->hash.pbData, digestedData->hash.cbData);
1647         LocalFree(digestedData);
1648     }
1649     return ret;
1650 }
1651
1652 static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
1653  CRYPT_DER_BLOB *blob)
1654 {
1655     BOOL ret;
1656     CRYPT_SIGNED_INFO *signedInfo;
1657     DWORD size;
1658
1659     ret = CRYPT_AsnDecodeCMSSignedInfo(blob->pbData, blob->cbData,
1660      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
1661      &size);
1662     if (ret)
1663         msg->u.signed_data.info = signedInfo;
1664     return ret;
1665 }
1666
1667 /* Decodes the content in blob as the type given, and updates the value
1668  * (type, parameters, etc.) of msg based on what blob contains.
1669  * It doesn't just use msg's type, to allow a recursive call from an implicitly
1670  * typed message once the outer content info has been decoded.
1671  */
1672 static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob,
1673  DWORD type)
1674 {
1675     BOOL ret;
1676
1677     switch (type)
1678     {
1679     case CMSG_DATA:
1680         if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
1681             msg->type = CMSG_DATA;
1682         break;
1683     case CMSG_HASHED:
1684         if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
1685             msg->type = CMSG_HASHED;
1686         break;
1687     case CMSG_ENVELOPED:
1688         FIXME("unimplemented for type CMSG_ENVELOPED\n");
1689         ret = TRUE;
1690         break;
1691     case CMSG_SIGNED:
1692         if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
1693             msg->type = CMSG_SIGNED;
1694         break;
1695     default:
1696     {
1697         CRYPT_CONTENT_INFO *info;
1698         DWORD size;
1699
1700         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
1701          msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
1702          NULL, &info, &size);
1703         if (ret)
1704         {
1705             if (!strcmp(info->pszObjId, szOID_RSA_data))
1706                 ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
1707             else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
1708                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1709                  CMSG_HASHED);
1710             else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
1711                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1712                  CMSG_ENVELOPED);
1713             else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
1714                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1715                  CMSG_SIGNED);
1716             else
1717             {
1718                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1719                 ret = FALSE;
1720             }
1721             LocalFree(info);
1722         }
1723     }
1724     }
1725     return ret;
1726 }
1727
1728 static BOOL CDecodeMsg_FinalizeHashedContent(CDecodeMsg *msg,
1729  CRYPT_DER_BLOB *blob)
1730 {
1731     CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
1732     DWORD size = 0;
1733     ALG_ID algID = 0;
1734     BOOL ret;
1735
1736     CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
1737     hashAlgoID = CryptMemAlloc(size);
1738     ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, hashAlgoID,
1739      &size);
1740     if (ret)
1741         algID = CertOIDToAlgId(hashAlgoID->pszObjId);
1742     ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->u.hash);
1743     if (ret)
1744     {
1745         CRYPT_DATA_BLOB content;
1746
1747         if (msg->base.open_flags & CMSG_DETACHED_FLAG)
1748         {
1749             /* Unlike for non-detached messages, the data were never stored as
1750              * the content param, but were saved in msg->detached_data instead.
1751              */
1752             content.pbData = msg->detached_data.pbData;
1753             content.cbData = msg->detached_data.cbData;
1754         }
1755         else
1756             ret = ContextPropertyList_FindProperty(msg->properties,
1757              CMSG_CONTENT_PARAM, &content);
1758         if (ret)
1759             ret = CryptHashData(msg->u.hash, content.pbData, content.cbData, 0);
1760     }
1761     CryptMemFree(hashAlgoID);
1762     return ret;
1763 }
1764
1765 static BOOL CDecodeMsg_FinalizeSignedContent(CDecodeMsg *msg,
1766  CRYPT_DER_BLOB *blob)
1767 {
1768     BOOL ret;
1769     DWORD i, size;
1770
1771     ret = CSignedMsgData_AllocateHandles(&msg->u.signed_data);
1772     for (i = 0; ret && i < msg->u.signed_data.info->cSignerInfo; i++)
1773         ret = CSignedMsgData_ConstructSignerHandles(&msg->u.signed_data, i,
1774          msg->crypt_prov);
1775     if (ret)
1776     {
1777         CRYPT_DATA_BLOB *content;
1778
1779         /* Now that we have all the content, update the hash handles with
1780          * it.  If the message is a detached message, the content is stored
1781          * in msg->detached_data rather than in the signed message's
1782          * content.
1783          */
1784         if (msg->base.open_flags & CMSG_DETACHED_FLAG)
1785             content = &msg->detached_data;
1786         else
1787             content = &msg->u.signed_data.info->content.Content;
1788         if (content->cbData)
1789         {
1790             /* If the message is not detached, have to decode the message's
1791              * content if the type is szOID_RSA_data.
1792              */
1793             if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) &&
1794              !strcmp(msg->u.signed_data.info->content.pszObjId,
1795              szOID_RSA_data))
1796             {
1797                 CRYPT_DATA_BLOB *blob;
1798
1799                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
1800                  X509_OCTET_STRING, content->pbData, content->cbData,
1801                  CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
1802                 if (ret)
1803                 {
1804                     ret = CSignedMsgData_Update(&msg->u.signed_data,
1805                      blob->pbData, blob->cbData, TRUE, Verify);
1806                     LocalFree(blob);
1807                 }
1808             }
1809             else
1810                 ret = CSignedMsgData_Update(&msg->u.signed_data,
1811                  content->pbData, content->cbData, TRUE, Verify);
1812         }
1813     }
1814     return ret;
1815 }
1816
1817 static BOOL CDecodeMsg_FinalizeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
1818 {
1819     BOOL ret = FALSE;
1820
1821     switch (msg->type)
1822     {
1823     case CMSG_HASHED:
1824         ret = CDecodeMsg_FinalizeHashedContent(msg, blob);
1825         break;
1826     case CMSG_SIGNED:
1827         ret = CDecodeMsg_FinalizeSignedContent(msg, blob);
1828         break;
1829     default:
1830         ret = TRUE;
1831     }
1832     return ret;
1833 }
1834
1835 static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1836  DWORD cbData, BOOL fFinal)
1837 {
1838     CDecodeMsg *msg = hCryptMsg;
1839     BOOL ret = FALSE;
1840
1841     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
1842
1843     if (msg->base.state == MsgStateFinalized)
1844         SetLastError(CRYPT_E_MSG_ERROR);
1845     else if (msg->base.streamed)
1846     {
1847         FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
1848          cbData, fFinal);
1849         switch (msg->base.state)
1850         {
1851         case MsgStateInit:
1852             ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
1853             if (fFinal)
1854             {
1855                 if (msg->base.open_flags & CMSG_DETACHED_FLAG)
1856                     msg->base.state = MsgStateDataFinalized;
1857                 else
1858                     msg->base.state = MsgStateFinalized;
1859             }
1860             else
1861                 msg->base.state = MsgStateUpdated;
1862             break;
1863         case MsgStateUpdated:
1864             ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
1865             if (fFinal)
1866             {
1867                 if (msg->base.open_flags & CMSG_DETACHED_FLAG)
1868                     msg->base.state = MsgStateDataFinalized;
1869                 else
1870                     msg->base.state = MsgStateFinalized;
1871             }
1872             break;
1873         case MsgStateDataFinalized:
1874             ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
1875             if (fFinal)
1876                 msg->base.state = MsgStateFinalized;
1877             break;
1878         default:
1879             SetLastError(CRYPT_E_MSG_ERROR);
1880             break;
1881         }
1882     }
1883     else
1884     {
1885         if (!fFinal)
1886             SetLastError(CRYPT_E_MSG_ERROR);
1887         else
1888         {
1889             switch (msg->base.state)
1890             {
1891             case MsgStateInit:
1892                 ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
1893                 if (msg->base.open_flags & CMSG_DETACHED_FLAG)
1894                     msg->base.state = MsgStateDataFinalized;
1895                 else
1896                     msg->base.state = MsgStateFinalized;
1897                 break;
1898             case MsgStateDataFinalized:
1899                 ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
1900                 msg->base.state = MsgStateFinalized;
1901                 break;
1902             default:
1903                 SetLastError(CRYPT_E_MSG_ERROR);
1904             }
1905         }
1906     }
1907     if (ret && fFinal &&
1908      ((msg->base.open_flags & CMSG_DETACHED_FLAG && msg->base.state ==
1909      MsgStateDataFinalized) ||
1910      (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->base.state ==
1911      MsgStateFinalized)))
1912         ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
1913     if (ret && msg->base.state == MsgStateFinalized)
1914         ret = CDecodeMsg_FinalizeContent(msg, &msg->msg_data);
1915     return ret;
1916 }
1917
1918 static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1919  DWORD dwIndex, void *pvData, DWORD *pcbData)
1920 {
1921     BOOL ret = FALSE;
1922
1923     switch (dwParamType)
1924     {
1925     case CMSG_TYPE_PARAM:
1926         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1927         break;
1928     case CMSG_HASH_ALGORITHM_PARAM:
1929     {
1930         CRYPT_DATA_BLOB blob;
1931
1932         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1933          &blob);
1934         if (ret)
1935         {
1936             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1937             if (ret && pvData)
1938                 CRYPT_FixUpAlgorithmID(pvData);
1939         }
1940         else
1941             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1942         break;
1943     }
1944     case CMSG_COMPUTED_HASH_PARAM:
1945         ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData, 0);
1946         break;
1947     default:
1948     {
1949         CRYPT_DATA_BLOB blob;
1950
1951         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1952          &blob);
1953         if (ret)
1954             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1955         else
1956             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1957     }
1958     }
1959     return ret;
1960 }
1961
1962 /* nextData is an in/out parameter - on input it's the memory location in
1963  * which a copy of in's data should be made, and on output it's the memory
1964  * location immediately after out's copy of in's data.
1965  */
1966 static inline void CRYPT_CopyBlob(CRYPT_DATA_BLOB *out,
1967  const CRYPT_DATA_BLOB *in, LPBYTE *nextData)
1968 {
1969     out->cbData = in->cbData;
1970     if (in->cbData)
1971     {
1972         out->pbData = *nextData;
1973         memcpy(out->pbData, in->pbData, in->cbData);
1974         *nextData += in->cbData;
1975     }
1976 }
1977
1978 static inline void CRYPT_CopyAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
1979  const CRYPT_ALGORITHM_IDENTIFIER *in, LPBYTE *nextData)
1980 {
1981     if (in->pszObjId)
1982     {
1983         out->pszObjId = (LPSTR)*nextData;
1984         strcpy(out->pszObjId, in->pszObjId);
1985         *nextData += strlen(out->pszObjId) + 1;
1986     }
1987     CRYPT_CopyBlob(&out->Parameters, &in->Parameters, nextData);
1988 }
1989
1990 static inline void CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
1991  const CRYPT_ATTRIBUTES *in, LPBYTE *nextData)
1992 {
1993     out->cAttr = in->cAttr;
1994     if (in->cAttr)
1995     {
1996         DWORD i;
1997
1998         *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
1999         out->rgAttr = (CRYPT_ATTRIBUTE *)*nextData;
2000         *nextData += in->cAttr * sizeof(CRYPT_ATTRIBUTE);
2001         for (i = 0; i < in->cAttr; i++)
2002         {
2003             if (in->rgAttr[i].pszObjId)
2004             {
2005                 out->rgAttr[i].pszObjId = (LPSTR)*nextData;
2006                 strcpy(out->rgAttr[i].pszObjId, in->rgAttr[i].pszObjId);
2007                 *nextData += strlen(in->rgAttr[i].pszObjId) + 1;
2008             }
2009             if (in->rgAttr[i].cValue)
2010             {
2011                 DWORD j;
2012
2013                 out->rgAttr[i].cValue = in->rgAttr[i].cValue;
2014                 *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
2015                 out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
2016                 *nextData += in->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
2017                 for (j = 0; j < in->rgAttr[i].cValue; j++)
2018                     CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
2019                      &in->rgAttr[i].rgValue[j], nextData);
2020             }
2021         }
2022     }
2023 }
2024
2025 static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
2026 {
2027     DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;
2028
2029     for (i = 0; i < attr->cAttr; i++)
2030     {
2031         if (attr->rgAttr[i].pszObjId)
2032             size += strlen(attr->rgAttr[i].pszObjId) + 1;
2033         /* align pointer */
2034         size = ALIGN_DWORD_PTR(size);
2035         size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
2036         for (j = 0; j < attr->rgAttr[i].cValue; j++)
2037             size += attr->rgAttr[i].rgValue[j].cbData;
2038     }
2039     /* align pointer again to be conservative */
2040     size = ALIGN_DWORD_PTR(size);
2041     return size;
2042 }
2043
2044 static DWORD CRYPT_SizeOfKeyIdAsIssuerAndSerial(const CRYPT_DATA_BLOB *keyId)
2045 {
2046     static char oid_key_rdn[] = szOID_KEYID_RDN;
2047     DWORD size = 0;
2048     CERT_RDN_ATTR attr;
2049     CERT_RDN rdn = { 1, &attr };
2050     CERT_NAME_INFO name = { 1, &rdn };
2051
2052     attr.pszObjId = oid_key_rdn;
2053     attr.dwValueType = CERT_RDN_OCTET_STRING;
2054     attr.Value.cbData = keyId->cbData;
2055     attr.Value.pbData = keyId->pbData;
2056     if (CryptEncodeObject(X509_ASN_ENCODING, X509_NAME, &name, NULL, &size))
2057         size++; /* Only include size of special zero serial number on success */
2058     return size;
2059 }
2060
2061 static BOOL CRYPT_CopyKeyIdAsIssuerAndSerial(CERT_NAME_BLOB *issuer,
2062  CRYPT_INTEGER_BLOB *serialNumber, const CRYPT_DATA_BLOB *keyId, DWORD encodedLen,
2063  LPBYTE *nextData)
2064 {
2065     static char oid_key_rdn[] = szOID_KEYID_RDN;
2066     CERT_RDN_ATTR attr;
2067     CERT_RDN rdn = { 1, &attr };
2068     CERT_NAME_INFO name = { 1, &rdn };
2069     BOOL ret;
2070
2071     /* Encode special zero serial number */
2072     serialNumber->cbData = 1;
2073     serialNumber->pbData = *nextData;
2074     **nextData = 0;
2075     (*nextData)++;
2076     /* Encode issuer */
2077     issuer->pbData = *nextData;
2078     attr.pszObjId = oid_key_rdn;
2079     attr.dwValueType = CERT_RDN_OCTET_STRING;
2080     attr.Value.cbData = keyId->cbData;
2081     attr.Value.pbData = keyId->pbData;
2082     ret = CryptEncodeObject(X509_ASN_ENCODING, X509_NAME, &name, *nextData,
2083      &encodedLen);
2084     if (ret)
2085     {
2086         *nextData += encodedLen;
2087         issuer->cbData = encodedLen;
2088     }
2089     return ret;
2090 }
2091
2092 static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
2093  const CMSG_CMS_SIGNER_INFO *in)
2094 {
2095     DWORD size = sizeof(CMSG_SIGNER_INFO), rdnSize = 0;
2096     BOOL ret;
2097
2098     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
2099
2100     if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2101     {
2102         size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
2103         size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2104     }
2105     else
2106     {
2107         rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2108         size += rdnSize;
2109     }
2110     if (in->HashAlgorithm.pszObjId)
2111         size += strlen(in->HashAlgorithm.pszObjId) + 1;
2112     size += in->HashAlgorithm.Parameters.cbData;
2113     if (in->HashEncryptionAlgorithm.pszObjId)
2114         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
2115     size += in->HashEncryptionAlgorithm.Parameters.cbData;
2116     size += in->EncryptedHash.cbData;
2117     /* align pointer */
2118     size = ALIGN_DWORD_PTR(size);
2119     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
2120     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
2121     if (!pvData)
2122     {
2123         *pcbData = size;
2124         ret = TRUE;
2125     }
2126     else if (*pcbData < size)
2127     {
2128         *pcbData = size;
2129         SetLastError(ERROR_MORE_DATA);
2130         ret = FALSE;
2131     }
2132     else
2133     {
2134         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
2135         CMSG_SIGNER_INFO *out = pvData;
2136
2137         ret = TRUE;
2138         out->dwVersion = in->dwVersion;
2139         if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2140         {
2141             CRYPT_CopyBlob(&out->Issuer,
2142              &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2143             CRYPT_CopyBlob(&out->SerialNumber,
2144              &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2145         }
2146         else
2147             ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2148              &in->SignerId.u.KeyId, rdnSize, &nextData);
2149         if (ret)
2150         {
2151             CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
2152              &nextData);
2153             CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
2154              &in->HashEncryptionAlgorithm, &nextData);
2155             CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2156             nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2157             CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
2158             CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
2159         }
2160     }
2161     TRACE("returning %d\n", ret);
2162     return ret;
2163 }
2164
2165 static BOOL CRYPT_CopyCMSSignerInfo(void *pvData, DWORD *pcbData,
2166  const CMSG_CMS_SIGNER_INFO *in)
2167 {
2168     DWORD size = sizeof(CMSG_CMS_SIGNER_INFO);
2169     BOOL ret;
2170
2171     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
2172
2173     if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2174     {
2175         size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
2176         size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2177     }
2178     else
2179         size += in->SignerId.u.KeyId.cbData;
2180     if (in->HashAlgorithm.pszObjId)
2181         size += strlen(in->HashAlgorithm.pszObjId) + 1;
2182     size += in->HashAlgorithm.Parameters.cbData;
2183     if (in->HashEncryptionAlgorithm.pszObjId)
2184         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
2185     size += in->HashEncryptionAlgorithm.Parameters.cbData;
2186     size += in->EncryptedHash.cbData;
2187     /* align pointer */
2188     size = ALIGN_DWORD_PTR(size);
2189     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
2190     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
2191     if (!pvData)
2192     {
2193         *pcbData = size;
2194         ret = TRUE;
2195     }
2196     else if (*pcbData < size)
2197     {
2198         *pcbData = size;
2199         SetLastError(ERROR_MORE_DATA);
2200         ret = FALSE;
2201     }
2202     else
2203     {
2204         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_CMS_SIGNER_INFO);
2205         CMSG_CMS_SIGNER_INFO *out = pvData;
2206
2207         out->dwVersion = in->dwVersion;
2208         out->SignerId.dwIdChoice = in->SignerId.dwIdChoice;
2209         if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2210         {
2211             CRYPT_CopyBlob(&out->SignerId.u.IssuerSerialNumber.Issuer,
2212              &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2213             CRYPT_CopyBlob(&out->SignerId.u.IssuerSerialNumber.SerialNumber,
2214              &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2215         }
2216         else
2217             CRYPT_CopyBlob(&out->SignerId.u.KeyId, &in->SignerId.u.KeyId, &nextData);
2218         CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
2219          &nextData);
2220         CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
2221          &in->HashEncryptionAlgorithm, &nextData);
2222         CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2223         nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2224         CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
2225         CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
2226         ret = TRUE;
2227     }
2228     TRACE("returning %d\n", ret);
2229     return ret;
2230 }
2231
2232 static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
2233  const CMSG_CMS_SIGNER_INFO *in)
2234 {
2235     DWORD size = sizeof(CERT_INFO), rdnSize = 0;
2236     BOOL ret;
2237
2238     TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);
2239
2240     if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2241     {
2242         size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
2243         size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2244     }
2245     else
2246     {
2247         rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2248         size += rdnSize;
2249     }
2250     if (!pvData)
2251     {
2252         *pcbData = size;
2253         ret = TRUE;
2254     }
2255     else if (*pcbData < size)
2256     {
2257         *pcbData = size;
2258         SetLastError(ERROR_MORE_DATA);
2259         ret = FALSE;
2260     }
2261     else
2262     {
2263         LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
2264         CERT_INFO *out = pvData;
2265
2266         memset(out, 0, sizeof(CERT_INFO));
2267         if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2268         {
2269             CRYPT_CopyBlob(&out->Issuer,
2270              &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2271             CRYPT_CopyBlob(&out->SerialNumber,
2272              &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2273             ret = TRUE;
2274         }
2275         else
2276             ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2277              &in->SignerId.u.KeyId, rdnSize, &nextData);
2278     }
2279     TRACE("returning %d\n", ret);
2280     return ret;
2281 }
2282
2283 static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
2284  DWORD dwIndex, void *pvData, DWORD *pcbData)
2285 {
2286     BOOL ret = FALSE;
2287
2288     switch (dwParamType)
2289     {
2290     case CMSG_TYPE_PARAM:
2291         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
2292         break;
2293     case CMSG_CONTENT_PARAM:
2294         if (msg->u.signed_data.info)
2295         {
2296             if (!strcmp(msg->u.signed_data.info->content.pszObjId,
2297              szOID_RSA_data))
2298             {
2299                 CRYPT_DATA_BLOB *blob;
2300                 DWORD size;
2301
2302                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
2303                  msg->u.signed_data.info->content.Content.pbData,
2304                  msg->u.signed_data.info->content.Content.cbData,
2305                  CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
2306                 if (ret)
2307                 {
2308                     ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
2309                      blob->cbData);
2310                     LocalFree(blob);
2311                 }
2312             }
2313             else
2314                 ret = CRYPT_CopyParam(pvData, pcbData,
2315                  msg->u.signed_data.info->content.Content.pbData,
2316                  msg->u.signed_data.info->content.Content.cbData);
2317         }
2318         else
2319             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2320         break;
2321     case CMSG_INNER_CONTENT_TYPE_PARAM:
2322         if (msg->u.signed_data.info)
2323             ret = CRYPT_CopyParam(pvData, pcbData,
2324              msg->u.signed_data.info->content.pszObjId,
2325              strlen(msg->u.signed_data.info->content.pszObjId) + 1);
2326         else
2327             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2328         break;
2329     case CMSG_SIGNER_COUNT_PARAM:
2330         if (msg->u.signed_data.info)
2331             ret = CRYPT_CopyParam(pvData, pcbData,
2332              &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
2333         else
2334             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2335         break;
2336     case CMSG_SIGNER_INFO_PARAM:
2337         if (msg->u.signed_data.info)
2338         {
2339             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2340                 SetLastError(CRYPT_E_INVALID_INDEX);
2341             else
2342                 ret = CRYPT_CopySignerInfo(pvData, pcbData,
2343                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2344         }
2345         else
2346             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2347         break;
2348     case CMSG_SIGNER_CERT_INFO_PARAM:
2349         if (msg->u.signed_data.info)
2350         {
2351             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2352                 SetLastError(CRYPT_E_INVALID_INDEX);
2353             else
2354                 ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
2355                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2356         }
2357         else
2358             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2359         break;
2360     case CMSG_CERT_COUNT_PARAM:
2361         if (msg->u.signed_data.info)
2362             ret = CRYPT_CopyParam(pvData, pcbData,
2363              &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
2364         else
2365             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2366         break;
2367     case CMSG_CERT_PARAM:
2368         if (msg->u.signed_data.info)
2369         {
2370             if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
2371                 SetLastError(CRYPT_E_INVALID_INDEX);
2372             else
2373                 ret = CRYPT_CopyParam(pvData, pcbData,
2374                  msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
2375                  msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
2376         }
2377         else
2378             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2379         break;
2380     case CMSG_CRL_COUNT_PARAM:
2381         if (msg->u.signed_data.info)
2382             ret = CRYPT_CopyParam(pvData, pcbData,
2383              &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
2384         else
2385             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2386         break;
2387     case CMSG_CRL_PARAM:
2388         if (msg->u.signed_data.info)
2389         {
2390             if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
2391                 SetLastError(CRYPT_E_INVALID_INDEX);
2392             else
2393                 ret = CRYPT_CopyParam(pvData, pcbData,
2394                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
2395                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
2396         }
2397         else
2398             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2399         break;
2400     case CMSG_COMPUTED_HASH_PARAM:
2401         if (msg->u.signed_data.info)
2402         {
2403             if (dwIndex >= msg->u.signed_data.cSignerHandle)
2404                 SetLastError(CRYPT_E_INVALID_INDEX);
2405             else
2406                 ret = CryptGetHashParam(
2407                  msg->u.signed_data.signerHandles[dwIndex].contentHash,
2408                  HP_HASHVAL, pvData, pcbData, 0);
2409         }
2410         else
2411             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2412         break;
2413     case CMSG_ATTR_CERT_COUNT_PARAM:
2414         if (msg->u.signed_data.info)
2415         {
2416             DWORD attrCertCount = 0;
2417
2418             ret = CRYPT_CopyParam(pvData, pcbData,
2419              &attrCertCount, sizeof(DWORD));
2420         }
2421         else
2422             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2423         break;
2424     case CMSG_ATTR_CERT_PARAM:
2425         if (msg->u.signed_data.info)
2426             SetLastError(CRYPT_E_INVALID_INDEX);
2427         else
2428             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2429         break;
2430     case CMSG_CMS_SIGNER_INFO_PARAM:
2431         if (msg->u.signed_data.info)
2432         {
2433             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2434                 SetLastError(CRYPT_E_INVALID_INDEX);
2435             else
2436                 ret = CRYPT_CopyCMSSignerInfo(pvData, pcbData,
2437                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2438         }
2439         else
2440             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2441         break;
2442     default:
2443         FIXME("unimplemented for %d\n", dwParamType);
2444         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2445     }
2446     return ret;
2447 }
2448
2449 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2450  DWORD dwIndex, void *pvData, DWORD *pcbData)
2451 {
2452     CDecodeMsg *msg = hCryptMsg;
2453     BOOL ret = FALSE;
2454
2455     switch (msg->type)
2456     {
2457     case CMSG_HASHED:
2458         ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2459          pcbData);
2460         break;
2461     case CMSG_SIGNED:
2462         ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2463          pcbData);
2464         break;
2465     default:
2466         switch (dwParamType)
2467         {
2468         case CMSG_TYPE_PARAM:
2469             ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
2470              sizeof(msg->type));
2471             break;
2472         default:
2473         {
2474             CRYPT_DATA_BLOB blob;
2475
2476             ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2477              &blob);
2478             if (ret)
2479                 ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
2480                  blob.cbData);
2481             else
2482                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2483         }
2484         }
2485     }
2486     return ret;
2487 }
2488
2489 static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
2490 {
2491     BOOL ret;
2492     CRYPT_DATA_BLOB hashBlob;
2493
2494     ret = ContextPropertyList_FindProperty(msg->properties,
2495      CMSG_HASH_DATA_PARAM, &hashBlob);
2496     if (ret)
2497     {
2498         DWORD computedHashSize = 0;
2499
2500         ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
2501          &computedHashSize);
2502         if (hashBlob.cbData == computedHashSize)
2503         {
2504             LPBYTE computedHash = CryptMemAlloc(computedHashSize);
2505
2506             if (computedHash)
2507             {
2508                 ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
2509                  computedHash, &computedHashSize);
2510                 if (ret)
2511                 {
2512                     if (memcmp(hashBlob.pbData, computedHash, hashBlob.cbData))
2513                     {
2514                         SetLastError(CRYPT_E_HASH_VALUE);
2515                         ret = FALSE;
2516                     }
2517                 }
2518                 CryptMemFree(computedHash);
2519             }
2520             else
2521             {
2522                 SetLastError(ERROR_OUTOFMEMORY);
2523                 ret = FALSE;
2524             }
2525         }
2526         else
2527         {
2528             SetLastError(CRYPT_E_HASH_VALUE);
2529             ret = FALSE;
2530         }
2531     }
2532     return ret;
2533 }
2534
2535 static BOOL CDecodeSignedMsg_VerifySignatureWithKey(CDecodeMsg *msg,
2536  HCRYPTPROV prov, DWORD signerIndex, PCERT_PUBLIC_KEY_INFO keyInfo)
2537 {
2538     HCRYPTKEY key;
2539     BOOL ret;
2540
2541     if (!prov)
2542         prov = msg->crypt_prov;
2543     ret = CryptImportPublicKeyInfo(prov, X509_ASN_ENCODING, keyInfo, &key);
2544     if (ret)
2545     {
2546         HCRYPTHASH hash;
2547         CRYPT_HASH_BLOB reversedHash;
2548
2549         if (msg->u.signed_data.info->rgSignerInfo[signerIndex].AuthAttrs.cAttr)
2550             hash = msg->u.signed_data.signerHandles[signerIndex].authAttrHash;
2551         else
2552             hash = msg->u.signed_data.signerHandles[signerIndex].contentHash;
2553         ret = CRYPT_ConstructBlob(&reversedHash,
2554          &msg->u.signed_data.info->rgSignerInfo[signerIndex].EncryptedHash);
2555         if (ret)
2556         {
2557             CRYPT_ReverseBytes(&reversedHash);
2558             ret = CryptVerifySignatureW(hash, reversedHash.pbData,
2559              reversedHash.cbData, key, NULL, 0);
2560             CryptMemFree(reversedHash.pbData);
2561         }
2562         CryptDestroyKey(key);
2563     }
2564     return ret;
2565 }
2566
2567 static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
2568 {
2569     BOOL ret = FALSE;
2570     DWORD i;
2571
2572     if (!msg->u.signed_data.signerHandles)
2573     {
2574         SetLastError(NTE_BAD_SIGNATURE);
2575         return FALSE;
2576     }
2577     for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
2578     {
2579         PCMSG_CMS_SIGNER_INFO signerInfo =
2580          &msg->u.signed_data.info->rgSignerInfo[i];
2581
2582         if (signerInfo->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2583         {
2584             ret = CertCompareCertificateName(X509_ASN_ENCODING,
2585              &signerInfo->SignerId.u.IssuerSerialNumber.Issuer,
2586              &info->Issuer);
2587             if (ret)
2588             {
2589                 ret = CertCompareIntegerBlob(
2590                  &signerInfo->SignerId.u.IssuerSerialNumber.SerialNumber,
2591                  &info->SerialNumber);
2592                 if (ret)
2593                     break;
2594             }
2595         }
2596         else
2597         {
2598             FIXME("signer %d: unimplemented for key id\n", i);
2599         }
2600     }
2601     if (ret)
2602         ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, 0, i,
2603          &info->SubjectPublicKeyInfo);
2604     else
2605         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2606
2607     return ret;
2608 }
2609
2610 static BOOL CDecodeSignedMsg_VerifySignatureEx(CDecodeMsg *msg,
2611  PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA para)
2612 {
2613     BOOL ret = FALSE;
2614
2615     if (para->cbSize != sizeof(CMSG_CTRL_VERIFY_SIGNATURE_EX_PARA))
2616         SetLastError(ERROR_INVALID_PARAMETER);
2617     else if (para->dwSignerIndex >= msg->u.signed_data.info->cSignerInfo)
2618         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2619     else if (!msg->u.signed_data.signerHandles)
2620         SetLastError(NTE_BAD_SIGNATURE);
2621     else
2622     {
2623         switch (para->dwSignerType)
2624         {
2625         case CMSG_VERIFY_SIGNER_PUBKEY:
2626             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg,
2627              para->hCryptProv, para->dwSignerIndex, para->pvSigner);
2628             break;
2629         case CMSG_VERIFY_SIGNER_CERT:
2630         {
2631             PCCERT_CONTEXT cert = para->pvSigner;
2632
2633             ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, para->hCryptProv,
2634              para->dwSignerIndex, &cert->pCertInfo->SubjectPublicKeyInfo);
2635             break;
2636         }
2637         default:
2638             FIXME("unimplemented for signer type %d\n", para->dwSignerType);
2639             SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2640         }
2641     }
2642     return ret;
2643 }
2644
2645 static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2646  DWORD dwCtrlType, const void *pvCtrlPara)
2647 {
2648     CDecodeMsg *msg = hCryptMsg;
2649     BOOL ret = FALSE;
2650
2651     switch (dwCtrlType)
2652     {
2653     case CMSG_CTRL_VERIFY_SIGNATURE:
2654         switch (msg->type)
2655         {
2656         case CMSG_SIGNED:
2657             ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
2658             break;
2659         default:
2660             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2661         }
2662         break;
2663     case CMSG_CTRL_DECRYPT:
2664         switch (msg->type)
2665         {
2666         default:
2667             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2668         }
2669         break;
2670     case CMSG_CTRL_VERIFY_HASH:
2671         switch (msg->type)
2672         {
2673         case CMSG_HASHED:
2674             ret = CDecodeHashMsg_VerifyHash(msg);
2675             break;
2676         default:
2677             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2678         }
2679         break;
2680     case CMSG_CTRL_VERIFY_SIGNATURE_EX:
2681         switch (msg->type)
2682         {
2683         case CMSG_SIGNED:
2684             ret = CDecodeSignedMsg_VerifySignatureEx(msg,
2685              (PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA)pvCtrlPara);
2686             break;
2687         default:
2688             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2689         }
2690         break;
2691     default:
2692         SetLastError(CRYPT_E_CONTROL_TYPE);
2693     }
2694     return ret;
2695 }
2696
2697 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
2698  DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
2699  PCMSG_STREAM_INFO pStreamInfo)
2700 {
2701     CDecodeMsg *msg;
2702
2703     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
2704      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
2705
2706     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
2707     {
2708         SetLastError(E_INVALIDARG);
2709         return NULL;
2710     }
2711     msg = CryptMemAlloc(sizeof(CDecodeMsg));
2712     if (msg)
2713     {
2714         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
2715          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
2716          CDecodeMsg_Control);
2717         msg->type = dwMsgType;
2718         if (hCryptProv)
2719             msg->crypt_prov = hCryptProv;
2720         else
2721         {
2722             msg->crypt_prov = CRYPT_GetDefaultProvider();
2723             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
2724         }
2725         memset(&msg->u, 0, sizeof(msg->u));
2726         msg->msg_data.cbData = 0;
2727         msg->msg_data.pbData = NULL;
2728         msg->detached_data.cbData = 0;
2729         msg->detached_data.pbData = NULL;
2730         msg->properties = ContextPropertyList_Create();
2731     }
2732     return msg;
2733 }
2734
2735 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
2736 {
2737     TRACE("(%p)\n", hCryptMsg);
2738
2739     if (hCryptMsg)
2740     {
2741         CryptMsgBase *msg = hCryptMsg;
2742
2743         InterlockedIncrement(&msg->ref);
2744     }
2745     return hCryptMsg;
2746 }
2747
2748 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
2749 {
2750     TRACE("(%p)\n", hCryptMsg);
2751
2752     if (hCryptMsg)
2753     {
2754         CryptMsgBase *msg = hCryptMsg;
2755
2756         if (InterlockedDecrement(&msg->ref) == 0)
2757         {
2758             TRACE("freeing %p\n", msg);
2759             if (msg->close)
2760                 msg->close(msg);
2761             CryptMemFree(msg);
2762         }
2763     }
2764     return TRUE;
2765 }
2766
2767 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
2768  DWORD cbData, BOOL fFinal)
2769 {
2770     CryptMsgBase *msg = hCryptMsg;
2771
2772     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
2773
2774     return msg->update(hCryptMsg, pbData, cbData, fFinal);
2775 }
2776
2777 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2778  DWORD dwIndex, void *pvData, DWORD *pcbData)
2779 {
2780     CryptMsgBase *msg = hCryptMsg;
2781
2782     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
2783      pvData, pcbData);
2784     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
2785 }
2786
2787 BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2788  DWORD dwCtrlType, const void *pvCtrlPara)
2789 {
2790     CryptMsgBase *msg = hCryptMsg;
2791
2792     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
2793      pvCtrlPara);
2794     return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
2795 }
2796
2797 static CERT_INFO *CRYPT_GetSignerCertInfoFromMsg(HCRYPTMSG msg,
2798  DWORD dwSignerIndex)
2799 {
2800     CERT_INFO *certInfo = NULL;
2801     DWORD size;
2802
2803     if (CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM, dwSignerIndex, NULL,
2804      &size))
2805     {
2806         certInfo = CryptMemAlloc(size);
2807         if (certInfo)
2808         {
2809             if (!CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM,
2810              dwSignerIndex, certInfo, &size))
2811             {
2812                 CryptMemFree(certInfo);
2813                 certInfo = NULL;
2814             }
2815         }
2816     }
2817     return certInfo;
2818 }
2819
2820 BOOL WINAPI CryptMsgGetAndVerifySigner(HCRYPTMSG hCryptMsg, DWORD cSignerStore,
2821  HCERTSTORE *rghSignerStore, DWORD dwFlags, PCCERT_CONTEXT *ppSigner,
2822  DWORD *pdwSignerIndex)
2823 {
2824     HCERTSTORE store;
2825     DWORD i, signerIndex = 0;
2826     PCCERT_CONTEXT signerCert = NULL;
2827     BOOL ret = FALSE;
2828
2829     TRACE("(%p, %d, %p, %08x, %p, %p)\n", hCryptMsg, cSignerStore,
2830      rghSignerStore, dwFlags, ppSigner, pdwSignerIndex);
2831
2832     /* Clear output parameters */
2833     if (ppSigner)
2834         *ppSigner = NULL;
2835     if (pdwSignerIndex && !(dwFlags & CMSG_USE_SIGNER_INDEX_FLAG))
2836         *pdwSignerIndex = 0;
2837
2838     /* Create store to search for signer certificates */
2839     store = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
2840      CERT_STORE_CREATE_NEW_FLAG, NULL);
2841     if (!(dwFlags & CMSG_TRUSTED_SIGNER_FLAG))
2842     {
2843         HCERTSTORE msgStore = CertOpenStore(CERT_STORE_PROV_MSG, 0, 0, 0,
2844          hCryptMsg);
2845
2846         CertAddStoreToCollection(store, msgStore, 0, 0);
2847         CertCloseStore(msgStore, 0);
2848     }
2849     for (i = 0; i < cSignerStore; i++)
2850         CertAddStoreToCollection(store, rghSignerStore[i], 0, 0);
2851
2852     /* Find signer cert */
2853     if (dwFlags & CMSG_USE_SIGNER_INDEX_FLAG)
2854     {
2855         CERT_INFO *signer = CRYPT_GetSignerCertInfoFromMsg(hCryptMsg,
2856          *pdwSignerIndex);
2857
2858         if (signer)
2859         {
2860             signerIndex = *pdwSignerIndex;
2861             signerCert = CertFindCertificateInStore(store, X509_ASN_ENCODING,
2862              0, CERT_FIND_SUBJECT_CERT, signer, NULL);
2863             CryptMemFree(signer);
2864         }
2865     }
2866     else
2867     {
2868         DWORD count, size = sizeof(count);
2869
2870         if (CryptMsgGetParam(hCryptMsg, CMSG_SIGNER_COUNT_PARAM, 0, &count,
2871          &size))
2872         {
2873             for (i = 0; !signerCert && i < count; i++)
2874             {
2875                 CERT_INFO *signer = CRYPT_GetSignerCertInfoFromMsg(hCryptMsg,
2876                  i);
2877
2878                 if (signer)
2879                 {
2880                     signerCert = CertFindCertificateInStore(store,
2881                      X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, signer,
2882                      NULL);
2883                     if (signerCert)
2884                         signerIndex = i;
2885                     CryptMemFree(signer);
2886                 }
2887             }
2888         }
2889         if (!signerCert)
2890             SetLastError(CRYPT_E_NO_TRUSTED_SIGNER);
2891     }
2892     if (signerCert)
2893     {
2894         if (!(dwFlags & CMSG_SIGNER_ONLY_FLAG))
2895             ret = CryptMsgControl(hCryptMsg, 0, CMSG_CTRL_VERIFY_SIGNATURE,
2896              signerCert->pCertInfo);
2897         else
2898             ret = TRUE;
2899         if (ret)
2900         {
2901             if (ppSigner)
2902                 *ppSigner = CertDuplicateCertificateContext(signerCert);
2903             if (pdwSignerIndex)
2904                 *pdwSignerIndex = signerIndex;
2905         }
2906         CertFreeCertificateContext(signerCert);
2907     }
2908
2909     CertCloseStore(store, 0);
2910     return ret;
2911 }
2912
2913 BOOL WINAPI CryptMsgVerifyCountersignatureEncodedEx(HCRYPTPROV_LEGACY hCryptProv,
2914  DWORD dwEncodingType, PBYTE pbSignerInfo, DWORD cbSignerInfo,
2915  PBYTE pbSignerInfoCountersignature, DWORD cbSignerInfoCountersignature,
2916  DWORD dwSignerType, void *pvSigner, DWORD dwFlags, void *pvReserved)
2917 {
2918     FIXME("(%08lx, %08x, %p, %d, %p, %d, %d, %p, %08x, %p): stub\n", hCryptProv,
2919      dwEncodingType, pbSignerInfo, cbSignerInfo, pbSignerInfoCountersignature,
2920      cbSignerInfoCountersignature, dwSignerType, pvSigner, dwFlags, pvReserved);
2921     return FALSE;
2922 }
2923
2924 BOOL WINAPI CryptMsgEncodeAndSignCTL(DWORD dwMsgEncodingType,
2925  PCTL_INFO pCtlInfo, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
2926  BYTE *pbEncoded, DWORD *pcbEncoded)
2927 {
2928     BOOL ret;
2929     BYTE *pbCtlContent;
2930     DWORD cbCtlContent;
2931
2932     TRACE("(%08x, %p, %p, %08x, %p, %p)\n", dwMsgEncodingType, pCtlInfo,
2933      pSignInfo, dwFlags, pbEncoded, pcbEncoded);
2934
2935     if (dwFlags)
2936     {
2937         FIXME("unimplemented for flags %08x\n", dwFlags);
2938         return FALSE;
2939     }
2940     if ((ret = CryptEncodeObjectEx(dwMsgEncodingType, PKCS_CTL, pCtlInfo,
2941      CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbCtlContent, &cbCtlContent)))
2942     {
2943         ret = CryptMsgSignCTL(dwMsgEncodingType, pbCtlContent, cbCtlContent,
2944          pSignInfo, dwFlags, pbEncoded, pcbEncoded);
2945         LocalFree(pbCtlContent);
2946     }
2947     return ret;
2948 }
2949
2950 BOOL WINAPI CryptMsgSignCTL(DWORD dwMsgEncodingType, BYTE *pbCtlContent,
2951  DWORD cbCtlContent, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
2952  BYTE *pbEncoded, DWORD *pcbEncoded)
2953 {
2954     static char oid_ctl[] = szOID_CTL;
2955     BOOL ret;
2956     HCRYPTMSG msg;
2957
2958     TRACE("(%08x, %p, %d, %p, %08x, %p, %p)\n", dwMsgEncodingType,
2959      pbCtlContent, cbCtlContent, pSignInfo, dwFlags, pbEncoded, pcbEncoded);
2960
2961     if (dwFlags)
2962     {
2963         FIXME("unimplemented for flags %08x\n", dwFlags);
2964         return FALSE;
2965     }
2966     msg = CryptMsgOpenToEncode(dwMsgEncodingType, 0, CMSG_SIGNED, pSignInfo,
2967      oid_ctl, NULL);
2968     if (msg)
2969     {
2970         ret = CryptMsgUpdate(msg, pbCtlContent, cbCtlContent, TRUE);
2971         if (ret)
2972             ret = CryptMsgGetParam(msg, CMSG_CONTENT_PARAM, 0, pbEncoded,
2973              pcbEncoded);
2974         CryptMsgClose(msg);
2975     }
2976     else
2977         ret = FALSE;
2978     return ret;
2979 }