crypt32: Only free allocated handles.
[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 #include <stdarg.h>
19 #include "windef.h"
20 #include "winbase.h"
21 #include "wincrypt.h"
22 #include "snmp.h"
23
24 #include "wine/debug.h"
25 #include "wine/exception.h"
26 #include "crypt32_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
29
30 /* Called when a message's ref count reaches zero.  Free any message-specific
31  * data here.
32  */
33 typedef void (*CryptMsgCloseFunc)(HCRYPTMSG msg);
34
35 typedef BOOL (*CryptMsgGetParamFunc)(HCRYPTMSG hCryptMsg, DWORD dwParamType,
36  DWORD dwIndex, void *pvData, DWORD *pcbData);
37
38 typedef BOOL (*CryptMsgUpdateFunc)(HCRYPTMSG hCryptMsg, const BYTE *pbData,
39  DWORD cbData, BOOL fFinal);
40
41 typedef BOOL (*CryptMsgControlFunc)(HCRYPTMSG hCryptMsg, DWORD dwFlags,
42  DWORD dwCtrlType, const void *pvCtrlPara);
43
44 BOOL CRYPT_DefaultMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
45  DWORD dwCtrlType, const void *pvCtrlPara)
46 {
47     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
48     SetLastError(E_INVALIDARG);
49     return FALSE;
50 }
51
52 typedef enum _CryptMsgState {
53     MsgStateInit,
54     MsgStateUpdated,
55     MsgStateFinalized
56 } CryptMsgState;
57
58 typedef struct _CryptMsgBase
59 {
60     LONG                 ref;
61     DWORD                open_flags;
62     BOOL                 streamed;
63     CMSG_STREAM_INFO     stream_info;
64     CryptMsgState        state;
65     CryptMsgCloseFunc    close;
66     CryptMsgUpdateFunc   update;
67     CryptMsgGetParamFunc get_param;
68     CryptMsgControlFunc  control;
69 } CryptMsgBase;
70
71 static inline void CryptMsgBase_Init(CryptMsgBase *msg, DWORD dwFlags,
72  PCMSG_STREAM_INFO pStreamInfo, CryptMsgCloseFunc close,
73  CryptMsgGetParamFunc get_param, CryptMsgUpdateFunc update,
74  CryptMsgControlFunc control)
75 {
76     msg->ref = 1;
77     msg->open_flags = dwFlags;
78     if (pStreamInfo)
79     {
80         msg->streamed = TRUE;
81         memcpy(&msg->stream_info, pStreamInfo, sizeof(msg->stream_info));
82     }
83     else
84     {
85         msg->streamed = FALSE;
86         memset(&msg->stream_info, 0, sizeof(msg->stream_info));
87     }
88     msg->close = close;
89     msg->get_param = get_param;
90     msg->update = update;
91     msg->control = control;
92     msg->state = MsgStateInit;
93 }
94
95 typedef struct _CDataEncodeMsg
96 {
97     CryptMsgBase base;
98     DWORD        bare_content_len;
99     LPBYTE       bare_content;
100 } CDataEncodeMsg;
101
102 static const BYTE empty_data_content[] = { 0x04,0x00 };
103
104 static void CDataEncodeMsg_Close(HCRYPTMSG hCryptMsg)
105 {
106     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
107
108     if (msg->bare_content != empty_data_content)
109         LocalFree(msg->bare_content);
110 }
111
112 static WINAPI BOOL CRYPT_EncodeContentLength(DWORD dwCertEncodingType,
113  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
114  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
115 {
116     const CDataEncodeMsg *msg = (const CDataEncodeMsg *)pvStructInfo;
117     DWORD lenBytes;
118     BOOL ret = TRUE;
119
120     /* Trick:  report bytes needed based on total message length, even though
121      * the message isn't available yet.  The caller will use the length
122      * reported here to encode its length.
123      */
124     CRYPT_EncodeLen(msg->base.stream_info.cbContent, NULL, &lenBytes);
125     if (!pbEncoded)
126         *pcbEncoded = 1 + lenBytes + msg->base.stream_info.cbContent;
127     else
128     {
129         if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
130          pcbEncoded, 1 + lenBytes)))
131         {
132             if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
133                 pbEncoded = *(BYTE **)pbEncoded;
134             *pbEncoded++ = ASN_OCTETSTRING;
135             CRYPT_EncodeLen(msg->base.stream_info.cbContent, pbEncoded,
136              &lenBytes);
137         }
138     }
139     return ret;
140 }
141
142 static BOOL CRYPT_EncodeDataContentInfoHeader(CDataEncodeMsg *msg,
143  CRYPT_DATA_BLOB *header)
144 {
145     BOOL ret;
146
147     if (msg->base.streamed && msg->base.stream_info.cbContent == 0xffffffff)
148     {
149         FIXME("unimplemented for indefinite-length encoding\n");
150         header->cbData = 0;
151         header->pbData = NULL;
152         ret = TRUE;
153     }
154     else
155     {
156         struct AsnConstructedItem constructed = { 0, msg,
157          CRYPT_EncodeContentLength };
158         struct AsnEncodeSequenceItem items[2] = {
159          { szOID_RSA_data, CRYPT_AsnEncodeOid, 0 },
160          { &constructed,   CRYPT_AsnEncodeConstructed, 0 },
161         };
162
163         ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
164          sizeof(items) / sizeof(items[0]), CRYPT_ENCODE_ALLOC_FLAG, NULL,
165          (LPBYTE)&header->pbData, &header->cbData);
166         if (ret)
167         {
168             /* Trick:  subtract the content length from the reported length,
169              * as the actual content hasn't come yet.
170              */
171             header->cbData -= msg->base.stream_info.cbContent;
172         }
173     }
174     return ret;
175 }
176
177 static BOOL CDataEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
178  DWORD cbData, BOOL fFinal)
179 {
180     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
181     BOOL ret = FALSE;
182
183     if (msg->base.streamed)
184     {
185         __TRY
186         {
187             if (msg->base.state != MsgStateUpdated)
188             {
189                 CRYPT_DATA_BLOB header;
190
191                 ret = CRYPT_EncodeDataContentInfoHeader(msg, &header);
192                 if (ret)
193                 {
194                     ret = msg->base.stream_info.pfnStreamOutput(
195                      msg->base.stream_info.pvArg, header.pbData, header.cbData,
196                      FALSE);
197                     LocalFree(header.pbData);
198                 }
199             }
200             if (!fFinal)
201                 ret = msg->base.stream_info.pfnStreamOutput(
202                  msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
203                  FALSE);
204             else
205             {
206                 if (msg->base.stream_info.cbContent == 0xffffffff)
207                 {
208                     BYTE indefinite_trailer[6] = { 0 };
209
210                     ret = msg->base.stream_info.pfnStreamOutput(
211                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
212                      FALSE);
213                     if (ret)
214                         ret = msg->base.stream_info.pfnStreamOutput(
215                          msg->base.stream_info.pvArg, indefinite_trailer,
216                          sizeof(indefinite_trailer), TRUE);
217                 }
218                 else
219                     ret = msg->base.stream_info.pfnStreamOutput(
220                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData, TRUE);
221             }
222         }
223         __EXCEPT_PAGE_FAULT
224         {
225             SetLastError(STATUS_ACCESS_VIOLATION);
226             ret = FALSE;
227         }
228         __ENDTRY;
229     }
230     else
231     {
232         if (!fFinal)
233         {
234             if (msg->base.open_flags & CMSG_DETACHED_FLAG)
235                 SetLastError(E_INVALIDARG);
236             else
237                 SetLastError(CRYPT_E_MSG_ERROR);
238         }
239         else
240         {
241             if (!cbData)
242                 SetLastError(E_INVALIDARG);
243             else
244             {
245                 CRYPT_DATA_BLOB blob = { cbData, (LPBYTE)pbData };
246
247                 /* non-streamed data messages don't allow non-final updates,
248                  * don't bother checking whether data already exist, they can't.
249                  */
250                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
251                  &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &msg->bare_content,
252                  &msg->bare_content_len);
253             }
254         }
255     }
256     return ret;
257 }
258
259 static BOOL CRYPT_CopyParam(void *pvData, DWORD *pcbData, const void *src,
260  DWORD len)
261 {
262     BOOL ret = TRUE;
263
264     if (!pvData)
265         *pcbData = len;
266     else if (*pcbData < len)
267     {
268         *pcbData = len;
269         SetLastError(ERROR_MORE_DATA);
270         ret = FALSE;
271     }
272     else
273     {
274         *pcbData = len;
275         memcpy(pvData, src, len);
276     }
277     return ret;
278 }
279
280 static BOOL CDataEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
281  DWORD dwIndex, void *pvData, DWORD *pcbData)
282 {
283     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
284     BOOL ret = FALSE;
285
286     switch (dwParamType)
287     {
288     case CMSG_CONTENT_PARAM:
289         if (msg->base.streamed)
290             SetLastError(E_INVALIDARG);
291         else
292         {
293             CRYPT_CONTENT_INFO info;
294             char rsa_data[] = "1.2.840.113549.1.7.1";
295
296             info.pszObjId = rsa_data;
297             info.Content.cbData = msg->bare_content_len;
298             info.Content.pbData = msg->bare_content;
299             ret = CryptEncodeObject(X509_ASN_ENCODING, PKCS_CONTENT_INFO, &info,
300              pvData, pcbData);
301         }
302         break;
303     case CMSG_BARE_CONTENT_PARAM:
304         if (msg->base.streamed)
305             SetLastError(E_INVALIDARG);
306         else
307             ret = CRYPT_CopyParam(pvData, pcbData, msg->bare_content,
308              msg->bare_content_len);
309         break;
310     default:
311         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
312     }
313     return ret;
314 }
315
316 static HCRYPTMSG CDataEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
317  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
318 {
319     CDataEncodeMsg *msg;
320
321     if (pvMsgEncodeInfo)
322     {
323         SetLastError(E_INVALIDARG);
324         return NULL;
325     }
326     msg = CryptMemAlloc(sizeof(CDataEncodeMsg));
327     if (msg)
328     {
329         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
330          CDataEncodeMsg_Close, CDataEncodeMsg_GetParam, CDataEncodeMsg_Update,
331          CRYPT_DefaultMsgControl);
332         msg->bare_content_len = sizeof(empty_data_content);
333         msg->bare_content = (LPBYTE)empty_data_content;
334     }
335     return (HCRYPTMSG)msg;
336 }
337
338 typedef struct _CHashEncodeMsg
339 {
340     CryptMsgBase    base;
341     HCRYPTPROV      prov;
342     HCRYPTHASH      hash;
343     CRYPT_DATA_BLOB data;
344 } CHashEncodeMsg;
345
346 static void CHashEncodeMsg_Close(HCRYPTMSG hCryptMsg)
347 {
348     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
349
350     CryptMemFree(msg->data.pbData);
351     CryptDestroyHash(msg->hash);
352     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
353         CryptReleaseContext(msg->prov, 0);
354 }
355
356 static BOOL CRYPT_EncodePKCSDigestedData(CHashEncodeMsg *msg, void *pvData,
357  DWORD *pcbData)
358 {
359     BOOL ret;
360     ALG_ID algID;
361     DWORD size = sizeof(algID);
362
363     ret = CryptGetHashParam(msg->hash, HP_ALGID, (BYTE *)&algID, &size, 0);
364     if (ret)
365     {
366         CRYPT_DIGESTED_DATA digestedData = { 0 };
367         char oid_rsa_data[] = szOID_RSA_data;
368
369         digestedData.version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
370         digestedData.DigestAlgorithm.pszObjId = (LPSTR)CertAlgIdToOID(algID);
371         /* FIXME: what about digestedData.DigestAlgorithm.Parameters? */
372         /* Quirk:  OID is only encoded messages if an update has happened */
373         if (msg->base.state != MsgStateInit)
374             digestedData.ContentInfo.pszObjId = oid_rsa_data;
375         if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->data.cbData)
376         {
377             ret = CRYPT_AsnEncodeOctets(0, NULL, &msg->data,
378              CRYPT_ENCODE_ALLOC_FLAG, NULL,
379              (LPBYTE)&digestedData.ContentInfo.Content.pbData,
380              &digestedData.ContentInfo.Content.cbData);
381         }
382         if (msg->base.state == MsgStateFinalized)
383         {
384             size = sizeof(DWORD);
385             ret = CryptGetHashParam(msg->hash, HP_HASHSIZE,
386              (LPBYTE)&digestedData.hash.cbData, &size, 0);
387             if (ret)
388             {
389                 digestedData.hash.pbData = CryptMemAlloc(
390                  digestedData.hash.cbData);
391                 ret = CryptGetHashParam(msg->hash, HP_HASHVAL,
392                  digestedData.hash.pbData, &digestedData.hash.cbData, 0);
393             }
394         }
395         if (ret)
396             ret = CRYPT_AsnEncodePKCSDigestedData(&digestedData, pvData,
397              pcbData);
398         CryptMemFree(digestedData.hash.pbData);
399         LocalFree(digestedData.ContentInfo.Content.pbData);
400     }
401     return ret;
402 }
403
404 static BOOL CHashEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
405  DWORD dwIndex, void *pvData, DWORD *pcbData)
406 {
407     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
408     BOOL ret = FALSE;
409
410     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
411      pvData, pcbData);
412
413     switch (dwParamType)
414     {
415     case CMSG_BARE_CONTENT_PARAM:
416         if (msg->base.streamed)
417             SetLastError(E_INVALIDARG);
418         else
419             ret = CRYPT_EncodePKCSDigestedData(msg, pvData, pcbData);
420         break;
421     case CMSG_CONTENT_PARAM:
422     {
423         CRYPT_CONTENT_INFO info;
424
425         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
426          &info.Content.cbData);
427         if (ret)
428         {
429             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
430             if (info.Content.pbData)
431             {
432                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
433                  info.Content.pbData, &info.Content.cbData);
434                 if (ret)
435                 {
436                     char oid_rsa_hashed[] = szOID_RSA_hashedData;
437
438                     info.pszObjId = oid_rsa_hashed;
439                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
440                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
441                 }
442                 CryptMemFree(info.Content.pbData);
443             }
444             else
445                 ret = FALSE;
446         }
447         break;
448     }
449     case CMSG_COMPUTED_HASH_PARAM:
450         ret = CryptGetHashParam(msg->hash, HP_HASHVAL, (BYTE *)pvData, pcbData,
451          0);
452         break;
453     case CMSG_VERSION_PARAM:
454         if (msg->base.state != MsgStateFinalized)
455             SetLastError(CRYPT_E_MSG_ERROR);
456         else
457         {
458             DWORD version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
459
460             /* Since the data are always encoded as octets, the version is
461              * always 0 (see rfc3852, section 7)
462              */
463             ret = CRYPT_CopyParam(pvData, pcbData, &version, sizeof(version));
464         }
465         break;
466     default:
467         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
468     }
469     return ret;
470 }
471
472 static BOOL CHashEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
473  DWORD cbData, BOOL fFinal)
474 {
475     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
476     BOOL ret = FALSE;
477
478     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
479
480     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
481     {
482         /* Doesn't do much, as stream output is never called, and you
483          * can't get the content.
484          */
485         ret = CryptHashData(msg->hash, pbData, cbData, 0);
486     }
487     else
488     {
489         if (!fFinal)
490             SetLastError(CRYPT_E_MSG_ERROR);
491         else
492         {
493             ret = CryptHashData(msg->hash, pbData, cbData, 0);
494             if (ret)
495             {
496                 msg->data.pbData = CryptMemAlloc(cbData);
497                 if (msg->data.pbData)
498                 {
499                     memcpy(msg->data.pbData + msg->data.cbData, pbData, cbData);
500                     msg->data.cbData += cbData;
501                 }
502                 else
503                     ret = FALSE;
504             }
505         }
506     }
507     return ret;
508 }
509
510 static HCRYPTMSG CHashEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
511  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
512 {
513     CHashEncodeMsg *msg;
514     const CMSG_HASHED_ENCODE_INFO *info =
515      (const CMSG_HASHED_ENCODE_INFO *)pvMsgEncodeInfo;
516     HCRYPTPROV prov;
517     ALG_ID algID;
518
519     if (info->cbSize != sizeof(CMSG_HASHED_ENCODE_INFO))
520     {
521         SetLastError(E_INVALIDARG);
522         return NULL;
523     }
524     if (!(algID = CertOIDToAlgId(info->HashAlgorithm.pszObjId)))
525     {
526         SetLastError(CRYPT_E_UNKNOWN_ALGO);
527         return NULL;
528     }
529     if (info->hCryptProv)
530         prov = info->hCryptProv;
531     else
532     {
533         prov = CRYPT_GetDefaultProvider();
534         dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
535     }
536     msg = CryptMemAlloc(sizeof(CHashEncodeMsg));
537     if (msg)
538     {
539         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
540          CHashEncodeMsg_Close, CHashEncodeMsg_GetParam, CHashEncodeMsg_Update,
541          CRYPT_DefaultMsgControl);
542         msg->prov = prov;
543         msg->data.cbData = 0;
544         msg->data.pbData = NULL;
545         if (!CryptCreateHash(prov, algID, 0, 0, &msg->hash))
546         {
547             CryptMsgClose(msg);
548             msg = NULL;
549         }
550     }
551     return (HCRYPTMSG)msg;
552 }
553
554 typedef struct _CMSG_SIGNER_ENCODE_INFO_WITH_CMS
555 {
556     DWORD                      cbSize;
557     PCERT_INFO                 pCertInfo;
558     HCRYPTPROV                 hCryptProv;
559     DWORD                      dwKeySpec;
560     CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
561     void                      *pvHashAuxInfo;
562     DWORD                      cAuthAttr;
563     PCRYPT_ATTRIBUTE           rgAuthAttr;
564     DWORD                      cUnauthAttr;
565     PCRYPT_ATTRIBUTE           rgUnauthAttr;
566     CERT_ID                    SignerId;
567     CRYPT_ALGORITHM_IDENTIFIER HashEncryptionAlgorithm;
568     void                      *pvHashEncryptionAuxInfo;
569 } CMSG_SIGNER_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNER_ENCODE_INFO_WITH_CMS;
570
571 typedef struct _CMSG_SIGNED_ENCODE_INFO_WITH_CMS
572 {
573     DWORD                             cbSize;
574     DWORD                             cSigners;
575     PCMSG_SIGNER_ENCODE_INFO_WITH_CMS rgSigners;
576     DWORD                             cCertEncoded;
577     PCERT_BLOB                        rgCertEncoded;
578     DWORD                             cCrlEncoded;
579     PCRL_BLOB                         rgCrlEncoded;
580     DWORD                             cAttrCertEncoded;
581     PCERT_BLOB                        rgAttrCertEncoded;
582 } CMSG_SIGNED_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNED_ENCODE_INFO_WITH_CMS;
583
584 static BOOL CRYPT_IsValidSigner(CMSG_SIGNER_ENCODE_INFO_WITH_CMS *signer)
585 {
586     if (signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO) &&
587      signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
588     {
589         SetLastError(E_INVALIDARG);
590         return FALSE;
591     }
592     if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
593     {
594         FIXME("CMSG_SIGNER_ENCODE_INFO with CMS fields unsupported\n");
595         return FALSE;
596     }
597     if (!signer->pCertInfo->SerialNumber.cbData)
598     {
599         SetLastError(E_INVALIDARG);
600         return FALSE;
601     }
602     if (!signer->pCertInfo->Issuer.cbData)
603     {
604         SetLastError(E_INVALIDARG);
605         return FALSE;
606     }
607     if (!signer->hCryptProv)
608     {
609         SetLastError(E_INVALIDARG);
610         return FALSE;
611     }
612     if (!CertOIDToAlgId(signer->HashAlgorithm.pszObjId))
613     {
614         SetLastError(CRYPT_E_UNKNOWN_ALGO);
615         return FALSE;
616     }
617     return TRUE;
618 }
619
620 static BOOL CRYPT_ConstructBlob(CRYPT_DATA_BLOB *out, const CRYPT_DATA_BLOB *in)
621 {
622     BOOL ret = TRUE;
623
624     out->cbData = in->cbData;
625     if (out->cbData)
626     {
627         out->pbData = CryptMemAlloc(out->cbData);
628         if (out->pbData)
629             memcpy(out->pbData, in->pbData, out->cbData);
630         else
631             ret = FALSE;
632     }
633     else
634         out->pbData = NULL;
635     return ret;
636 }
637
638 typedef struct _BlobArray
639 {
640     DWORD            cBlobs;
641     PCRYPT_DATA_BLOB blobs;
642 } BlobArray;
643
644 static BOOL CRYPT_ConstructBlobArray(BlobArray *out, const BlobArray *in)
645 {
646     BOOL ret = TRUE;
647
648     out->cBlobs = in->cBlobs;
649     if (out->cBlobs)
650     {
651         out->blobs = CryptMemAlloc(out->cBlobs * sizeof(CRYPT_DATA_BLOB));
652         if (out->blobs)
653         {
654             DWORD i;
655
656             memset(out->blobs, 0, out->cBlobs * sizeof(CRYPT_DATA_BLOB));
657             for (i = 0; ret && i < out->cBlobs; i++)
658                 ret = CRYPT_ConstructBlob(&out->blobs[i], &in->blobs[i]);
659         }
660         else
661             ret = FALSE;
662     }
663     return ret;
664 }
665
666 static void CRYPT_FreeBlobArray(BlobArray *array)
667 {
668     DWORD i;
669
670     for (i = 0; i < array->cBlobs; i++)
671         CryptMemFree(array->blobs[i].pbData);
672     CryptMemFree(array->blobs);
673 }
674
675 static BOOL CRYPT_ConstructAttribute(CRYPT_ATTRIBUTE *out,
676  const CRYPT_ATTRIBUTE *in)
677 {
678     BOOL ret;
679
680     out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
681     if (out->pszObjId)
682     {
683         strcpy(out->pszObjId, in->pszObjId);
684         ret = CRYPT_ConstructBlobArray((BlobArray *)&out->cValue,
685          (const BlobArray *)&in->cValue);
686     }
687     else
688         ret = FALSE;
689     return ret;
690 }
691
692 static BOOL CRYPT_ConstructAttributes(CRYPT_ATTRIBUTES *out,
693  const CRYPT_ATTRIBUTES *in)
694 {
695     BOOL ret = TRUE;
696
697     out->cAttr = in->cAttr;
698     if (out->cAttr)
699     {
700         out->rgAttr = CryptMemAlloc(out->cAttr * sizeof(CRYPT_ATTRIBUTE));
701         if (out->rgAttr)
702         {
703             DWORD i;
704
705             memset(out->rgAttr, 0, out->cAttr * sizeof(CRYPT_ATTRIBUTE));
706             for (i = 0; ret && i < out->cAttr; i++)
707                 ret = CRYPT_ConstructAttribute(&out->rgAttr[i], &in->rgAttr[i]);
708         }
709         else
710             ret = FALSE;
711     }
712     else
713         out->rgAttr = NULL;
714     return ret;
715 }
716
717 /* Constructs a CMSG_SIGNER_INFO from a CMSG_SIGNER_ENCODE_INFO_WITH_CMS. */
718 static BOOL CSignerInfo_Construct(CMSG_SIGNER_INFO *info,
719  CMSG_SIGNER_ENCODE_INFO_WITH_CMS *in)
720 {
721     BOOL ret;
722
723     /* Note: needs to change if CMS fields are supported */
724     info->dwVersion = CMSG_SIGNER_INFO_V1;
725     ret = CRYPT_ConstructBlob(&info->Issuer, &in->pCertInfo->Issuer);
726     if (ret)
727         ret = CRYPT_ConstructBlob(&info->SerialNumber,
728          &in->pCertInfo->SerialNumber);
729     /* Assumption:  algorithm IDs will point to static strings, not
730      * stack-based ones, so copying the pointer values is safe.
731      */
732     info->HashAlgorithm.pszObjId = in->HashAlgorithm.pszObjId;
733     if (ret)
734         ret = CRYPT_ConstructBlob(&info->HashAlgorithm.Parameters,
735          &in->HashAlgorithm.Parameters);
736     memset(&info->HashEncryptionAlgorithm, 0,
737      sizeof(info->HashEncryptionAlgorithm));
738     if (ret)
739         ret = CRYPT_ConstructAttributes(&info->AuthAttrs,
740          (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
741     if (ret)
742         ret = CRYPT_ConstructAttributes(&info->UnauthAttrs,
743          (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
744     return ret;
745 }
746
747 static void CSignerInfo_Free(CMSG_SIGNER_INFO *info)
748 {
749     DWORD i, j;
750
751     CryptMemFree(info->Issuer.pbData);
752     CryptMemFree(info->SerialNumber.pbData);
753     CryptMemFree(info->HashAlgorithm.Parameters.pbData);
754     CryptMemFree(info->EncryptedHash.pbData);
755     for (i = 0; i < info->AuthAttrs.cAttr; i++)
756     {
757         for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
758             CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
759         CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
760         CryptMemFree(info->AuthAttrs.rgAttr[i].pszObjId);
761     }
762     CryptMemFree(info->AuthAttrs.rgAttr);
763     for (i = 0; i < info->UnauthAttrs.cAttr; i++)
764     {
765         for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
766             CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
767         CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
768         CryptMemFree(info->UnauthAttrs.rgAttr[i].pszObjId);
769     }
770     CryptMemFree(info->UnauthAttrs.rgAttr);
771 }
772
773 typedef struct _CSignerHandles
774 {
775     HCRYPTHASH contentHash;
776     HCRYPTHASH authAttrHash;
777     HCRYPTKEY  key;
778 } CSignerHandles;
779
780 typedef struct _CSignedMsgData
781 {
782     CRYPT_SIGNED_INFO *info;
783     CSignerHandles    *signerHandles;
784 } CSignedMsgData;
785
786 /* Constructs the signer handles for the signerIndex'th signer of msg_data.
787  * Assumes signerIndex is a valid idnex, and that msg_data's info has already
788  * been constructed.
789  */
790 static BOOL CSignedMsgData_ConstructSignerHandles(CSignedMsgData *msg_data,
791  DWORD signerIndex, HCRYPTPROV crypt_prov)
792 {
793     ALG_ID algID;
794     BOOL ret;
795
796     algID = CertOIDToAlgId(
797      msg_data->info->rgSignerInfo[signerIndex].HashAlgorithm.pszObjId);
798     ret = CryptCreateHash(crypt_prov, algID, 0, 0,
799      &msg_data->signerHandles->contentHash);
800     if (ret && msg_data->info->rgSignerInfo[signerIndex].AuthAttrs.cAttr > 0)
801         ret = CryptCreateHash(crypt_prov, algID, 0, 0,
802          &msg_data->signerHandles->authAttrHash);
803     return ret;
804 }
805
806 /* Allocates a CSignedMsgData's handles.  Assumes its info has already been
807  * constructed.
808  */
809 static BOOL CSignedMsgData_AllocateHandles(CSignedMsgData *msg_data)
810 {
811     BOOL ret = TRUE;
812
813     if (msg_data->info->cSignerInfo)
814     {
815         msg_data->signerHandles =
816          CryptMemAlloc(msg_data->info->cSignerInfo * sizeof(CSignerHandles));
817         if (msg_data->signerHandles)
818             memset(msg_data->signerHandles, 0,
819              msg_data->info->cSignerInfo * sizeof(CSignerHandles));
820         else
821             ret = FALSE;
822     }
823     else
824         msg_data->signerHandles = NULL;
825     return ret;
826 }
827
828 static void CSignedMsgData_CloseHandles(CSignedMsgData *msg_data)
829 {
830     DWORD i;
831
832     for (i = 0; i < msg_data->info->cSignerInfo; i++)
833     {
834         if (msg_data->signerHandles[i].key)
835             CryptDestroyKey(msg_data->signerHandles[i].key);
836         if (msg_data->signerHandles[i].contentHash)
837             CryptDestroyHash(msg_data->signerHandles[i].contentHash);
838         if (msg_data->signerHandles[i].authAttrHash)
839             CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
840     }
841     CryptMemFree(msg_data->signerHandles);
842 }
843
844 static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
845  const BYTE *pbData, DWORD cbData)
846 {
847     DWORD i;
848     BOOL ret = TRUE;
849
850     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
851         ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
852          cbData, 0);
853     return ret;
854 }
855
856 static BOOL CRYPT_AppendAttribute(CRYPT_ATTRIBUTES *out,
857  const CRYPT_ATTRIBUTE *in)
858 {
859     BOOL ret = FALSE;
860
861     out->rgAttr = CryptMemRealloc(out->rgAttr,
862      (out->cAttr + 1) * sizeof(CRYPT_ATTRIBUTE));
863     if (out->rgAttr)
864     {
865         ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
866         if (ret)
867             out->cAttr++;
868     }
869     return ret;
870 }
871
872 static BOOL CSignedMsgData_AppendMessageDigestAttribute(
873  CSignedMsgData *msg_data, DWORD signerIndex)
874 {
875     BOOL ret;
876     DWORD size;
877     CRYPT_HASH_BLOB hash = { 0, NULL }, encodedHash = { 0, NULL };
878     char messageDigest[] = szOID_RSA_messageDigest;
879     CRYPT_ATTRIBUTE messageDigestAttr = { messageDigest, 1, &encodedHash };
880
881     size = sizeof(DWORD);
882     ret = CryptGetHashParam(
883      msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
884      (LPBYTE)&hash.cbData, &size, 0);
885     if (ret)
886     {
887         hash.pbData = CryptMemAlloc(hash.cbData);
888         ret = CryptGetHashParam(
889          msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
890          hash.pbData, &hash.cbData, 0);
891         if (ret)
892         {
893             ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
894              NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
895             if (ret)
896             {
897                 ret = CRYPT_AppendAttribute(
898                  &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
899                  &messageDigestAttr);
900                 LocalFree(encodedHash.pbData);
901             }
902         }
903         CryptMemFree(hash.pbData);
904     }
905     return ret;
906 }
907
908 typedef enum {
909     Sign,
910     Verify
911 } SignOrVerify;
912
913 static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
914  CSignedMsgData *msg_data, SignOrVerify flag)
915 {
916     DWORD i;
917     BOOL ret = TRUE;
918
919     TRACE("(%p)\n", msg_data);
920
921     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
922     {
923         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
924         {
925             if (flag == Sign)
926             {
927                 BYTE oid_rsa_data_encoded[] = { 0x06,0x09,0x2a,0x86,0x48,0x86,
928                  0xf7,0x0d,0x01,0x07,0x01 };
929                 CRYPT_DATA_BLOB content = { sizeof(oid_rsa_data_encoded),
930                  oid_rsa_data_encoded };
931                 char contentType[] = szOID_RSA_contentType;
932                 CRYPT_ATTRIBUTE contentTypeAttr = { contentType, 1, &content };
933
934                 /* FIXME: does this depend on inner OID? */
935                 ret = CRYPT_AppendAttribute(
936                  &msg_data->info->rgSignerInfo[i].AuthAttrs, &contentTypeAttr);
937                 if (ret)
938                     ret = CSignedMsgData_AppendMessageDigestAttribute(msg_data,
939                      i);
940             }
941             if (ret)
942             {
943                 LPBYTE encodedAttrs;
944                 DWORD size;
945
946                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
947                  &msg_data->info->rgSignerInfo[i].AuthAttrs,
948                  CRYPT_ENCODE_ALLOC_FLAG, NULL, (LPBYTE)&encodedAttrs, &size);
949                 if (ret)
950                 {
951                     ret = CryptHashData(
952                      msg_data->signerHandles[i].authAttrHash, encodedAttrs,
953                      size, 0);
954                     LocalFree(encodedAttrs);
955                 }
956             }
957         }
958     }
959     TRACE("returning %d\n", ret);
960     return ret;
961 }
962
963 static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
964 {
965     DWORD i;
966     BYTE tmp;
967
968     for (i = 0; i < hash->cbData / 2; i++)
969     {
970         tmp = hash->pbData[hash->cbData - i - 1];
971         hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
972         hash->pbData[i] = tmp;
973     }
974 }
975
976 static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
977 {
978     DWORD i;
979     BOOL ret = TRUE;
980
981     TRACE("(%p)\n", msg_data);
982
983     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
984     {
985         HCRYPTHASH hash;
986
987         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
988             hash = msg_data->signerHandles[i].authAttrHash;
989         else
990             hash = msg_data->signerHandles[i].contentHash;
991         ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
992          &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
993         if (ret)
994         {
995             msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
996              CryptMemAlloc(
997              msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
998             if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
999             {
1000                 ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
1001                  msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
1002                  &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1003                 if (ret)
1004                     CRYPT_ReverseBytes(
1005                      &msg_data->info->rgSignerInfo[i].EncryptedHash);
1006             }
1007             else
1008                 ret = FALSE;
1009         }
1010     }
1011     return ret;
1012 }
1013
1014 static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1015  const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1016 {
1017     BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);
1018
1019     if (ret && fFinal)
1020     {
1021         ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
1022         if (ret && flag == Sign)
1023             ret = CSignedMsgData_Sign(msg_data);
1024     }
1025     return ret;
1026 }
1027
1028 typedef struct _CSignedEncodeMsg
1029 {
1030     CryptMsgBase    base;
1031     CRYPT_DATA_BLOB data;
1032     CSignedMsgData  msg_data;
1033 } CSignedEncodeMsg;
1034
1035 static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
1036 {
1037     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1038     DWORD i;
1039
1040     CryptMemFree(msg->data.pbData);
1041     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCertEncoded);
1042     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCrlEncoded);
1043     for (i = 0; i < msg->msg_data.info->cSignerInfo; i++)
1044         CSignerInfo_Free(&msg->msg_data.info->rgSignerInfo[i]);
1045     CSignedMsgData_CloseHandles(&msg->msg_data);
1046     CryptMemFree(msg->msg_data.info->rgSignerInfo);
1047     CryptMemFree(msg->msg_data.info);
1048 }
1049
1050 static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1051  DWORD dwIndex, void *pvData, DWORD *pcbData)
1052 {
1053     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1054     BOOL ret = FALSE;
1055
1056     switch (dwParamType)
1057     {
1058     case CMSG_CONTENT_PARAM:
1059     {
1060         CRYPT_CONTENT_INFO info;
1061
1062         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
1063          &info.Content.cbData);
1064         if (ret)
1065         {
1066             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
1067             if (info.Content.pbData)
1068             {
1069                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
1070                  info.Content.pbData, &info.Content.cbData);
1071                 if (ret)
1072                 {
1073                     char oid_rsa_signed[] = szOID_RSA_signedData;
1074
1075                     info.pszObjId = oid_rsa_signed;
1076                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
1077                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
1078                 }
1079                 CryptMemFree(info.Content.pbData);
1080             }
1081             else
1082                 ret = FALSE;
1083         }
1084         break;
1085     }
1086     case CMSG_BARE_CONTENT_PARAM:
1087     {
1088         CRYPT_SIGNED_INFO info;
1089         char oid_rsa_data[] = szOID_RSA_data;
1090
1091         memcpy(&info, msg->msg_data.info, sizeof(info));
1092         /* Quirk:  OID is only encoded messages if an update has happened */
1093         if (msg->base.state != MsgStateInit)
1094             info.content.pszObjId = oid_rsa_data;
1095         else
1096             info.content.pszObjId = NULL;
1097         if (msg->data.cbData)
1098         {
1099             CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
1100
1101             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1102              &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1103              &info.content.Content.pbData, &info.content.Content.cbData);
1104         }
1105         else
1106         {
1107             info.content.Content.cbData = 0;
1108             info.content.Content.pbData = NULL;
1109             ret = TRUE;
1110         }
1111         if (ret)
1112         {
1113             ret = CRYPT_AsnEncodePKCSSignedInfo(&info, pvData, pcbData);
1114             LocalFree(info.content.Content.pbData);
1115         }
1116         break;
1117     }
1118     case CMSG_COMPUTED_HASH_PARAM:
1119         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1120             SetLastError(CRYPT_E_INVALID_INDEX);
1121         else
1122             ret = CryptGetHashParam(
1123              msg->msg_data.signerHandles[dwIndex].contentHash, HP_HASHVAL,
1124              pvData, pcbData, 0);
1125         break;
1126     case CMSG_ENCODED_SIGNER:
1127         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1128             SetLastError(CRYPT_E_INVALID_INDEX);
1129         else
1130             ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1131              PKCS7_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1132              NULL, pvData, pcbData);
1133         break;
1134     case CMSG_VERSION_PARAM:
1135         ret = CRYPT_CopyParam(pvData, pcbData, &msg->msg_data.info->version,
1136          sizeof(msg->msg_data.info->version));
1137         break;
1138     default:
1139         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1140     }
1141     return ret;
1142 }
1143
1144 static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1145  DWORD cbData, BOOL fFinal)
1146 {
1147     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1148     BOOL ret = FALSE;
1149
1150     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1151     {
1152         ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
1153          Sign);
1154         if (msg->base.streamed)
1155             FIXME("streamed partial stub\n");
1156     }
1157     else
1158     {
1159         if (!fFinal)
1160             SetLastError(CRYPT_E_MSG_ERROR);
1161         else
1162         {
1163             if (cbData)
1164             {
1165                 msg->data.pbData = CryptMemAlloc(cbData);
1166                 if (msg->data.pbData)
1167                 {
1168                     memcpy(msg->data.pbData, pbData, cbData);
1169                     msg->data.cbData = cbData;
1170                     ret = TRUE;
1171                 }
1172             }
1173             else
1174                 ret = TRUE;
1175             if (ret)
1176                 ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1177                  fFinal, Sign);
1178         }
1179     }
1180     return ret;
1181 }
1182
1183 static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1184  const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1185  PCMSG_STREAM_INFO pStreamInfo)
1186 {
1187     const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info =
1188      (const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *)pvMsgEncodeInfo;
1189     DWORD i;
1190     CSignedEncodeMsg *msg;
1191
1192     if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
1193      info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1194     {
1195         SetLastError(E_INVALIDARG);
1196         return NULL;
1197     }
1198     if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1199     {
1200         FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
1201         return NULL;
1202     }
1203     for (i = 0; i < info->cSigners; i++)
1204         if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
1205             return NULL;
1206     msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
1207     if (msg)
1208     {
1209         BOOL ret = TRUE;
1210
1211         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1212          CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1213          CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1214         msg->data.cbData = 0;
1215         msg->data.pbData = NULL;
1216         msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
1217         if (msg->msg_data.info)
1218         {
1219             memset(msg->msg_data.info, 0, sizeof(CRYPT_SIGNED_INFO));
1220             msg->msg_data.info->version = CMSG_SIGNED_DATA_V1;
1221         }
1222         else
1223             ret = FALSE;
1224         if (ret && info->cSigners)
1225         {
1226             msg->msg_data.info->rgSignerInfo =
1227              CryptMemAlloc(info->cSigners * sizeof(CMSG_SIGNER_INFO));
1228             if (msg->msg_data.info->rgSignerInfo)
1229             {
1230                 msg->msg_data.info->cSignerInfo = info->cSigners;
1231                 memset(msg->msg_data.info->rgSignerInfo, 0,
1232                  msg->msg_data.info->cSignerInfo * sizeof(CMSG_SIGNER_INFO));
1233                 ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
1234                 for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1235                 {
1236                     ret = CSignerInfo_Construct(
1237                      &msg->msg_data.info->rgSignerInfo[i],
1238                      &info->rgSigners[i]);
1239                     if (ret)
1240                     {
1241                         ret = CSignedMsgData_ConstructSignerHandles(
1242                          &msg->msg_data, i, info->rgSigners[i].hCryptProv);
1243                         if (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1244                             CryptReleaseContext(info->rgSigners[i].hCryptProv,
1245                              0);
1246                     }
1247                 }
1248             }
1249             else
1250                 ret = FALSE;
1251         }
1252         if (ret)
1253             ret = CRYPT_ConstructBlobArray(
1254              (BlobArray *)&msg->msg_data.info->cCertEncoded,
1255              (const BlobArray *)&info->cCertEncoded);
1256         if (ret)
1257             ret = CRYPT_ConstructBlobArray(
1258              (BlobArray *)&msg->msg_data.info->cCrlEncoded,
1259              (const BlobArray *)&info->cCrlEncoded);
1260         if (!ret)
1261         {
1262             CSignedEncodeMsg_Close(msg);
1263             msg = NULL;
1264         }
1265     }
1266     return msg;
1267 }
1268
1269 static inline const char *MSG_TYPE_STR(DWORD type)
1270 {
1271     switch (type)
1272     {
1273 #define _x(x) case (x): return #x
1274         _x(CMSG_DATA);
1275         _x(CMSG_SIGNED);
1276         _x(CMSG_ENVELOPED);
1277         _x(CMSG_SIGNED_AND_ENVELOPED);
1278         _x(CMSG_HASHED);
1279         _x(CMSG_ENCRYPTED);
1280 #undef _x
1281         default:
1282             return wine_dbg_sprintf("unknown (%d)", type);
1283     }
1284 }
1285
1286 HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
1287  DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1288  PCMSG_STREAM_INFO pStreamInfo)
1289 {
1290     HCRYPTMSG msg = NULL;
1291
1292     TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
1293      dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
1294
1295     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
1296     {
1297         SetLastError(E_INVALIDARG);
1298         return NULL;
1299     }
1300     switch (dwMsgType)
1301     {
1302     case CMSG_DATA:
1303         msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1304          pszInnerContentObjID, pStreamInfo);
1305         break;
1306     case CMSG_HASHED:
1307         msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1308          pszInnerContentObjID, pStreamInfo);
1309         break;
1310     case CMSG_SIGNED:
1311         msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1312          pszInnerContentObjID, pStreamInfo);
1313         break;
1314     case CMSG_ENVELOPED:
1315         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(dwMsgType));
1316         break;
1317     case CMSG_SIGNED_AND_ENVELOPED:
1318     case CMSG_ENCRYPTED:
1319         /* defined but invalid, fall through */
1320     default:
1321         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1322     }
1323     return msg;
1324 }
1325
1326 typedef struct _CDecodeMsg
1327 {
1328     CryptMsgBase           base;
1329     DWORD                  type;
1330     HCRYPTPROV             crypt_prov;
1331     union {
1332         HCRYPTHASH     hash;
1333         CSignedMsgData signed_data;
1334     } u;
1335     CRYPT_DATA_BLOB        msg_data;
1336     PCONTEXT_PROPERTY_LIST properties;
1337 } CDecodeMsg;
1338
1339 static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
1340 {
1341     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1342
1343     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1344         CryptReleaseContext(msg->crypt_prov, 0);
1345     switch (msg->type)
1346     {
1347     case CMSG_HASHED:
1348         if (msg->u.hash)
1349             CryptDestroyHash(msg->u.hash);
1350         break;
1351     case CMSG_SIGNED:
1352         if (msg->u.signed_data.info)
1353         {
1354             LocalFree(msg->u.signed_data.info);
1355             CSignedMsgData_CloseHandles(&msg->u.signed_data);
1356         }
1357         break;
1358     }
1359     CryptMemFree(msg->msg_data.pbData);
1360     ContextPropertyList_Free(msg->properties);
1361 }
1362
1363 static BOOL CDecodeMsg_CopyData(CDecodeMsg *msg, const BYTE *pbData,
1364  DWORD cbData)
1365 {
1366     BOOL ret = TRUE;
1367
1368     if (cbData)
1369     {
1370         if (msg->msg_data.cbData)
1371             msg->msg_data.pbData = CryptMemRealloc(msg->msg_data.pbData,
1372              msg->msg_data.cbData + cbData);
1373         else
1374             msg->msg_data.pbData = CryptMemAlloc(cbData);
1375         if (msg->msg_data.pbData)
1376         {
1377             memcpy(msg->msg_data.pbData + msg->msg_data.cbData, pbData, cbData);
1378             msg->msg_data.cbData += cbData;
1379         }
1380         else
1381             ret = FALSE;
1382     }
1383     return ret;
1384 }
1385
1386 static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
1387 {
1388     BOOL ret;
1389     CRYPT_DATA_BLOB *data;
1390     DWORD size;
1391
1392     ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1393      blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&data,
1394      &size);
1395     if (ret)
1396     {
1397         ret = ContextPropertyList_SetProperty(msg->properties,
1398          CMSG_CONTENT_PARAM, data->pbData, data->cbData);
1399         LocalFree(data);
1400     }
1401     return ret;
1402 }
1403
1404 static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
1405  const CRYPT_ALGORITHM_IDENTIFIER *id)
1406 {
1407     static const BYTE nullParams[] = { ASN_NULL, 0 };
1408     CRYPT_ALGORITHM_IDENTIFIER *copy;
1409     DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);
1410
1411     /* Linearize algorithm id */
1412     len += strlen(id->pszObjId) + 1;
1413     len += id->Parameters.cbData;
1414     copy = CryptMemAlloc(len);
1415     if (copy)
1416     {
1417         copy->pszObjId =
1418          (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1419         strcpy(copy->pszObjId, id->pszObjId);
1420         copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
1421          + 1;
1422         /* Trick:  omit NULL parameters */
1423         if (id->Parameters.cbData == sizeof(nullParams) &&
1424          !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
1425         {
1426             copy->Parameters.cbData = 0;
1427             len -= sizeof(nullParams);
1428         }
1429         else
1430             copy->Parameters.cbData = id->Parameters.cbData;
1431         if (copy->Parameters.cbData)
1432             memcpy(copy->Parameters.pbData, id->Parameters.pbData,
1433              id->Parameters.cbData);
1434         ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
1435          len);
1436         CryptMemFree(copy);
1437     }
1438 }
1439
1440 static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
1441 {
1442     id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1443     id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
1444 }
1445
1446 static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
1447  CRYPT_DER_BLOB *blob)
1448 {
1449     BOOL ret;
1450     CRYPT_DIGESTED_DATA *digestedData;
1451     DWORD size;
1452
1453     ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
1454      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
1455      &size);
1456     if (ret)
1457     {
1458         ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
1459          (const BYTE *)&digestedData->version, sizeof(digestedData->version));
1460         CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
1461          &digestedData->DigestAlgorithm);
1462         ContextPropertyList_SetProperty(msg->properties,
1463          CMSG_INNER_CONTENT_TYPE_PARAM,
1464          (const BYTE *)digestedData->ContentInfo.pszObjId,
1465          digestedData->ContentInfo.pszObjId ?
1466          strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
1467         if (digestedData->ContentInfo.Content.cbData)
1468             CDecodeMsg_DecodeDataContent(msg,
1469              &digestedData->ContentInfo.Content);
1470         else
1471             ContextPropertyList_SetProperty(msg->properties,
1472              CMSG_CONTENT_PARAM, NULL, 0);
1473         ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
1474          digestedData->hash.pbData, digestedData->hash.cbData);
1475         LocalFree(digestedData);
1476     }
1477     return ret;
1478 }
1479
1480 static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
1481  CRYPT_DER_BLOB *blob)
1482 {
1483     BOOL ret;
1484     CRYPT_SIGNED_INFO *signedInfo;
1485     DWORD size;
1486
1487     ret = CRYPT_AsnDecodePKCSSignedInfo(blob->pbData, blob->cbData,
1488      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
1489      &size);
1490     if (ret)
1491     {
1492         DWORD i;
1493
1494         msg->u.signed_data.info = signedInfo;
1495         ret = CSignedMsgData_AllocateHandles(&msg->u.signed_data);
1496         for (i = 0; ret && i < msg->u.signed_data.info->cSignerInfo; i++)
1497             ret = CSignedMsgData_ConstructSignerHandles(&msg->u.signed_data, i,
1498              msg->crypt_prov);
1499         if (ret)
1500         {
1501             /* Now that we have all the content, update the hash handles with
1502              * it.  Have to decode it if the type is szOID_RSA_data.
1503              */
1504             if (msg->u.signed_data.info->content.Content.cbData)
1505             {
1506                 if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1507                  szOID_RSA_data))
1508                 {
1509                     CRYPT_DATA_BLOB *blob;
1510
1511                     ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
1512                      X509_OCTET_STRING,
1513                      msg->u.signed_data.info->content.Content.pbData,
1514                      msg->u.signed_data.info->content.Content.cbData,
1515                      CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1516                     if (ret)
1517                     {
1518                         ret = CSignedMsgData_Update(&msg->u.signed_data,
1519                          blob->pbData, blob->cbData, TRUE, Verify);
1520                         LocalFree(blob);
1521                     }
1522                 }
1523                 else
1524                     ret = CSignedMsgData_Update(&msg->u.signed_data,
1525                      msg->u.signed_data.info->content.Content.pbData,
1526                      msg->u.signed_data.info->content.Content.cbData, TRUE,
1527                      Verify);
1528             }
1529         }
1530     }
1531     return ret;
1532 }
1533 /* Decodes the content in blob as the type given, and updates the value
1534  * (type, parameters, etc.) of msg based on what blob contains.
1535  * It doesn't just use msg's type, to allow a recursive call from an implicitly
1536  * typed message once the outer content info has been decoded.
1537  */
1538 static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob,
1539  DWORD type)
1540 {
1541     BOOL ret;
1542
1543     switch (type)
1544     {
1545     case CMSG_DATA:
1546         if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
1547             msg->type = CMSG_DATA;
1548         break;
1549     case CMSG_HASHED:
1550         if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
1551             msg->type = CMSG_HASHED;
1552         break;
1553     case CMSG_ENVELOPED:
1554         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(type));
1555         ret = TRUE;
1556         break;
1557     case CMSG_SIGNED:
1558         if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
1559             msg->type = CMSG_SIGNED;
1560         break;
1561     default:
1562     {
1563         CRYPT_CONTENT_INFO *info;
1564         DWORD size;
1565
1566         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
1567          msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
1568          NULL, (LPBYTE)&info, &size);
1569         if (ret)
1570         {
1571             if (!strcmp(info->pszObjId, szOID_RSA_data))
1572                 ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
1573             else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
1574                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1575                  CMSG_HASHED);
1576             else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
1577                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1578                  CMSG_ENVELOPED);
1579             else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
1580                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1581                  CMSG_SIGNED);
1582             else
1583             {
1584                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1585                 ret = FALSE;
1586             }
1587             LocalFree(info);
1588         }
1589     }
1590     }
1591     return ret;
1592 }
1593
1594 static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1595  DWORD cbData, BOOL fFinal)
1596 {
1597     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1598     BOOL ret = FALSE;
1599
1600     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
1601
1602     if (msg->base.streamed)
1603     {
1604         ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1605         FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
1606          cbData, fFinal);
1607     }
1608     else
1609     {
1610         if (!fFinal)
1611             SetLastError(CRYPT_E_MSG_ERROR);
1612         else
1613         {
1614             ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1615             if (ret)
1616                 ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
1617
1618         }
1619     }
1620     return ret;
1621 }
1622
1623 static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1624  DWORD dwIndex, void *pvData, DWORD *pcbData)
1625 {
1626     BOOL ret = FALSE;
1627
1628     switch (dwParamType)
1629     {
1630     case CMSG_TYPE_PARAM:
1631         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1632         break;
1633     case CMSG_HASH_ALGORITHM_PARAM:
1634     {
1635         CRYPT_DATA_BLOB blob;
1636
1637         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1638          &blob);
1639         if (ret)
1640         {
1641             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1642             if (ret && pvData)
1643                 CRYPT_FixUpAlgorithmID((CRYPT_ALGORITHM_IDENTIFIER *)pvData);
1644         }
1645         else
1646             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1647         break;
1648     }
1649     case CMSG_COMPUTED_HASH_PARAM:
1650         if (!msg->u.hash)
1651         {
1652             CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
1653             DWORD size = 0;
1654             ALG_ID algID = 0;
1655
1656             CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
1657             hashAlgoID = CryptMemAlloc(size);
1658             ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0,
1659              hashAlgoID, &size);
1660             if (ret)
1661                 algID = CertOIDToAlgId(hashAlgoID->pszObjId);
1662             ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->u.hash);
1663             if (ret)
1664             {
1665                 CRYPT_DATA_BLOB content;
1666
1667                 ret = ContextPropertyList_FindProperty(msg->properties,
1668                  CMSG_CONTENT_PARAM, &content);
1669                 if (ret)
1670                     ret = CryptHashData(msg->u.hash, content.pbData,
1671                      content.cbData, 0);
1672             }
1673             CryptMemFree(hashAlgoID);
1674         }
1675         else
1676             ret = TRUE;
1677         if (ret)
1678             ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData,
1679              0);
1680         break;
1681     default:
1682     {
1683         CRYPT_DATA_BLOB blob;
1684
1685         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1686          &blob);
1687         if (ret)
1688             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1689         else
1690             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1691     }
1692     }
1693     return ret;
1694 }
1695
1696 /* nextData is an in/out parameter - on input it's the memory location in
1697  * which a copy of in's data should be made, and on output it's the memory
1698  * location immediately after out's copy of in's data.
1699  */
1700 static inline void CRYPT_CopyBlob(CRYPT_DATA_BLOB *out,
1701  const CRYPT_DATA_BLOB *in, LPBYTE *nextData)
1702 {
1703     out->cbData = in->cbData;
1704     if (in->cbData)
1705     {
1706         out->pbData = *nextData;
1707         memcpy(out->pbData, in->pbData, in->cbData);
1708         *nextData += in->cbData;
1709     }
1710 }
1711
1712 static inline void CRYPT_CopyAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
1713  const CRYPT_ALGORITHM_IDENTIFIER *in, LPBYTE *nextData)
1714 {
1715     if (in->pszObjId)
1716     {
1717         out->pszObjId = (LPSTR)*nextData;
1718         strcpy(out->pszObjId, in->pszObjId);
1719         *nextData += strlen(out->pszObjId) + 1;
1720     }
1721     CRYPT_CopyBlob(&out->Parameters, &in->Parameters, nextData);
1722 }
1723
1724 static inline void CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
1725  const CRYPT_ATTRIBUTES *in, LPBYTE *nextData)
1726 {
1727     out->cAttr = in->cAttr;
1728     if (in->cAttr)
1729     {
1730         DWORD i;
1731
1732         if ((*nextData - (LPBYTE)0) % sizeof(DWORD))
1733             *nextData += (*nextData - (LPBYTE)0) % sizeof(DWORD);
1734         out->rgAttr = (CRYPT_ATTRIBUTE *)*nextData;
1735         *nextData += in->cAttr * sizeof(CRYPT_ATTRIBUTE);
1736         for (i = 0; i < in->cAttr; i++)
1737         {
1738             if (in->rgAttr[i].pszObjId)
1739             {
1740                 out->rgAttr[i].pszObjId = (LPSTR)*nextData;
1741                 strcpy(out->rgAttr[i].pszObjId, in->rgAttr[i].pszObjId);
1742                 *nextData += strlen(in->rgAttr[i].pszObjId) + 1;
1743             }
1744             if (in->rgAttr[i].cValue)
1745             {
1746                 DWORD j;
1747
1748                 out->rgAttr[i].cValue = in->rgAttr[i].cValue;
1749                 if ((*nextData - (LPBYTE)0) % sizeof(DWORD))
1750                     *nextData += (*nextData - (LPBYTE)0) % sizeof(DWORD);
1751                 out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
1752                 for (j = 0; j < in->rgAttr[i].cValue; j++)
1753                     CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
1754                      &in->rgAttr[i].rgValue[j], nextData);
1755             }
1756         }
1757     }
1758 }
1759
1760 static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
1761 {
1762     DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;
1763
1764     for (i = 0; i < attr->cAttr; i++)
1765     {
1766         if (attr->rgAttr[i].pszObjId)
1767             size += strlen(attr->rgAttr[i].pszObjId) + 1;
1768         /* align pointer */
1769         if (size % sizeof(DWORD))
1770             size += size % sizeof(DWORD);
1771         size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
1772         for (j = 0; j < attr->rgAttr[i].cValue; j++)
1773             size += attr->rgAttr[i].rgValue[j].cbData;
1774     }
1775     return size;
1776 }
1777
1778 static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
1779  const CMSG_SIGNER_INFO *in)
1780 {
1781     DWORD size = sizeof(CMSG_SIGNER_INFO);
1782     BOOL ret;
1783
1784     size += in->Issuer.cbData;
1785     size += in->SerialNumber.cbData;
1786     if (in->HashAlgorithm.pszObjId)
1787         size += strlen(in->HashAlgorithm.pszObjId) + 1;
1788     size += in->HashAlgorithm.Parameters.cbData;
1789     if (in->HashEncryptionAlgorithm.pszObjId)
1790         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
1791     size += in->HashEncryptionAlgorithm.Parameters.cbData;
1792     size += in->EncryptedHash.cbData;
1793     /* align pointer */
1794     if (size % sizeof(DWORD))
1795         size += size % sizeof(DWORD);
1796     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
1797     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
1798     if (!pvData)
1799     {
1800         *pcbData = size;
1801         ret = TRUE;
1802     }
1803     else if (*pcbData < size)
1804     {
1805         *pcbData = size;
1806         SetLastError(ERROR_MORE_DATA);
1807         ret = FALSE;
1808     }
1809     else
1810     {
1811         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
1812         CMSG_SIGNER_INFO *out = (CMSG_SIGNER_INFO *)pvData;
1813
1814         out->dwVersion = in->dwVersion;
1815         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1816         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1817         CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
1818          &nextData);
1819         CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
1820          &in->HashEncryptionAlgorithm, &nextData);
1821         CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
1822         /* align pointer */
1823         if ((nextData - (LPBYTE)0) % sizeof(DWORD))
1824             nextData += (nextData - (LPBYTE)0) % sizeof(DWORD);
1825         CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
1826         CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
1827         ret = TRUE;
1828     }
1829     return ret;
1830 }
1831
1832 static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
1833  const CMSG_SIGNER_INFO *in)
1834 {
1835     DWORD size = sizeof(CERT_INFO);
1836     BOOL ret;
1837
1838     size += in->Issuer.cbData;
1839     size += in->SerialNumber.cbData;
1840     if (!pvData)
1841     {
1842         *pcbData = size;
1843         ret = TRUE;
1844     }
1845     else if (*pcbData < size)
1846     {
1847         *pcbData = size;
1848         SetLastError(ERROR_MORE_DATA);
1849         ret = FALSE;
1850     }
1851     else
1852     {
1853         LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
1854         CERT_INFO *out = (CERT_INFO *)pvData;
1855
1856         memset(out, 0, sizeof(CERT_INFO));
1857         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1858         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1859         ret = TRUE;
1860     }
1861     return ret;
1862 }
1863
1864 static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1865  DWORD dwIndex, void *pvData, DWORD *pcbData)
1866 {
1867     BOOL ret = FALSE;
1868
1869     switch (dwParamType)
1870     {
1871     case CMSG_TYPE_PARAM:
1872         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1873         break;
1874     case CMSG_CONTENT_PARAM:
1875         if (msg->u.signed_data.info)
1876         {
1877             if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1878              szOID_RSA_data))
1879             {
1880                 CRYPT_DATA_BLOB *blob;
1881                 DWORD size;
1882
1883                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1884                  msg->u.signed_data.info->content.Content.pbData,
1885                  msg->u.signed_data.info->content.Content.cbData,
1886                  CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1887                 if (ret)
1888                 {
1889                     ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
1890                      blob->cbData);
1891                     LocalFree(blob);
1892                 }
1893             }
1894             else
1895                 ret = CRYPT_CopyParam(pvData, pcbData,
1896                  msg->u.signed_data.info->content.Content.pbData,
1897                  msg->u.signed_data.info->content.Content.cbData);
1898         }
1899         else
1900             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1901         break;
1902     case CMSG_INNER_CONTENT_TYPE_PARAM:
1903         if (msg->u.signed_data.info)
1904             ret = CRYPT_CopyParam(pvData, pcbData,
1905              msg->u.signed_data.info->content.pszObjId,
1906              strlen(msg->u.signed_data.info->content.pszObjId) + 1);
1907         else
1908             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1909         break;
1910     case CMSG_SIGNER_COUNT_PARAM:
1911         if (msg->u.signed_data.info)
1912             ret = CRYPT_CopyParam(pvData, pcbData,
1913              &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
1914         else
1915             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1916         break;
1917     case CMSG_SIGNER_INFO_PARAM:
1918         if (msg->u.signed_data.info)
1919         {
1920             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1921                 SetLastError(CRYPT_E_INVALID_INDEX);
1922             else
1923                 ret = CRYPT_CopySignerInfo(pvData, pcbData,
1924                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1925         }
1926         else
1927             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1928         break;
1929     case CMSG_SIGNER_CERT_INFO_PARAM:
1930         if (msg->u.signed_data.info)
1931         {
1932             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1933                 SetLastError(CRYPT_E_INVALID_INDEX);
1934             else
1935                 ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
1936                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1937         }
1938         else
1939             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1940         break;
1941     case CMSG_CERT_COUNT_PARAM:
1942         if (msg->u.signed_data.info)
1943             ret = CRYPT_CopyParam(pvData, pcbData,
1944              &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
1945         else
1946             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1947         break;
1948     case CMSG_CERT_PARAM:
1949         if (msg->u.signed_data.info)
1950         {
1951             if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
1952                 SetLastError(CRYPT_E_INVALID_INDEX);
1953             else
1954                 ret = CRYPT_CopyParam(pvData, pcbData,
1955                  msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
1956                  msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
1957         }
1958         else
1959             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1960         break;
1961     case CMSG_CRL_COUNT_PARAM:
1962         if (msg->u.signed_data.info)
1963             ret = CRYPT_CopyParam(pvData, pcbData,
1964              &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
1965         else
1966             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1967         break;
1968     case CMSG_CRL_PARAM:
1969         if (msg->u.signed_data.info)
1970         {
1971             if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
1972                 SetLastError(CRYPT_E_INVALID_INDEX);
1973             else
1974                 ret = CRYPT_CopyParam(pvData, pcbData,
1975                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
1976                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
1977         }
1978         else
1979             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1980         break;
1981     case CMSG_COMPUTED_HASH_PARAM:
1982         if (msg->u.signed_data.info)
1983         {
1984             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1985                 SetLastError(CRYPT_E_INVALID_INDEX);
1986             else
1987                 ret = CryptGetHashParam(
1988                  msg->u.signed_data.signerHandles[dwIndex].contentHash,
1989                  HP_HASHVAL, pvData, pcbData, 0);
1990         }
1991         else
1992             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1993         break;
1994     case CMSG_ATTR_CERT_COUNT_PARAM:
1995         if (msg->u.signed_data.info)
1996         {
1997             DWORD attrCertCount = 0;
1998
1999             ret = CRYPT_CopyParam(pvData, pcbData,
2000              &attrCertCount, sizeof(DWORD));
2001         }
2002         else
2003             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2004         break;
2005     case CMSG_ATTR_CERT_PARAM:
2006         if (msg->u.signed_data.info)
2007             SetLastError(CRYPT_E_INVALID_INDEX);
2008         else
2009             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2010         break;
2011     default:
2012         FIXME("unimplemented for %d\n", dwParamType);
2013         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2014     }
2015     return ret;
2016 }
2017
2018 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2019  DWORD dwIndex, void *pvData, DWORD *pcbData)
2020 {
2021     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2022     BOOL ret = FALSE;
2023
2024     switch (msg->type)
2025     {
2026     case CMSG_HASHED:
2027         ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2028          pcbData);
2029         break;
2030     case CMSG_SIGNED:
2031         ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2032          pcbData);
2033         break;
2034     default:
2035         switch (dwParamType)
2036         {
2037         case CMSG_TYPE_PARAM:
2038             ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
2039              sizeof(msg->type));
2040             break;
2041         default:
2042         {
2043             CRYPT_DATA_BLOB blob;
2044
2045             ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2046              &blob);
2047             if (ret)
2048                 ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
2049                  blob.cbData);
2050             else
2051                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2052         }
2053         }
2054     }
2055     return ret;
2056 }
2057
2058 static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
2059 {
2060     BOOL ret;
2061     CRYPT_DATA_BLOB hashBlob;
2062
2063     ret = ContextPropertyList_FindProperty(msg->properties,
2064      CMSG_HASH_DATA_PARAM, &hashBlob);
2065     if (ret)
2066     {
2067         DWORD computedHashSize = 0;
2068
2069         ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
2070          &computedHashSize);
2071         if (hashBlob.cbData == computedHashSize)
2072         {
2073             LPBYTE computedHash = CryptMemAlloc(computedHashSize);
2074
2075             if (computedHash)
2076             {
2077                 ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
2078                  computedHash, &computedHashSize);
2079                 if (ret)
2080                     ret = !memcmp(hashBlob.pbData, computedHash,
2081                      hashBlob.cbData);
2082             }
2083             else
2084                 ret = FALSE;
2085         }
2086     }
2087     return ret;
2088 }
2089
2090 static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
2091 {
2092     BOOL ret = FALSE;
2093     DWORD i;
2094
2095     for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
2096     {
2097         ret = CertCompareCertificateName(X509_ASN_ENCODING,
2098          &msg->u.signed_data.info->rgSignerInfo[i].Issuer, &info->Issuer);
2099         if (ret)
2100             ret = CertCompareIntegerBlob(
2101              &msg->u.signed_data.info->rgSignerInfo[i].SerialNumber,
2102              &info->SerialNumber);
2103     }
2104     if (ret)
2105     {
2106         HCRYPTKEY key;
2107
2108         ret = CryptImportPublicKeyInfo(msg->crypt_prov, X509_ASN_ENCODING,
2109          &info->SubjectPublicKeyInfo, &key);
2110         if (ret)
2111         {
2112             HCRYPTHASH hash;
2113
2114             if (msg->u.signed_data.info->rgSignerInfo[i].AuthAttrs.cAttr)
2115                 hash = msg->u.signed_data.signerHandles[i].authAttrHash;
2116             else
2117                 hash = msg->u.signed_data.signerHandles[i].contentHash;
2118             ret = CryptVerifySignatureW(hash,
2119              msg->u.signed_data.info->rgSignerInfo[i].EncryptedHash.pbData,
2120              msg->u.signed_data.info->rgSignerInfo[i].EncryptedHash.cbData,
2121              key, NULL, 0);
2122             CryptDestroyKey(key);
2123         }
2124     }
2125     else
2126         SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2127
2128     return ret;
2129 }
2130
2131 static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2132  DWORD dwCtrlType, const void *pvCtrlPara)
2133 {
2134     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2135     BOOL ret = FALSE;
2136
2137     switch (dwCtrlType)
2138     {
2139     case CMSG_CTRL_VERIFY_SIGNATURE:
2140         switch (msg->type)
2141         {
2142         case CMSG_SIGNED:
2143             ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
2144             break;
2145         default:
2146             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2147         }
2148         break;
2149     case CMSG_CTRL_DECRYPT:
2150         switch (msg->type)
2151         {
2152         default:
2153             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2154         }
2155         break;
2156     case CMSG_CTRL_VERIFY_HASH:
2157         switch (msg->type)
2158         {
2159         case CMSG_HASHED:
2160             ret = CDecodeHashMsg_VerifyHash(msg);
2161             break;
2162         default:
2163             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2164         }
2165         break;
2166     default:
2167         SetLastError(CRYPT_E_CONTROL_TYPE);
2168     }
2169     return ret;
2170 }
2171
2172 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
2173  DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
2174  PCMSG_STREAM_INFO pStreamInfo)
2175 {
2176     CDecodeMsg *msg;
2177
2178     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
2179      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
2180
2181     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
2182     {
2183         SetLastError(E_INVALIDARG);
2184         return NULL;
2185     }
2186     msg = CryptMemAlloc(sizeof(CDecodeMsg));
2187     if (msg)
2188     {
2189         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
2190          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
2191          CDecodeMsg_Control);
2192         msg->type = dwMsgType;
2193         if (hCryptProv)
2194             msg->crypt_prov = hCryptProv;
2195         else
2196         {
2197             msg->crypt_prov = CRYPT_GetDefaultProvider();
2198             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
2199         }
2200         memset(&msg->u, 0, sizeof(msg->u));
2201         msg->msg_data.cbData = 0;
2202         msg->msg_data.pbData = NULL;
2203         msg->properties = ContextPropertyList_Create();
2204     }
2205     return msg;
2206 }
2207
2208 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
2209 {
2210     TRACE("(%p)\n", hCryptMsg);
2211
2212     if (hCryptMsg)
2213     {
2214         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2215
2216         InterlockedIncrement(&msg->ref);
2217     }
2218     return hCryptMsg;
2219 }
2220
2221 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
2222 {
2223     TRACE("(%p)\n", hCryptMsg);
2224
2225     if (hCryptMsg)
2226     {
2227         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2228
2229         if (InterlockedDecrement(&msg->ref) == 0)
2230         {
2231             TRACE("freeing %p\n", msg);
2232             if (msg->close)
2233                 msg->close(msg);
2234             CryptMemFree(msg);
2235         }
2236     }
2237     return TRUE;
2238 }
2239
2240 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
2241  DWORD cbData, BOOL fFinal)
2242 {
2243     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2244     BOOL ret = FALSE;
2245
2246     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
2247
2248     if (msg->state == MsgStateFinalized)
2249         SetLastError(CRYPT_E_MSG_ERROR);
2250     else
2251     {
2252         ret = msg->update(hCryptMsg, pbData, cbData, fFinal);
2253         msg->state = MsgStateUpdated;
2254         if (fFinal)
2255             msg->state = MsgStateFinalized;
2256     }
2257     return ret;
2258 }
2259
2260 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2261  DWORD dwIndex, void *pvData, DWORD *pcbData)
2262 {
2263     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2264
2265     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
2266      pvData, pcbData);
2267     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
2268 }
2269
2270 BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2271  DWORD dwCtrlType, const void *pvCtrlPara)
2272 {
2273     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2274
2275     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
2276      pvCtrlPara);
2277     return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
2278 }
2279
2280 HCERTSTORE WINAPI CryptGetMessageCertificates(DWORD dwMsgAndCertEncodingType,
2281  HCRYPTPROV_LEGACY hCryptProv, DWORD dwFlags, const BYTE* pbSignedBlob,
2282  DWORD cbSignedBlob)
2283 {
2284     CRYPT_DATA_BLOB blob = { cbSignedBlob, (LPBYTE)pbSignedBlob };
2285
2286     TRACE("(%08x, %ld, %d08x %p, %d)\n", dwMsgAndCertEncodingType, hCryptProv,
2287      dwFlags, pbSignedBlob, cbSignedBlob);
2288
2289     return CertOpenStore(CERT_STORE_PROV_PKCS7, dwMsgAndCertEncodingType,
2290      hCryptProv, dwFlags, &blob);
2291 }
2292
2293 LONG WINAPI CryptGetMessageSignerCount(DWORD dwMsgEncodingType,
2294  const BYTE *pbSignedBlob, DWORD cbSignedBlob)
2295 {
2296     HCRYPTMSG msg;
2297     LONG count = -1;
2298
2299     TRACE("(%08x, %p, %d)\n", dwMsgEncodingType, pbSignedBlob, cbSignedBlob);
2300
2301     msg = CryptMsgOpenToDecode(dwMsgEncodingType, 0, 0, 0, NULL, NULL);
2302     if (msg)
2303     {
2304         if (CryptMsgUpdate(msg, pbSignedBlob, cbSignedBlob, TRUE))
2305         {
2306             DWORD size = sizeof(count);
2307
2308             CryptMsgGetParam(msg, CMSG_SIGNER_COUNT_PARAM, 0, &count, &size);
2309         }
2310         CryptMsgClose(msg);
2311     }
2312     return count;
2313 }