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