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