crypt32: Update a hash message's hash handles when decoding it.
[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         CryptDestroyKey(msg_data->signerHandles[i].key);
835         CryptDestroyHash(msg_data->signerHandles[i].contentHash);
836         CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
837     }
838     CryptMemFree(msg_data->signerHandles);
839 }
840
841 static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
842  const BYTE *pbData, DWORD cbData)
843 {
844     DWORD i;
845     BOOL ret = TRUE;
846
847     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
848         ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
849          cbData, 0);
850     return ret;
851 }
852
853 static BOOL CRYPT_AppendAttribute(CRYPT_ATTRIBUTES *out,
854  const CRYPT_ATTRIBUTE *in)
855 {
856     BOOL ret = FALSE;
857
858     out->rgAttr = CryptMemRealloc(out->rgAttr,
859      (out->cAttr + 1) * sizeof(CRYPT_ATTRIBUTE));
860     if (out->rgAttr)
861     {
862         ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
863         if (ret)
864             out->cAttr++;
865     }
866     return ret;
867 }
868
869 static BOOL CSignedMsgData_AppendMessageDigestAttribute(
870  CSignedMsgData *msg_data, DWORD signerIndex)
871 {
872     BOOL ret;
873     DWORD size;
874     CRYPT_HASH_BLOB hash = { 0, NULL }, encodedHash = { 0, NULL };
875     char messageDigest[] = szOID_RSA_messageDigest;
876     CRYPT_ATTRIBUTE messageDigestAttr = { messageDigest, 1, &encodedHash };
877
878     size = sizeof(DWORD);
879     ret = CryptGetHashParam(
880      msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
881      (LPBYTE)&hash.cbData, &size, 0);
882     if (ret)
883     {
884         hash.pbData = CryptMemAlloc(hash.cbData);
885         ret = CryptGetHashParam(
886          msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
887          hash.pbData, &hash.cbData, 0);
888         if (ret)
889         {
890             ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
891              NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
892             if (ret)
893             {
894                 ret = CRYPT_AppendAttribute(
895                  &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
896                  &messageDigestAttr);
897                 LocalFree(encodedHash.pbData);
898             }
899         }
900         CryptMemFree(hash.pbData);
901     }
902     return ret;
903 }
904
905 typedef enum {
906     Sign,
907     Verify
908 } SignOrVerify;
909
910 static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
911  CSignedMsgData *msg_data, SignOrVerify flag)
912 {
913     DWORD i;
914     BOOL ret = TRUE;
915
916     TRACE("(%p)\n", msg_data);
917
918     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
919     {
920         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
921         {
922             if (flag == Sign)
923             {
924                 BYTE oid_rsa_data_encoded[] = { 0x06,0x09,0x2a,0x86,0x48,0x86,
925                  0xf7,0x0d,0x01,0x07,0x01 };
926                 CRYPT_DATA_BLOB content = { sizeof(oid_rsa_data_encoded),
927                  oid_rsa_data_encoded };
928                 char contentType[] = szOID_RSA_contentType;
929                 CRYPT_ATTRIBUTE contentTypeAttr = { contentType, 1, &content };
930
931                 /* FIXME: does this depend on inner OID? */
932                 ret = CRYPT_AppendAttribute(
933                  &msg_data->info->rgSignerInfo[i].AuthAttrs, &contentTypeAttr);
934                 if (ret)
935                     ret = CSignedMsgData_AppendMessageDigestAttribute(msg_data,
936                      i);
937             }
938             if (ret)
939             {
940                 LPBYTE encodedAttrs;
941                 DWORD size;
942
943                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
944                  &msg_data->info->rgSignerInfo[i].AuthAttrs,
945                  CRYPT_ENCODE_ALLOC_FLAG, NULL, (LPBYTE)&encodedAttrs, &size);
946                 if (ret)
947                 {
948                     ret = CryptHashData(
949                      msg_data->signerHandles[i].authAttrHash, encodedAttrs,
950                      size, 0);
951                     LocalFree(encodedAttrs);
952                 }
953             }
954         }
955     }
956     TRACE("returning %d\n", ret);
957     return ret;
958 }
959
960 static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
961 {
962     DWORD i;
963     BYTE tmp;
964
965     for (i = 0; i < hash->cbData / 2; i++)
966     {
967         tmp = hash->pbData[hash->cbData - i - 1];
968         hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
969         hash->pbData[i] = tmp;
970     }
971 }
972
973 static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
974 {
975     DWORD i;
976     BOOL ret = TRUE;
977
978     TRACE("(%p)\n", msg_data);
979
980     for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
981     {
982         HCRYPTHASH hash;
983
984         if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
985             hash = msg_data->signerHandles[i].authAttrHash;
986         else
987             hash = msg_data->signerHandles[i].contentHash;
988         ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
989          &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
990         if (ret)
991         {
992             msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
993              CryptMemAlloc(
994              msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
995             if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
996             {
997                 ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
998                  msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
999                  &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1000                 if (ret)
1001                     CRYPT_ReverseBytes(
1002                      &msg_data->info->rgSignerInfo[i].EncryptedHash);
1003             }
1004             else
1005                 ret = FALSE;
1006         }
1007     }
1008     return ret;
1009 }
1010
1011 static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1012  const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1013 {
1014     BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);
1015
1016     if (ret && fFinal)
1017     {
1018         ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
1019         if (ret && flag == Sign)
1020             ret = CSignedMsgData_Sign(msg_data);
1021     }
1022     return ret;
1023 }
1024
1025 typedef struct _CSignedEncodeMsg
1026 {
1027     CryptMsgBase    base;
1028     CRYPT_DATA_BLOB data;
1029     CSignedMsgData  msg_data;
1030 } CSignedEncodeMsg;
1031
1032 static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
1033 {
1034     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1035     DWORD i;
1036
1037     CryptMemFree(msg->data.pbData);
1038     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCertEncoded);
1039     CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCrlEncoded);
1040     for (i = 0; i < msg->msg_data.info->cSignerInfo; i++)
1041         CSignerInfo_Free(&msg->msg_data.info->rgSignerInfo[i]);
1042     CSignedMsgData_CloseHandles(&msg->msg_data);
1043     CryptMemFree(msg->msg_data.info->rgSignerInfo);
1044     CryptMemFree(msg->msg_data.info);
1045 }
1046
1047 static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1048  DWORD dwIndex, void *pvData, DWORD *pcbData)
1049 {
1050     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1051     BOOL ret = FALSE;
1052
1053     switch (dwParamType)
1054     {
1055     case CMSG_CONTENT_PARAM:
1056     {
1057         CRYPT_CONTENT_INFO info;
1058
1059         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
1060          &info.Content.cbData);
1061         if (ret)
1062         {
1063             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
1064             if (info.Content.pbData)
1065             {
1066                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
1067                  info.Content.pbData, &info.Content.cbData);
1068                 if (ret)
1069                 {
1070                     char oid_rsa_signed[] = szOID_RSA_signedData;
1071
1072                     info.pszObjId = oid_rsa_signed;
1073                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
1074                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
1075                 }
1076                 CryptMemFree(info.Content.pbData);
1077             }
1078             else
1079                 ret = FALSE;
1080         }
1081         break;
1082     }
1083     case CMSG_BARE_CONTENT_PARAM:
1084     {
1085         CRYPT_SIGNED_INFO info;
1086         char oid_rsa_data[] = szOID_RSA_data;
1087
1088         memcpy(&info, msg->msg_data.info, sizeof(info));
1089         /* Quirk:  OID is only encoded messages if an update has happened */
1090         if (msg->base.state != MsgStateInit)
1091             info.content.pszObjId = oid_rsa_data;
1092         else
1093             info.content.pszObjId = NULL;
1094         if (msg->data.cbData)
1095         {
1096             CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
1097
1098             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1099              &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
1100              &info.content.Content.pbData, &info.content.Content.cbData);
1101         }
1102         else
1103         {
1104             info.content.Content.cbData = 0;
1105             info.content.Content.pbData = NULL;
1106             ret = TRUE;
1107         }
1108         if (ret)
1109         {
1110             ret = CRYPT_AsnEncodePKCSSignedInfo(&info, pvData, pcbData);
1111             LocalFree(info.content.Content.pbData);
1112         }
1113         break;
1114     }
1115     case CMSG_COMPUTED_HASH_PARAM:
1116         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1117             SetLastError(CRYPT_E_INVALID_INDEX);
1118         else
1119             ret = CryptGetHashParam(
1120              msg->msg_data.signerHandles[dwIndex].contentHash, HP_HASHVAL,
1121              pvData, pcbData, 0);
1122         break;
1123     case CMSG_ENCODED_SIGNER:
1124         if (dwIndex >= msg->msg_data.info->cSignerInfo)
1125             SetLastError(CRYPT_E_INVALID_INDEX);
1126         else
1127             ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1128              PKCS7_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1129              NULL, pvData, pcbData);
1130         break;
1131     case CMSG_VERSION_PARAM:
1132         ret = CRYPT_CopyParam(pvData, pcbData, &msg->msg_data.info->version,
1133          sizeof(msg->msg_data.info->version));
1134         break;
1135     default:
1136         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1137     }
1138     return ret;
1139 }
1140
1141 static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1142  DWORD cbData, BOOL fFinal)
1143 {
1144     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
1145     BOOL ret = FALSE;
1146
1147     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1148     {
1149         ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
1150          Sign);
1151         if (msg->base.streamed)
1152             FIXME("streamed partial stub\n");
1153     }
1154     else
1155     {
1156         if (!fFinal)
1157             SetLastError(CRYPT_E_MSG_ERROR);
1158         else
1159         {
1160             if (cbData)
1161             {
1162                 msg->data.pbData = CryptMemAlloc(cbData);
1163                 if (msg->data.pbData)
1164                 {
1165                     memcpy(msg->data.pbData, pbData, cbData);
1166                     msg->data.cbData = cbData;
1167                     ret = TRUE;
1168                 }
1169             }
1170             else
1171                 ret = TRUE;
1172             if (ret)
1173                 ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1174                  fFinal, Sign);
1175         }
1176     }
1177     return ret;
1178 }
1179
1180 static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1181  const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1182  PCMSG_STREAM_INFO pStreamInfo)
1183 {
1184     const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info =
1185      (const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *)pvMsgEncodeInfo;
1186     DWORD i;
1187     CSignedEncodeMsg *msg;
1188
1189     if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
1190      info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1191     {
1192         SetLastError(E_INVALIDARG);
1193         return NULL;
1194     }
1195     if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1196     {
1197         FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
1198         return NULL;
1199     }
1200     for (i = 0; i < info->cSigners; i++)
1201         if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
1202             return NULL;
1203     msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
1204     if (msg)
1205     {
1206         BOOL ret = TRUE;
1207
1208         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1209          CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1210          CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1211         msg->data.cbData = 0;
1212         msg->data.pbData = NULL;
1213         msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
1214         if (msg->msg_data.info)
1215         {
1216             memset(msg->msg_data.info, 0, sizeof(CRYPT_SIGNED_INFO));
1217             msg->msg_data.info->version = CMSG_SIGNED_DATA_V1;
1218         }
1219         else
1220             ret = FALSE;
1221         if (ret && info->cSigners)
1222         {
1223             msg->msg_data.info->rgSignerInfo =
1224              CryptMemAlloc(info->cSigners * sizeof(CMSG_SIGNER_INFO));
1225             if (msg->msg_data.info->rgSignerInfo)
1226             {
1227                 msg->msg_data.info->cSignerInfo = info->cSigners;
1228                 memset(msg->msg_data.info->rgSignerInfo, 0,
1229                  msg->msg_data.info->cSignerInfo * sizeof(CMSG_SIGNER_INFO));
1230                 ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
1231                 for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1232                 {
1233                     ret = CSignerInfo_Construct(
1234                      &msg->msg_data.info->rgSignerInfo[i],
1235                      &info->rgSigners[i]);
1236                     if (ret)
1237                     {
1238                         ret = CSignedMsgData_ConstructSignerHandles(
1239                          &msg->msg_data, i, info->rgSigners[i].hCryptProv);
1240                         if (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1241                             CryptReleaseContext(info->rgSigners[i].hCryptProv,
1242                              0);
1243                     }
1244                 }
1245             }
1246             else
1247                 ret = FALSE;
1248         }
1249         if (ret)
1250             ret = CRYPT_ConstructBlobArray(
1251              (BlobArray *)&msg->msg_data.info->cCertEncoded,
1252              (const BlobArray *)&info->cCertEncoded);
1253         if (ret)
1254             ret = CRYPT_ConstructBlobArray(
1255              (BlobArray *)&msg->msg_data.info->cCrlEncoded,
1256              (const BlobArray *)&info->cCrlEncoded);
1257         if (!ret)
1258         {
1259             CSignedEncodeMsg_Close(msg);
1260             msg = NULL;
1261         }
1262     }
1263     return msg;
1264 }
1265
1266 static inline const char *MSG_TYPE_STR(DWORD type)
1267 {
1268     switch (type)
1269     {
1270 #define _x(x) case (x): return #x
1271         _x(CMSG_DATA);
1272         _x(CMSG_SIGNED);
1273         _x(CMSG_ENVELOPED);
1274         _x(CMSG_SIGNED_AND_ENVELOPED);
1275         _x(CMSG_HASHED);
1276         _x(CMSG_ENCRYPTED);
1277 #undef _x
1278         default:
1279             return wine_dbg_sprintf("unknown (%d)", type);
1280     }
1281 }
1282
1283 HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
1284  DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1285  PCMSG_STREAM_INFO pStreamInfo)
1286 {
1287     HCRYPTMSG msg = NULL;
1288
1289     TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
1290      dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
1291
1292     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
1293     {
1294         SetLastError(E_INVALIDARG);
1295         return NULL;
1296     }
1297     switch (dwMsgType)
1298     {
1299     case CMSG_DATA:
1300         msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1301          pszInnerContentObjID, pStreamInfo);
1302         break;
1303     case CMSG_HASHED:
1304         msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1305          pszInnerContentObjID, pStreamInfo);
1306         break;
1307     case CMSG_SIGNED:
1308         msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1309          pszInnerContentObjID, pStreamInfo);
1310         break;
1311     case CMSG_ENVELOPED:
1312         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(dwMsgType));
1313         break;
1314     case CMSG_SIGNED_AND_ENVELOPED:
1315     case CMSG_ENCRYPTED:
1316         /* defined but invalid, fall through */
1317     default:
1318         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1319     }
1320     return msg;
1321 }
1322
1323 typedef struct _CDecodeMsg
1324 {
1325     CryptMsgBase           base;
1326     DWORD                  type;
1327     HCRYPTPROV             crypt_prov;
1328     union {
1329         HCRYPTHASH     hash;
1330         CSignedMsgData signed_data;
1331     } u;
1332     CRYPT_DATA_BLOB        msg_data;
1333     PCONTEXT_PROPERTY_LIST properties;
1334 } CDecodeMsg;
1335
1336 static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
1337 {
1338     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1339
1340     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1341         CryptReleaseContext(msg->crypt_prov, 0);
1342     switch (msg->type)
1343     {
1344     case CMSG_HASHED:
1345         if (msg->u.hash)
1346             CryptDestroyHash(msg->u.hash);
1347         break;
1348     case CMSG_SIGNED:
1349         if (msg->u.signed_data.info)
1350         {
1351             LocalFree(msg->u.signed_data.info);
1352             CSignedMsgData_CloseHandles(&msg->u.signed_data);
1353         }
1354         break;
1355     }
1356     CryptMemFree(msg->msg_data.pbData);
1357     ContextPropertyList_Free(msg->properties);
1358 }
1359
1360 static BOOL CDecodeMsg_CopyData(CDecodeMsg *msg, const BYTE *pbData,
1361  DWORD cbData)
1362 {
1363     BOOL ret = TRUE;
1364
1365     if (cbData)
1366     {
1367         if (msg->msg_data.cbData)
1368             msg->msg_data.pbData = CryptMemRealloc(msg->msg_data.pbData,
1369              msg->msg_data.cbData + cbData);
1370         else
1371             msg->msg_data.pbData = CryptMemAlloc(cbData);
1372         if (msg->msg_data.pbData)
1373         {
1374             memcpy(msg->msg_data.pbData + msg->msg_data.cbData, pbData, cbData);
1375             msg->msg_data.cbData += cbData;
1376         }
1377         else
1378             ret = FALSE;
1379     }
1380     return ret;
1381 }
1382
1383 static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
1384 {
1385     BOOL ret;
1386     CRYPT_DATA_BLOB *data;
1387     DWORD size;
1388
1389     ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1390      blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&data,
1391      &size);
1392     if (ret)
1393     {
1394         ret = ContextPropertyList_SetProperty(msg->properties,
1395          CMSG_CONTENT_PARAM, data->pbData, data->cbData);
1396         LocalFree(data);
1397     }
1398     return ret;
1399 }
1400
1401 static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
1402  const CRYPT_ALGORITHM_IDENTIFIER *id)
1403 {
1404     static const BYTE nullParams[] = { ASN_NULL, 0 };
1405     CRYPT_ALGORITHM_IDENTIFIER *copy;
1406     DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);
1407
1408     /* Linearize algorithm id */
1409     len += strlen(id->pszObjId) + 1;
1410     len += id->Parameters.cbData;
1411     copy = CryptMemAlloc(len);
1412     if (copy)
1413     {
1414         copy->pszObjId =
1415          (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1416         strcpy(copy->pszObjId, id->pszObjId);
1417         copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
1418          + 1;
1419         /* Trick:  omit NULL parameters */
1420         if (id->Parameters.cbData == sizeof(nullParams) &&
1421          !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
1422         {
1423             copy->Parameters.cbData = 0;
1424             len -= sizeof(nullParams);
1425         }
1426         else
1427             copy->Parameters.cbData = id->Parameters.cbData;
1428         if (copy->Parameters.cbData)
1429             memcpy(copy->Parameters.pbData, id->Parameters.pbData,
1430              id->Parameters.cbData);
1431         ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
1432          len);
1433         CryptMemFree(copy);
1434     }
1435 }
1436
1437 static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
1438 {
1439     id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1440     id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
1441 }
1442
1443 static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
1444  CRYPT_DER_BLOB *blob)
1445 {
1446     BOOL ret;
1447     CRYPT_DIGESTED_DATA *digestedData;
1448     DWORD size;
1449
1450     ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
1451      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
1452      &size);
1453     if (ret)
1454     {
1455         ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
1456          (const BYTE *)&digestedData->version, sizeof(digestedData->version));
1457         CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
1458          &digestedData->DigestAlgorithm);
1459         ContextPropertyList_SetProperty(msg->properties,
1460          CMSG_INNER_CONTENT_TYPE_PARAM,
1461          (const BYTE *)digestedData->ContentInfo.pszObjId,
1462          digestedData->ContentInfo.pszObjId ?
1463          strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
1464         if (digestedData->ContentInfo.Content.cbData)
1465             CDecodeMsg_DecodeDataContent(msg,
1466              &digestedData->ContentInfo.Content);
1467         else
1468             ContextPropertyList_SetProperty(msg->properties,
1469              CMSG_CONTENT_PARAM, NULL, 0);
1470         ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
1471          digestedData->hash.pbData, digestedData->hash.cbData);
1472         LocalFree(digestedData);
1473     }
1474     return ret;
1475 }
1476
1477 static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
1478  CRYPT_DER_BLOB *blob)
1479 {
1480     BOOL ret;
1481     CRYPT_SIGNED_INFO *signedInfo;
1482     DWORD size;
1483
1484     ret = CRYPT_AsnDecodePKCSSignedInfo(blob->pbData, blob->cbData,
1485      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
1486      &size);
1487     if (ret)
1488     {
1489         DWORD i;
1490
1491         msg->u.signed_data.info = signedInfo;
1492         ret = CSignedMsgData_AllocateHandles(&msg->u.signed_data);
1493         for (i = 0; ret && i < msg->u.signed_data.info->cSignerInfo; i++)
1494             ret = CSignedMsgData_ConstructSignerHandles(&msg->u.signed_data, i,
1495              msg->crypt_prov);
1496         if (ret)
1497         {
1498             /* Now that we have all the content, update the hash handles with
1499              * it.  Have to decode it if the type is szOID_RSA_data.
1500              */
1501             if (msg->u.signed_data.info->content.Content.cbData)
1502             {
1503                 if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1504                  szOID_RSA_data))
1505                 {
1506                     CRYPT_DATA_BLOB *blob;
1507
1508                     ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
1509                      X509_OCTET_STRING,
1510                      msg->u.signed_data.info->content.Content.pbData,
1511                      msg->u.signed_data.info->content.Content.cbData,
1512                      CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1513                     if (ret)
1514                     {
1515                         ret = CSignedMsgData_Update(&msg->u.signed_data,
1516                          blob->pbData, blob->cbData, TRUE, Verify);
1517                         LocalFree(blob);
1518                     }
1519                 }
1520                 else
1521                     ret = CSignedMsgData_Update(&msg->u.signed_data,
1522                      msg->u.signed_data.info->content.Content.pbData,
1523                      msg->u.signed_data.info->content.Content.cbData, TRUE,
1524                      Verify);
1525             }
1526         }
1527     }
1528     return ret;
1529 }
1530 /* Decodes the content in blob as the type given, and updates the value
1531  * (type, parameters, etc.) of msg based on what blob contains.
1532  * It doesn't just use msg's type, to allow a recursive call from an implicitly
1533  * typed message once the outer content info has been decoded.
1534  */
1535 static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob,
1536  DWORD type)
1537 {
1538     BOOL ret;
1539
1540     switch (type)
1541     {
1542     case CMSG_DATA:
1543         if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
1544             msg->type = CMSG_DATA;
1545         break;
1546     case CMSG_HASHED:
1547         if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
1548             msg->type = CMSG_HASHED;
1549         break;
1550     case CMSG_ENVELOPED:
1551         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(type));
1552         ret = TRUE;
1553         break;
1554     case CMSG_SIGNED:
1555         if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
1556             msg->type = CMSG_SIGNED;
1557         break;
1558     default:
1559     {
1560         CRYPT_CONTENT_INFO *info;
1561         DWORD size;
1562
1563         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
1564          msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
1565          NULL, (LPBYTE)&info, &size);
1566         if (ret)
1567         {
1568             if (!strcmp(info->pszObjId, szOID_RSA_data))
1569                 ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
1570             else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
1571                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1572                  CMSG_HASHED);
1573             else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
1574                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1575                  CMSG_ENVELOPED);
1576             else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
1577                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1578                  CMSG_SIGNED);
1579             else
1580             {
1581                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1582                 ret = FALSE;
1583             }
1584             LocalFree(info);
1585         }
1586     }
1587     }
1588     return ret;
1589 }
1590
1591 static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1592  DWORD cbData, BOOL fFinal)
1593 {
1594     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1595     BOOL ret = FALSE;
1596
1597     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
1598
1599     if (msg->base.streamed)
1600     {
1601         ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1602         FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
1603          cbData, fFinal);
1604     }
1605     else
1606     {
1607         if (!fFinal)
1608             SetLastError(CRYPT_E_MSG_ERROR);
1609         else
1610         {
1611             ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1612             if (ret)
1613                 ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
1614
1615         }
1616     }
1617     return ret;
1618 }
1619
1620 static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1621  DWORD dwIndex, void *pvData, DWORD *pcbData)
1622 {
1623     BOOL ret = FALSE;
1624
1625     switch (dwParamType)
1626     {
1627     case CMSG_TYPE_PARAM:
1628         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1629         break;
1630     case CMSG_HASH_ALGORITHM_PARAM:
1631     {
1632         CRYPT_DATA_BLOB blob;
1633
1634         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1635          &blob);
1636         if (ret)
1637         {
1638             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1639             if (ret && pvData)
1640                 CRYPT_FixUpAlgorithmID((CRYPT_ALGORITHM_IDENTIFIER *)pvData);
1641         }
1642         else
1643             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1644         break;
1645     }
1646     case CMSG_COMPUTED_HASH_PARAM:
1647         if (!msg->u.hash)
1648         {
1649             CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
1650             DWORD size = 0;
1651             ALG_ID algID = 0;
1652
1653             CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
1654             hashAlgoID = CryptMemAlloc(size);
1655             ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0,
1656              hashAlgoID, &size);
1657             if (ret)
1658                 algID = CertOIDToAlgId(hashAlgoID->pszObjId);
1659             ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->u.hash);
1660             if (ret)
1661             {
1662                 CRYPT_DATA_BLOB content;
1663
1664                 ret = ContextPropertyList_FindProperty(msg->properties,
1665                  CMSG_CONTENT_PARAM, &content);
1666                 if (ret)
1667                     ret = CryptHashData(msg->u.hash, content.pbData,
1668                      content.cbData, 0);
1669             }
1670             CryptMemFree(hashAlgoID);
1671         }
1672         else
1673             ret = TRUE;
1674         if (ret)
1675             ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData,
1676              0);
1677         break;
1678     default:
1679     {
1680         CRYPT_DATA_BLOB blob;
1681
1682         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1683          &blob);
1684         if (ret)
1685             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1686         else
1687             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1688     }
1689     }
1690     return ret;
1691 }
1692
1693 /* nextData is an in/out parameter - on input it's the memory location in
1694  * which a copy of in's data should be made, and on output it's the memory
1695  * location immediately after out's copy of in's data.
1696  */
1697 static inline void CRYPT_CopyBlob(CRYPT_DATA_BLOB *out,
1698  const CRYPT_DATA_BLOB *in, LPBYTE *nextData)
1699 {
1700     out->cbData = in->cbData;
1701     if (in->cbData)
1702     {
1703         out->pbData = *nextData;
1704         memcpy(out->pbData, in->pbData, in->cbData);
1705         *nextData += in->cbData;
1706     }
1707 }
1708
1709 static inline void CRYPT_CopyAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
1710  const CRYPT_ALGORITHM_IDENTIFIER *in, LPBYTE *nextData)
1711 {
1712     if (in->pszObjId)
1713     {
1714         out->pszObjId = (LPSTR)*nextData;
1715         strcpy(out->pszObjId, in->pszObjId);
1716         *nextData += strlen(out->pszObjId) + 1;
1717     }
1718     CRYPT_CopyBlob(&out->Parameters, &in->Parameters, nextData);
1719 }
1720
1721 static inline void CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
1722  const CRYPT_ATTRIBUTES *in, LPBYTE *nextData)
1723 {
1724     out->cAttr = in->cAttr;
1725     if (in->cAttr)
1726     {
1727         DWORD i;
1728
1729         if ((*nextData - (LPBYTE)0) % sizeof(DWORD))
1730             *nextData += (*nextData - (LPBYTE)0) % sizeof(DWORD);
1731         out->rgAttr = (CRYPT_ATTRIBUTE *)*nextData;
1732         *nextData += in->cAttr * sizeof(CRYPT_ATTRIBUTE);
1733         for (i = 0; i < in->cAttr; i++)
1734         {
1735             if (in->rgAttr[i].pszObjId)
1736             {
1737                 out->rgAttr[i].pszObjId = (LPSTR)*nextData;
1738                 strcpy(out->rgAttr[i].pszObjId, in->rgAttr[i].pszObjId);
1739                 *nextData += strlen(in->rgAttr[i].pszObjId) + 1;
1740             }
1741             if (in->rgAttr[i].cValue)
1742             {
1743                 DWORD j;
1744
1745                 out->rgAttr[i].cValue = in->rgAttr[i].cValue;
1746                 if ((*nextData - (LPBYTE)0) % sizeof(DWORD))
1747                     *nextData += (*nextData - (LPBYTE)0) % sizeof(DWORD);
1748                 out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
1749                 for (j = 0; j < in->rgAttr[i].cValue; j++)
1750                     CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
1751                      &in->rgAttr[i].rgValue[j], nextData);
1752             }
1753         }
1754     }
1755 }
1756
1757 static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
1758 {
1759     DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;
1760
1761     for (i = 0; i < attr->cAttr; i++)
1762     {
1763         if (attr->rgAttr[i].pszObjId)
1764             size += strlen(attr->rgAttr[i].pszObjId) + 1;
1765         /* align pointer */
1766         if (size % sizeof(DWORD))
1767             size += size % sizeof(DWORD);
1768         size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
1769         for (j = 0; j < attr->rgAttr[i].cValue; j++)
1770             size += attr->rgAttr[i].rgValue[j].cbData;
1771     }
1772     return size;
1773 }
1774
1775 static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
1776  const CMSG_SIGNER_INFO *in)
1777 {
1778     DWORD size = sizeof(CMSG_SIGNER_INFO);
1779     BOOL ret;
1780
1781     size += in->Issuer.cbData;
1782     size += in->SerialNumber.cbData;
1783     if (in->HashAlgorithm.pszObjId)
1784         size += strlen(in->HashAlgorithm.pszObjId) + 1;
1785     size += in->HashAlgorithm.Parameters.cbData;
1786     if (in->HashEncryptionAlgorithm.pszObjId)
1787         size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
1788     size += in->HashEncryptionAlgorithm.Parameters.cbData;
1789     size += in->EncryptedHash.cbData;
1790     /* align pointer */
1791     if (size % sizeof(DWORD))
1792         size += size % sizeof(DWORD);
1793     size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
1794     size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
1795     if (!pvData)
1796     {
1797         *pcbData = size;
1798         ret = TRUE;
1799     }
1800     else if (*pcbData < size)
1801     {
1802         *pcbData = size;
1803         SetLastError(ERROR_MORE_DATA);
1804         ret = FALSE;
1805     }
1806     else
1807     {
1808         LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
1809         CMSG_SIGNER_INFO *out = (CMSG_SIGNER_INFO *)pvData;
1810
1811         out->dwVersion = in->dwVersion;
1812         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1813         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1814         CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
1815          &nextData);
1816         CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
1817          &in->HashEncryptionAlgorithm, &nextData);
1818         CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
1819         /* align pointer */
1820         if ((nextData - (LPBYTE)0) % sizeof(DWORD))
1821             nextData += (nextData - (LPBYTE)0) % sizeof(DWORD);
1822         CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
1823         CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
1824         ret = TRUE;
1825     }
1826     return ret;
1827 }
1828
1829 static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
1830  const CMSG_SIGNER_INFO *in)
1831 {
1832     DWORD size = sizeof(CERT_INFO);
1833     BOOL ret;
1834
1835     size += in->Issuer.cbData;
1836     size += in->SerialNumber.cbData;
1837     if (!pvData)
1838     {
1839         *pcbData = size;
1840         ret = TRUE;
1841     }
1842     else if (*pcbData < size)
1843     {
1844         *pcbData = size;
1845         SetLastError(ERROR_MORE_DATA);
1846         ret = FALSE;
1847     }
1848     else
1849     {
1850         LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
1851         CERT_INFO *out = (CERT_INFO *)pvData;
1852
1853         memset(out, 0, sizeof(CERT_INFO));
1854         CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
1855         CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
1856         ret = TRUE;
1857     }
1858     return ret;
1859 }
1860
1861 static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1862  DWORD dwIndex, void *pvData, DWORD *pcbData)
1863 {
1864     BOOL ret = FALSE;
1865
1866     switch (dwParamType)
1867     {
1868     case CMSG_TYPE_PARAM:
1869         ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1870         break;
1871     case CMSG_CONTENT_PARAM:
1872         if (msg->u.signed_data.info)
1873         {
1874             if (!strcmp(msg->u.signed_data.info->content.pszObjId,
1875              szOID_RSA_data))
1876             {
1877                 CRYPT_DATA_BLOB *blob;
1878                 DWORD size;
1879
1880                 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1881                  msg->u.signed_data.info->content.Content.pbData,
1882                  msg->u.signed_data.info->content.Content.cbData,
1883                  CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&blob, &size);
1884                 if (ret)
1885                 {
1886                     ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
1887                      blob->cbData);
1888                     LocalFree(blob);
1889                 }
1890             }
1891             else
1892                 ret = CRYPT_CopyParam(pvData, pcbData,
1893                  msg->u.signed_data.info->content.Content.pbData,
1894                  msg->u.signed_data.info->content.Content.cbData);
1895         }
1896         else
1897             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1898         break;
1899     case CMSG_INNER_CONTENT_TYPE_PARAM:
1900         if (msg->u.signed_data.info)
1901             ret = CRYPT_CopyParam(pvData, pcbData,
1902              msg->u.signed_data.info->content.pszObjId,
1903              strlen(msg->u.signed_data.info->content.pszObjId) + 1);
1904         else
1905             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1906         break;
1907     case CMSG_SIGNER_COUNT_PARAM:
1908         if (msg->u.signed_data.info)
1909             ret = CRYPT_CopyParam(pvData, pcbData,
1910              &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
1911         else
1912             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1913         break;
1914     case CMSG_SIGNER_INFO_PARAM:
1915         if (msg->u.signed_data.info)
1916         {
1917             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1918                 SetLastError(CRYPT_E_INVALID_INDEX);
1919             else
1920                 ret = CRYPT_CopySignerInfo(pvData, pcbData,
1921                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1922         }
1923         else
1924             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1925         break;
1926     case CMSG_SIGNER_CERT_INFO_PARAM:
1927         if (msg->u.signed_data.info)
1928         {
1929             if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
1930                 SetLastError(CRYPT_E_INVALID_INDEX);
1931             else
1932                 ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
1933                  &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
1934         }
1935         else
1936             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1937         break;
1938     case CMSG_CERT_COUNT_PARAM:
1939         if (msg->u.signed_data.info)
1940             ret = CRYPT_CopyParam(pvData, pcbData,
1941              &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
1942         else
1943             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1944         break;
1945     case CMSG_CERT_PARAM:
1946         if (msg->u.signed_data.info)
1947         {
1948             if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
1949                 SetLastError(CRYPT_E_INVALID_INDEX);
1950             else
1951                 ret = CRYPT_CopyParam(pvData, pcbData,
1952                  msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
1953                  msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
1954         }
1955         else
1956             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1957         break;
1958     case CMSG_CRL_COUNT_PARAM:
1959         if (msg->u.signed_data.info)
1960             ret = CRYPT_CopyParam(pvData, pcbData,
1961              &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
1962         else
1963             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1964         break;
1965     case CMSG_CRL_PARAM:
1966         if (msg->u.signed_data.info)
1967         {
1968             if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
1969                 SetLastError(CRYPT_E_INVALID_INDEX);
1970             else
1971                 ret = CRYPT_CopyParam(pvData, pcbData,
1972                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
1973                  msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
1974         }
1975         else
1976             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1977         break;
1978     case CMSG_ATTR_CERT_COUNT_PARAM:
1979         if (msg->u.signed_data.info)
1980         {
1981             DWORD attrCertCount = 0;
1982
1983             ret = CRYPT_CopyParam(pvData, pcbData,
1984              &attrCertCount, sizeof(DWORD));
1985         }
1986         else
1987             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1988         break;
1989     case CMSG_ATTR_CERT_PARAM:
1990         if (msg->u.signed_data.info)
1991             SetLastError(CRYPT_E_INVALID_INDEX);
1992         else
1993             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1994         break;
1995     default:
1996         FIXME("unimplemented for %d\n", dwParamType);
1997         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1998     }
1999     return ret;
2000 }
2001
2002 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2003  DWORD dwIndex, void *pvData, DWORD *pcbData)
2004 {
2005     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2006     BOOL ret = FALSE;
2007
2008     switch (msg->type)
2009     {
2010     case CMSG_HASHED:
2011         ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2012          pcbData);
2013         break;
2014     case CMSG_SIGNED:
2015         ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
2016          pcbData);
2017         break;
2018     default:
2019         switch (dwParamType)
2020         {
2021         case CMSG_TYPE_PARAM:
2022             ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
2023              sizeof(msg->type));
2024             break;
2025         default:
2026         {
2027             CRYPT_DATA_BLOB blob;
2028
2029             ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
2030              &blob);
2031             if (ret)
2032                 ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
2033                  blob.cbData);
2034             else
2035                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2036         }
2037         }
2038     }
2039     return ret;
2040 }
2041
2042 static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
2043 {
2044     BOOL ret;
2045     CRYPT_DATA_BLOB hashBlob;
2046
2047     ret = ContextPropertyList_FindProperty(msg->properties,
2048      CMSG_HASH_DATA_PARAM, &hashBlob);
2049     if (ret)
2050     {
2051         DWORD computedHashSize = 0;
2052
2053         ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
2054          &computedHashSize);
2055         if (hashBlob.cbData == computedHashSize)
2056         {
2057             LPBYTE computedHash = CryptMemAlloc(computedHashSize);
2058
2059             if (computedHash)
2060             {
2061                 ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
2062                  computedHash, &computedHashSize);
2063                 if (ret)
2064                     ret = !memcmp(hashBlob.pbData, computedHash,
2065                      hashBlob.cbData);
2066             }
2067             else
2068                 ret = FALSE;
2069         }
2070     }
2071     return ret;
2072 }
2073
2074 static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2075  DWORD dwCtrlType, const void *pvCtrlPara)
2076 {
2077     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
2078     BOOL ret = FALSE;
2079
2080     switch (dwCtrlType)
2081     {
2082     case CMSG_CTRL_VERIFY_SIGNATURE:
2083         switch (msg->type)
2084         {
2085         case CMSG_SIGNED:
2086             FIXME("CMSG_CTRL_VERIFY_SIGNATURE: stub\n");
2087             break;
2088         default:
2089             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2090         }
2091         break;
2092     case CMSG_CTRL_DECRYPT:
2093         switch (msg->type)
2094         {
2095         default:
2096             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2097         }
2098         break;
2099     case CMSG_CTRL_VERIFY_HASH:
2100         switch (msg->type)
2101         {
2102         case CMSG_HASHED:
2103             ret = CDecodeHashMsg_VerifyHash(msg);
2104             break;
2105         default:
2106             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2107         }
2108         break;
2109     default:
2110         SetLastError(CRYPT_E_CONTROL_TYPE);
2111     }
2112     return ret;
2113 }
2114
2115 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
2116  DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
2117  PCMSG_STREAM_INFO pStreamInfo)
2118 {
2119     CDecodeMsg *msg;
2120
2121     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
2122      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
2123
2124     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
2125     {
2126         SetLastError(E_INVALIDARG);
2127         return NULL;
2128     }
2129     msg = CryptMemAlloc(sizeof(CDecodeMsg));
2130     if (msg)
2131     {
2132         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
2133          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
2134          CDecodeMsg_Control);
2135         msg->type = dwMsgType;
2136         if (hCryptProv)
2137             msg->crypt_prov = hCryptProv;
2138         else
2139         {
2140             msg->crypt_prov = CRYPT_GetDefaultProvider();
2141             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
2142         }
2143         memset(&msg->u, 0, sizeof(msg->u));
2144         msg->msg_data.cbData = 0;
2145         msg->msg_data.pbData = NULL;
2146         msg->properties = ContextPropertyList_Create();
2147     }
2148     return msg;
2149 }
2150
2151 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
2152 {
2153     TRACE("(%p)\n", hCryptMsg);
2154
2155     if (hCryptMsg)
2156     {
2157         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2158
2159         InterlockedIncrement(&msg->ref);
2160     }
2161     return hCryptMsg;
2162 }
2163
2164 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
2165 {
2166     TRACE("(%p)\n", hCryptMsg);
2167
2168     if (hCryptMsg)
2169     {
2170         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2171
2172         if (InterlockedDecrement(&msg->ref) == 0)
2173         {
2174             TRACE("freeing %p\n", msg);
2175             if (msg->close)
2176                 msg->close(msg);
2177             CryptMemFree(msg);
2178         }
2179     }
2180     return TRUE;
2181 }
2182
2183 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
2184  DWORD cbData, BOOL fFinal)
2185 {
2186     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2187     BOOL ret = FALSE;
2188
2189     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
2190
2191     if (msg->state == MsgStateFinalized)
2192         SetLastError(CRYPT_E_MSG_ERROR);
2193     else
2194     {
2195         ret = msg->update(hCryptMsg, pbData, cbData, fFinal);
2196         msg->state = MsgStateUpdated;
2197         if (fFinal)
2198             msg->state = MsgStateFinalized;
2199     }
2200     return ret;
2201 }
2202
2203 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
2204  DWORD dwIndex, void *pvData, DWORD *pcbData)
2205 {
2206     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2207
2208     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
2209      pvData, pcbData);
2210     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
2211 }
2212
2213 BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
2214  DWORD dwCtrlType, const void *pvCtrlPara)
2215 {
2216     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
2217
2218     TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
2219      pvCtrlPara);
2220     return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
2221 }