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