crypt32: Partially implement decoding of signed messages.
[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 enum _CryptMsgState {
42     MsgStateInit,
43     MsgStateUpdated,
44     MsgStateFinalized
45 } CryptMsgState;
46
47 typedef struct _CryptMsgBase
48 {
49     LONG                 ref;
50     DWORD                open_flags;
51     BOOL                 streamed;
52     CMSG_STREAM_INFO     stream_info;
53     CryptMsgState        state;
54     CryptMsgCloseFunc    close;
55     CryptMsgUpdateFunc   update;
56     CryptMsgGetParamFunc get_param;
57 } CryptMsgBase;
58
59 static inline void CryptMsgBase_Init(CryptMsgBase *msg, DWORD dwFlags,
60  PCMSG_STREAM_INFO pStreamInfo, CryptMsgCloseFunc close,
61  CryptMsgGetParamFunc get_param, CryptMsgUpdateFunc update)
62 {
63     msg->ref = 1;
64     msg->open_flags = dwFlags;
65     if (pStreamInfo)
66     {
67         msg->streamed = TRUE;
68         memcpy(&msg->stream_info, pStreamInfo, sizeof(msg->stream_info));
69     }
70     else
71     {
72         msg->streamed = FALSE;
73         memset(&msg->stream_info, 0, sizeof(msg->stream_info));
74     }
75     msg->close = close;
76     msg->get_param = get_param;
77     msg->update = update;
78     msg->state = MsgStateInit;
79 }
80
81 typedef struct _CDataEncodeMsg
82 {
83     CryptMsgBase base;
84     DWORD        bare_content_len;
85     LPBYTE       bare_content;
86 } CDataEncodeMsg;
87
88 static const BYTE empty_data_content[] = { 0x04,0x00 };
89
90 static void CDataEncodeMsg_Close(HCRYPTMSG hCryptMsg)
91 {
92     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
93
94     if (msg->bare_content != empty_data_content)
95         LocalFree(msg->bare_content);
96 }
97
98 static WINAPI BOOL CRYPT_EncodeContentLength(DWORD dwCertEncodingType,
99  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
100  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
101 {
102     const CDataEncodeMsg *msg = (const CDataEncodeMsg *)pvStructInfo;
103     DWORD lenBytes;
104     BOOL ret = TRUE;
105
106     /* Trick:  report bytes needed based on total message length, even though
107      * the message isn't available yet.  The caller will use the length
108      * reported here to encode its length.
109      */
110     CRYPT_EncodeLen(msg->base.stream_info.cbContent, NULL, &lenBytes);
111     if (!pbEncoded)
112         *pcbEncoded = 1 + lenBytes + msg->base.stream_info.cbContent;
113     else
114     {
115         if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
116          pcbEncoded, 1 + lenBytes)))
117         {
118             if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
119                 pbEncoded = *(BYTE **)pbEncoded;
120             *pbEncoded++ = ASN_OCTETSTRING;
121             CRYPT_EncodeLen(msg->base.stream_info.cbContent, pbEncoded,
122              &lenBytes);
123         }
124     }
125     return ret;
126 }
127
128 static BOOL CRYPT_EncodeDataContentInfoHeader(CDataEncodeMsg *msg,
129  CRYPT_DATA_BLOB *header)
130 {
131     BOOL ret;
132
133     if (msg->base.streamed && msg->base.stream_info.cbContent == 0xffffffff)
134     {
135         FIXME("unimplemented for indefinite-length encoding\n");
136         header->cbData = 0;
137         header->pbData = NULL;
138         ret = TRUE;
139     }
140     else
141     {
142         struct AsnConstructedItem constructed = { 0, msg,
143          CRYPT_EncodeContentLength };
144         struct AsnEncodeSequenceItem items[2] = {
145          { szOID_RSA_data, CRYPT_AsnEncodeOid, 0 },
146          { &constructed,   CRYPT_AsnEncodeConstructed, 0 },
147         };
148
149         ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
150          sizeof(items) / sizeof(items[0]), CRYPT_ENCODE_ALLOC_FLAG, NULL,
151          (LPBYTE)&header->pbData, &header->cbData);
152         if (ret)
153         {
154             /* Trick:  subtract the content length from the reported length,
155              * as the actual content hasn't come yet.
156              */
157             header->cbData -= msg->base.stream_info.cbContent;
158         }
159     }
160     return ret;
161 }
162
163 static BOOL CDataEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
164  DWORD cbData, BOOL fFinal)
165 {
166     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
167     BOOL ret = FALSE;
168
169     if (msg->base.streamed)
170     {
171         __TRY
172         {
173             if (msg->base.state != MsgStateUpdated)
174             {
175                 CRYPT_DATA_BLOB header;
176
177                 ret = CRYPT_EncodeDataContentInfoHeader(msg, &header);
178                 if (ret)
179                 {
180                     ret = msg->base.stream_info.pfnStreamOutput(
181                      msg->base.stream_info.pvArg, header.pbData, header.cbData,
182                      FALSE);
183                     LocalFree(header.pbData);
184                 }
185             }
186             if (!fFinal)
187                 ret = msg->base.stream_info.pfnStreamOutput(
188                  msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
189                  FALSE);
190             else
191             {
192                 if (msg->base.stream_info.cbContent == 0xffffffff)
193                 {
194                     BYTE indefinite_trailer[6] = { 0 };
195
196                     ret = msg->base.stream_info.pfnStreamOutput(
197                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
198                      FALSE);
199                     if (ret)
200                         ret = msg->base.stream_info.pfnStreamOutput(
201                          msg->base.stream_info.pvArg, indefinite_trailer,
202                          sizeof(indefinite_trailer), TRUE);
203                 }
204                 else
205                     ret = msg->base.stream_info.pfnStreamOutput(
206                      msg->base.stream_info.pvArg, (BYTE *)pbData, cbData, TRUE);
207             }
208         }
209         __EXCEPT_PAGE_FAULT
210         {
211             SetLastError(STATUS_ACCESS_VIOLATION);
212         }
213         __ENDTRY;
214     }
215     else
216     {
217         if (!fFinal)
218         {
219             if (msg->base.open_flags & CMSG_DETACHED_FLAG)
220                 SetLastError(E_INVALIDARG);
221             else
222                 SetLastError(CRYPT_E_MSG_ERROR);
223         }
224         else
225         {
226             if (!cbData)
227                 SetLastError(E_INVALIDARG);
228             else
229             {
230                 CRYPT_DATA_BLOB blob = { cbData, (LPBYTE)pbData };
231
232                 /* non-streamed data messages don't allow non-final updates,
233                  * don't bother checking whether data already exist, they can't.
234                  */
235                 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
236                  &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &msg->bare_content,
237                  &msg->bare_content_len);
238             }
239         }
240     }
241     return ret;
242 }
243
244 static BOOL CRYPT_CopyParam(void *pvData, DWORD *pcbData, const BYTE *src,
245  DWORD len)
246 {
247     BOOL ret = TRUE;
248
249     if (!pvData)
250         *pcbData = len;
251     else if (*pcbData < len)
252     {
253         *pcbData = len;
254         SetLastError(ERROR_MORE_DATA);
255         ret = FALSE;
256     }
257     else
258     {
259         *pcbData = len;
260         memcpy(pvData, src, len);
261     }
262     return ret;
263 }
264
265 static BOOL CDataEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
266  DWORD dwIndex, void *pvData, DWORD *pcbData)
267 {
268     CDataEncodeMsg *msg = (CDataEncodeMsg *)hCryptMsg;
269     BOOL ret = FALSE;
270
271     switch (dwParamType)
272     {
273     case CMSG_CONTENT_PARAM:
274         if (msg->base.streamed)
275             SetLastError(E_INVALIDARG);
276         else
277         {
278             CRYPT_CONTENT_INFO info;
279             char rsa_data[] = "1.2.840.113549.1.7.1";
280
281             info.pszObjId = rsa_data;
282             info.Content.cbData = msg->bare_content_len;
283             info.Content.pbData = msg->bare_content;
284             ret = CryptEncodeObject(X509_ASN_ENCODING, PKCS_CONTENT_INFO, &info,
285              pvData, pcbData);
286         }
287         break;
288     case CMSG_BARE_CONTENT_PARAM:
289         if (msg->base.streamed)
290             SetLastError(E_INVALIDARG);
291         else
292             ret = CRYPT_CopyParam(pvData, pcbData, msg->bare_content,
293              msg->bare_content_len);
294         break;
295     default:
296         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
297     }
298     return ret;
299 }
300
301 static HCRYPTMSG CDataEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
302  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
303 {
304     CDataEncodeMsg *msg;
305
306     if (pvMsgEncodeInfo)
307     {
308         SetLastError(E_INVALIDARG);
309         return NULL;
310     }
311     msg = CryptMemAlloc(sizeof(CDataEncodeMsg));
312     if (msg)
313     {
314         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
315          CDataEncodeMsg_Close, CDataEncodeMsg_GetParam, CDataEncodeMsg_Update);
316         msg->bare_content_len = sizeof(empty_data_content);
317         msg->bare_content = (LPBYTE)empty_data_content;
318     }
319     return (HCRYPTMSG)msg;
320 }
321
322 typedef struct _CHashEncodeMsg
323 {
324     CryptMsgBase    base;
325     HCRYPTPROV      prov;
326     HCRYPTHASH      hash;
327     CRYPT_DATA_BLOB data;
328 } CHashEncodeMsg;
329
330 static void CHashEncodeMsg_Close(HCRYPTMSG hCryptMsg)
331 {
332     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
333
334     CryptMemFree(msg->data.pbData);
335     CryptDestroyHash(msg->hash);
336     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
337         CryptReleaseContext(msg->prov, 0);
338 }
339
340 static BOOL CRYPT_EncodePKCSDigestedData(CHashEncodeMsg *msg, void *pvData,
341  DWORD *pcbData)
342 {
343     BOOL ret;
344     ALG_ID algID;
345     DWORD size = sizeof(algID);
346
347     ret = CryptGetHashParam(msg->hash, HP_ALGID, (BYTE *)&algID, &size, 0);
348     if (ret)
349     {
350         CRYPT_DIGESTED_DATA digestedData = { 0 };
351         char oid_rsa_data[] = szOID_RSA_data;
352
353         digestedData.version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
354         digestedData.DigestAlgorithm.pszObjId = (LPSTR)CertAlgIdToOID(algID);
355         /* FIXME: what about digestedData.DigestAlgorithm.Parameters? */
356         /* Quirk:  OID is only encoded messages if an update has happened */
357         if (msg->base.state != MsgStateInit)
358             digestedData.ContentInfo.pszObjId = oid_rsa_data;
359         if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->data.cbData)
360         {
361             ret = CRYPT_AsnEncodeOctets(0, NULL, &msg->data,
362              CRYPT_ENCODE_ALLOC_FLAG, NULL,
363              (LPBYTE)&digestedData.ContentInfo.Content.pbData,
364              &digestedData.ContentInfo.Content.cbData);
365         }
366         if (msg->base.state == MsgStateFinalized)
367         {
368             size = sizeof(DWORD);
369             ret = CryptGetHashParam(msg->hash, HP_HASHSIZE,
370              (LPBYTE)&digestedData.hash.cbData, &size, 0);
371             if (ret)
372             {
373                 digestedData.hash.pbData = CryptMemAlloc(
374                  digestedData.hash.cbData);
375                 ret = CryptGetHashParam(msg->hash, HP_HASHVAL,
376                  digestedData.hash.pbData, &digestedData.hash.cbData, 0);
377             }
378         }
379         if (ret)
380             ret = CRYPT_AsnEncodePKCSDigestedData(&digestedData, pvData,
381              pcbData);
382         CryptMemFree(digestedData.hash.pbData);
383         LocalFree(digestedData.ContentInfo.Content.pbData);
384     }
385     return ret;
386 }
387
388 static BOOL CHashEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
389  DWORD dwIndex, void *pvData, DWORD *pcbData)
390 {
391     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
392     BOOL ret = FALSE;
393
394     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
395      pvData, pcbData);
396
397     switch (dwParamType)
398     {
399     case CMSG_BARE_CONTENT_PARAM:
400         if (msg->base.streamed)
401             SetLastError(E_INVALIDARG);
402         else
403             ret = CRYPT_EncodePKCSDigestedData(msg, pvData, pcbData);
404         break;
405     case CMSG_CONTENT_PARAM:
406     {
407         CRYPT_CONTENT_INFO info;
408
409         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
410          &info.Content.cbData);
411         if (ret)
412         {
413             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
414             if (info.Content.pbData)
415             {
416                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
417                  info.Content.pbData, &info.Content.cbData);
418                 if (ret)
419                 {
420                     char oid_rsa_hashed[] = szOID_RSA_hashedData;
421
422                     info.pszObjId = oid_rsa_hashed;
423                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
424                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
425                 }
426                 CryptMemFree(info.Content.pbData);
427             }
428             else
429                 ret = FALSE;
430         }
431         break;
432     }
433     case CMSG_COMPUTED_HASH_PARAM:
434         ret = CryptGetHashParam(msg->hash, HP_HASHVAL, (BYTE *)pvData, pcbData,
435          0);
436         break;
437     case CMSG_VERSION_PARAM:
438         if (msg->base.state != MsgStateFinalized)
439             SetLastError(CRYPT_E_MSG_ERROR);
440         else
441         {
442             DWORD version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
443
444             /* Since the data are always encoded as octets, the version is
445              * always 0 (see rfc3852, section 7)
446              */
447             ret = CRYPT_CopyParam(pvData, pcbData, (const BYTE *)&version,
448              sizeof(version));
449         }
450         break;
451     default:
452         ret = FALSE;
453     }
454     return ret;
455 }
456
457 static BOOL CHashEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
458  DWORD cbData, BOOL fFinal)
459 {
460     CHashEncodeMsg *msg = (CHashEncodeMsg *)hCryptMsg;
461     BOOL ret = FALSE;
462
463     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
464
465     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
466     {
467         /* Doesn't do much, as stream output is never called, and you
468          * can't get the content.
469          */
470         ret = CryptHashData(msg->hash, pbData, cbData, 0);
471     }
472     else
473     {
474         if (!fFinal)
475             SetLastError(CRYPT_E_MSG_ERROR);
476         else
477         {
478             ret = CryptHashData(msg->hash, pbData, cbData, 0);
479             if (ret)
480             {
481                 msg->data.pbData = CryptMemAlloc(cbData);
482                 if (msg->data.pbData)
483                 {
484                     memcpy(msg->data.pbData + msg->data.cbData, pbData, cbData);
485                     msg->data.cbData += cbData;
486                 }
487                 else
488                     ret = FALSE;
489             }
490         }
491     }
492     return ret;
493 }
494
495 static HCRYPTMSG CHashEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
496  LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
497 {
498     CHashEncodeMsg *msg;
499     const CMSG_HASHED_ENCODE_INFO *info =
500      (const CMSG_HASHED_ENCODE_INFO *)pvMsgEncodeInfo;
501     HCRYPTPROV prov;
502     ALG_ID algID;
503
504     if (info->cbSize != sizeof(CMSG_HASHED_ENCODE_INFO))
505     {
506         SetLastError(E_INVALIDARG);
507         return NULL;
508     }
509     if (!(algID = CertOIDToAlgId(info->HashAlgorithm.pszObjId)))
510     {
511         SetLastError(CRYPT_E_UNKNOWN_ALGO);
512         return NULL;
513     }
514     if (info->hCryptProv)
515         prov = info->hCryptProv;
516     else
517     {
518         prov = CRYPT_GetDefaultProvider();
519         dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
520     }
521     msg = CryptMemAlloc(sizeof(CHashEncodeMsg));
522     if (msg)
523     {
524         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
525          CHashEncodeMsg_Close, CHashEncodeMsg_GetParam, CHashEncodeMsg_Update);
526         msg->prov = prov;
527         msg->data.cbData = 0;
528         msg->data.pbData = NULL;
529         if (!CryptCreateHash(prov, algID, 0, 0, &msg->hash))
530         {
531             CryptMsgClose(msg);
532             msg = NULL;
533         }
534     }
535     return (HCRYPTMSG)msg;
536 }
537
538 typedef struct _CMSG_SIGNER_ENCODE_INFO_WITH_CMS
539 {
540     DWORD                      cbSize;
541     PCERT_INFO                 pCertInfo;
542     HCRYPTPROV                 hCryptProv;
543     DWORD                      dwKeySpec;
544     CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
545     void                      *pvHashAuxInfo;
546     DWORD                      cAuthAttr;
547     PCRYPT_ATTRIBUTE           rgAuthAttr;
548     DWORD                      cUnauthAttr;
549     PCRYPT_ATTRIBUTE           rgUnauthAttr;
550     CERT_ID                    SignerId;
551     CRYPT_ALGORITHM_IDENTIFIER HashEncryptionAlgorithm;
552     void                      *pvHashEncryptionAuxInfo;
553 } CMSG_SIGNER_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNER_ENCODE_INFO_WITH_CMS;
554
555 typedef struct _CMSG_SIGNED_ENCODE_INFO_WITH_CMS
556 {
557     DWORD                             cbSize;
558     DWORD                             cSigners;
559     PCMSG_SIGNER_ENCODE_INFO_WITH_CMS rgSigners;
560     DWORD                             cCertEncoded;
561     PCERT_BLOB                        rgCertEncoded;
562     DWORD                             cCrlEncoded;
563     PCRL_BLOB                         rgCrlEncoded;
564     DWORD                             cAttrCertEncoded;
565     PCERT_BLOB                        rgAttrCertEncoded;
566 } CMSG_SIGNED_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNED_ENCODE_INFO_WITH_CMS;
567
568 static BOOL CRYPT_IsValidSigner(CMSG_SIGNER_ENCODE_INFO_WITH_CMS *signer)
569 {
570     if (signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO) &&
571      signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
572     {
573         SetLastError(E_INVALIDARG);
574         return FALSE;
575     }
576     if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
577     {
578         FIXME("CMSG_SIGNER_ENCODE_INFO with CMS fields unsupported\n");
579         return FALSE;
580     }
581     if (!signer->pCertInfo->SerialNumber.cbData)
582     {
583         SetLastError(E_INVALIDARG);
584         return FALSE;
585     }
586     if (!signer->pCertInfo->Issuer.cbData)
587     {
588         SetLastError(E_INVALIDARG);
589         return FALSE;
590     }
591     if (!signer->hCryptProv)
592     {
593         SetLastError(E_INVALIDARG);
594         return FALSE;
595     }
596     if (!CertOIDToAlgId(signer->HashAlgorithm.pszObjId))
597     {
598         SetLastError(CRYPT_E_UNKNOWN_ALGO);
599         return FALSE;
600     }
601     return TRUE;
602 }
603
604 typedef struct _CSignerHandles
605 {
606     HCRYPTPROV       prov;
607     HCRYPTHASH       hash;
608     HCRYPTKEY        key;
609 } CSignerHandles;
610
611 static BOOL CRYPT_CopyBlob(CRYPT_DATA_BLOB *out, const CRYPT_DATA_BLOB *in)
612 {
613     BOOL ret = TRUE;
614
615     out->cbData = in->cbData;
616     if (out->cbData)
617     {
618         out->pbData = CryptMemAlloc(out->cbData);
619         if (out->pbData)
620             memcpy(out->pbData, in->pbData, out->cbData);
621         else
622             ret = FALSE;
623     }
624     else
625         out->pbData = NULL;
626     return ret;
627 }
628
629 typedef struct _BlobArray
630 {
631     DWORD            cBlobs;
632     PCRYPT_DATA_BLOB blobs;
633 } BlobArray;
634
635 static BOOL CRYPT_CopyBlobArray(BlobArray *out, const BlobArray *in)
636 {
637     BOOL ret = TRUE;
638
639     out->cBlobs = in->cBlobs;
640     if (out->cBlobs)
641     {
642         out->blobs = CryptMemAlloc(out->cBlobs * sizeof(CRYPT_DATA_BLOB));
643         if (out->blobs)
644         {
645             DWORD i;
646
647             memset(out->blobs, 0, out->cBlobs * sizeof(CRYPT_DATA_BLOB));
648             for (i = 0; ret && i < out->cBlobs; i++)
649                 ret = CRYPT_CopyBlob(&out->blobs[i], &in->blobs[i]);
650         }
651         else
652             ret = FALSE;
653     }
654     return ret;
655 }
656
657 static void CRYPT_FreeBlobArray(BlobArray *array)
658 {
659     DWORD i;
660
661     for (i = 0; i < array->cBlobs; i++)
662         CryptMemFree(array->blobs[i].pbData);
663     CryptMemFree(array->blobs);
664 }
665
666 static BOOL CRYPT_CopyAttribute(CRYPT_ATTRIBUTE *out, const CRYPT_ATTRIBUTE *in)
667 {
668     /* Assumption:  algorithm IDs will point to static strings, not stack-based
669      * ones, so copying the pointer values is safe.
670      */
671     out->pszObjId = in->pszObjId;
672     return CRYPT_CopyBlobArray((BlobArray *)&out->cValue,
673      (const BlobArray *)&in->cValue);
674 }
675
676 static BOOL CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
677  const CRYPT_ATTRIBUTES *in)
678 {
679     BOOL ret = TRUE;
680
681     out->cAttr = in->cAttr;
682     if (out->cAttr)
683     {
684         out->rgAttr = CryptMemAlloc(out->cAttr * sizeof(CRYPT_ATTRIBUTE));
685         if (out->rgAttr)
686         {
687             DWORD i;
688
689             memset(out->rgAttr, 0, out->cAttr * sizeof(CRYPT_ATTRIBUTE));
690             for (i = 0; ret && i < out->cAttr; i++)
691                 ret = CRYPT_CopyAttribute(&out->rgAttr[i], &in->rgAttr[i]);
692         }
693         else
694             ret = FALSE;
695     }
696     else
697         out->rgAttr = NULL;
698     return ret;
699 }
700
701 /* Constructs both a CSignerHandles and a CMSG_SIGNER_INFO from a
702  * CMSG_SIGNER_ENCODE_INFO_WITH_CMS.
703  */
704 static BOOL CSignerInfo_Construct(CSignerHandles *handles,
705  CMSG_SIGNER_INFO *info, CMSG_SIGNER_ENCODE_INFO_WITH_CMS *in, DWORD open_flags)
706 {
707     ALG_ID algID;
708     BOOL ret;
709
710     handles->prov = in->hCryptProv;
711     if (!(open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG))
712         CryptContextAddRef(handles->prov, NULL, 0);
713     algID = CertOIDToAlgId(in->HashAlgorithm.pszObjId);
714     ret = CryptCreateHash(handles->prov, algID, 0, 0, &handles->hash);
715     if (ret)
716     {
717         /* Note: needs to change if CMS fields are supported */
718         info->dwVersion = CMSG_SIGNER_INFO_V1;
719         ret = CRYPT_CopyBlob(&info->Issuer, &in->pCertInfo->Issuer);
720         if (ret)
721             ret = CRYPT_CopyBlob(&info->SerialNumber,
722              &in->pCertInfo->SerialNumber);
723         /* Assumption:  algorithm IDs will point to static strings, not
724          * stack-based ones, so copying the pointer values is safe.
725          */
726         info->HashAlgorithm.pszObjId = in->HashAlgorithm.pszObjId;
727         if (ret)
728             ret = CRYPT_CopyBlob(&info->HashAlgorithm.Parameters,
729              &in->HashAlgorithm.Parameters);
730         memset(&info->HashEncryptionAlgorithm, 0,
731          sizeof(info->HashEncryptionAlgorithm));
732         if (ret)
733             ret = CRYPT_CopyAttributes(&info->AuthAttrs,
734              (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
735         if (ret)
736             ret = CRYPT_CopyAttributes(&info->UnauthAttrs,
737              (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
738     }
739     return ret;
740 }
741
742 static void CSignerInfo_Free(CMSG_SIGNER_INFO *info)
743 {
744     DWORD i, j;
745
746     CryptMemFree(info->Issuer.pbData);
747     CryptMemFree(info->SerialNumber.pbData);
748     CryptMemFree(info->HashAlgorithm.Parameters.pbData);
749     CryptMemFree(info->EncryptedHash.pbData);
750     for (i = 0; i < info->AuthAttrs.cAttr; i++)
751     {
752         for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
753             CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
754         CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
755     }
756     CryptMemFree(info->AuthAttrs.rgAttr);
757     for (i = 0; i < info->UnauthAttrs.cAttr; i++)
758     {
759         for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
760             CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
761         CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
762     }
763     CryptMemFree(info->UnauthAttrs.rgAttr);
764 }
765
766 typedef struct _CSignedEncodeMsg
767 {
768     CryptMsgBase      base;
769     CRYPT_DATA_BLOB   data;
770     CRYPT_SIGNED_INFO info;
771     CSignerHandles   *signerHandles;
772 } CSignedEncodeMsg;
773
774 static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
775 {
776     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
777     DWORD i;
778
779     CryptMemFree(msg->data.pbData);
780     CRYPT_FreeBlobArray((BlobArray *)&msg->info.cCertEncoded);
781     CRYPT_FreeBlobArray((BlobArray *)&msg->info.cCrlEncoded);
782     for (i = 0; i < msg->info.cSignerInfo; i++)
783     {
784         CSignerInfo_Free(&msg->info.rgSignerInfo[i]);
785         CryptDestroyKey(msg->signerHandles[i].key);
786         CryptDestroyHash(msg->signerHandles[i].hash);
787         CryptReleaseContext(msg->signerHandles[i].prov, 0);
788     }
789     CryptMemFree(msg->signerHandles);
790     CryptMemFree(msg->info.rgSignerInfo);
791 }
792
793 static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
794  DWORD dwIndex, void *pvData, DWORD *pcbData)
795 {
796     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
797     BOOL ret = FALSE;
798
799     switch (dwParamType)
800     {
801     case CMSG_CONTENT_PARAM:
802     {
803         CRYPT_CONTENT_INFO info;
804
805         ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
806          &info.Content.cbData);
807         if (ret)
808         {
809             info.Content.pbData = CryptMemAlloc(info.Content.cbData);
810             if (info.Content.pbData)
811             {
812                 ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
813                  info.Content.pbData, &info.Content.cbData);
814                 if (ret)
815                 {
816                     char oid_rsa_signed[] = szOID_RSA_signedData;
817
818                     info.pszObjId = oid_rsa_signed;
819                     ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
820                      PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
821                 }
822                 CryptMemFree(info.Content.pbData);
823             }
824             else
825                 ret = FALSE;
826         }
827         break;
828     }
829     case CMSG_BARE_CONTENT_PARAM:
830     {
831         CRYPT_SIGNED_INFO info;
832         char oid_rsa_data[] = szOID_RSA_data;
833
834         memcpy(&info, &msg->info, sizeof(info));
835         /* Quirk:  OID is only encoded messages if an update has happened */
836         if (msg->base.state != MsgStateInit)
837             info.content.pszObjId = oid_rsa_data;
838         else
839             info.content.pszObjId = NULL;
840         if (msg->data.cbData)
841         {
842             CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
843
844             ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
845              &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
846              &info.content.Content.pbData, &info.content.Content.cbData);
847         }
848         else
849         {
850             info.content.Content.cbData = 0;
851             info.content.Content.pbData = NULL;
852             ret = TRUE;
853         }
854         if (ret)
855         {
856             ret = CRYPT_AsnEncodePKCSSignedInfo(&info, pvData, pcbData);
857             LocalFree(info.content.Content.pbData);
858         }
859         break;
860     }
861     case CMSG_COMPUTED_HASH_PARAM:
862         if (dwIndex >= msg->info.cSignerInfo)
863             SetLastError(CRYPT_E_INVALID_INDEX);
864         else
865             ret = CryptGetHashParam(msg->signerHandles[dwIndex].hash,
866              HP_HASHVAL, pvData, pcbData, 0);
867         break;
868     case CMSG_ENCODED_SIGNER:
869         if (dwIndex >= msg->info.cSignerInfo)
870             SetLastError(CRYPT_E_INVALID_INDEX);
871         else
872             ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
873              PKCS7_SIGNER_INFO, &msg->info.rgSignerInfo[dwIndex], 0, NULL,
874              pvData, pcbData);
875         break;
876     case CMSG_VERSION_PARAM:
877         ret = CRYPT_CopyParam(pvData, pcbData, (const BYTE *)&msg->info.version,
878          sizeof(msg->info.version));
879         break;
880     default:
881         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
882     }
883     return ret;
884 }
885
886 static BOOL CSignedEncodeMsg_UpdateHash(CSignedEncodeMsg *msg,
887  const BYTE *pbData, DWORD cbData)
888 {
889     DWORD i;
890     BOOL ret = TRUE;
891
892     TRACE("(%p, %p, %d)\n", msg, pbData, cbData);
893
894     for (i = 0; ret && i < msg->info.cSignerInfo; i++)
895         ret = CryptHashData(msg->signerHandles[i].hash, pbData, cbData, 0);
896     return ret;
897 }
898
899 static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
900 {
901     DWORD i;
902     BYTE tmp;
903
904     for (i = 0; i < hash->cbData / 2; i++)
905     {
906         tmp = hash->pbData[hash->cbData - i - 1];
907         hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
908         hash->pbData[i] = tmp;
909     }
910 }
911
912 static BOOL CSignedEncodeMsg_Sign(CSignedEncodeMsg *msg)
913 {
914     DWORD i;
915     BOOL ret = TRUE;
916
917     TRACE("(%p)\n", msg);
918
919     for (i = 0; ret && i < msg->info.cSignerInfo; i++)
920     {
921         ret = CryptSignHashW(msg->signerHandles[i].hash, AT_SIGNATURE, NULL, 0,
922          NULL, &msg->info.rgSignerInfo[i].EncryptedHash.cbData);
923         if (ret)
924         {
925             msg->info.rgSignerInfo[i].EncryptedHash.pbData =
926              CryptMemAlloc(msg->info.rgSignerInfo[i].EncryptedHash.cbData);
927             if (msg->info.rgSignerInfo[i].EncryptedHash.pbData)
928             {
929                 ret = CryptSignHashW(msg->signerHandles[i].hash, AT_SIGNATURE,
930                  NULL, 0, msg->info.rgSignerInfo[i].EncryptedHash.pbData,
931                  &msg->info.rgSignerInfo[i].EncryptedHash.cbData);
932                 if (ret)
933                     CRYPT_ReverseBytes(&msg->info.rgSignerInfo[i].EncryptedHash);
934             }
935             else
936                 ret = FALSE;
937         }
938     }
939     return ret;
940 }
941
942 static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
943  DWORD cbData, BOOL fFinal)
944 {
945     CSignedEncodeMsg *msg = (CSignedEncodeMsg *)hCryptMsg;
946     BOOL ret = FALSE;
947
948     if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
949     {
950         ret = CSignedEncodeMsg_UpdateHash(msg, pbData, cbData);
951         /* FIXME: hash authenticated attributes on final update */
952         if (ret && fFinal)
953             ret = CSignedEncodeMsg_Sign(msg);
954         if (msg->base.streamed)
955             FIXME("streamed partial stub\n");
956     }
957     else
958     {
959         if (!fFinal)
960             SetLastError(CRYPT_E_MSG_ERROR);
961         else
962         {
963             if (cbData)
964             {
965                 msg->data.pbData = CryptMemAlloc(cbData);
966                 if (msg->data.pbData)
967                 {
968                     memcpy(msg->data.pbData, pbData, cbData);
969                     msg->data.cbData = cbData;
970                     ret = TRUE;
971                 }
972             }
973             else
974                 ret = TRUE;
975             if (ret)
976                 ret = CSignedEncodeMsg_UpdateHash(msg, pbData, cbData);
977             /* FIXME: hash authenticated attributes */
978             if (ret)
979                 ret = CSignedEncodeMsg_Sign(msg);
980         }
981     }
982     return ret;
983 }
984
985 static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
986  const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
987  PCMSG_STREAM_INFO pStreamInfo)
988 {
989     const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info =
990      (const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *)pvMsgEncodeInfo;
991     DWORD i;
992     CSignedEncodeMsg *msg;
993
994     if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
995      info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
996     {
997         SetLastError(E_INVALIDARG);
998         return NULL;
999     }
1000     if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
1001     {
1002         FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
1003         return NULL;
1004     }
1005     for (i = 0; i < info->cSigners; i++)
1006         if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
1007             return NULL;
1008     msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
1009     if (msg)
1010     {
1011         BOOL ret = TRUE;
1012
1013         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1014          CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1015          CSignedEncodeMsg_Update);
1016         msg->data.cbData = 0;
1017         msg->data.pbData = NULL;
1018         memset(&msg->info, 0, sizeof(msg->info));
1019         msg->info.version = CMSG_SIGNED_DATA_V1;
1020         if (info->cSigners)
1021         {
1022             msg->signerHandles =
1023              CryptMemAlloc(info->cSigners * sizeof(CSignerHandles));
1024             if (msg->signerHandles)
1025                 msg->info.rgSignerInfo =
1026                  CryptMemAlloc(info->cSigners * sizeof(CMSG_SIGNER_INFO));
1027             else
1028             {
1029                 ret = FALSE;
1030                 msg->info.rgSignerInfo = NULL;
1031             }
1032             if (msg->info.rgSignerInfo)
1033             {
1034                 msg->info.cSignerInfo = info->cSigners;
1035                 memset(msg->signerHandles, 0,
1036                  msg->info.cSignerInfo * sizeof(CSignerHandles));
1037                 memset(msg->info.rgSignerInfo, 0,
1038                  msg->info.cSignerInfo * sizeof(CMSG_SIGNER_INFO));
1039                 for (i = 0; ret && i < msg->info.cSignerInfo; i++)
1040                     ret = CSignerInfo_Construct(&msg->signerHandles[i],
1041                      &msg->info.rgSignerInfo[i], &info->rgSigners[i], dwFlags);
1042             }
1043             else
1044                 ret = FALSE;
1045         }
1046         if (ret)
1047             ret = CRYPT_CopyBlobArray((BlobArray *)&msg->info.cCertEncoded,
1048              (const BlobArray *)&info->cCertEncoded);
1049         if (ret)
1050             ret = CRYPT_CopyBlobArray((BlobArray *)&msg->info.cCrlEncoded,
1051              (const BlobArray *)&info->cCrlEncoded);
1052         if (!ret)
1053         {
1054             CSignedEncodeMsg_Close(msg);
1055             msg = NULL;
1056         }
1057     }
1058     return msg;
1059 }
1060
1061 static inline const char *MSG_TYPE_STR(DWORD type)
1062 {
1063     switch (type)
1064     {
1065 #define _x(x) case (x): return #x
1066         _x(CMSG_DATA);
1067         _x(CMSG_SIGNED);
1068         _x(CMSG_ENVELOPED);
1069         _x(CMSG_SIGNED_AND_ENVELOPED);
1070         _x(CMSG_HASHED);
1071         _x(CMSG_ENCRYPTED);
1072 #undef _x
1073         default:
1074             return wine_dbg_sprintf("unknown (%d)", type);
1075     }
1076 }
1077
1078 HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
1079  DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
1080  PCMSG_STREAM_INFO pStreamInfo)
1081 {
1082     HCRYPTMSG msg = NULL;
1083
1084     TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
1085      dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
1086
1087     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
1088     {
1089         SetLastError(E_INVALIDARG);
1090         return NULL;
1091     }
1092     switch (dwMsgType)
1093     {
1094     case CMSG_DATA:
1095         msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1096          pszInnerContentObjID, pStreamInfo);
1097         break;
1098     case CMSG_HASHED:
1099         msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1100          pszInnerContentObjID, pStreamInfo);
1101         break;
1102     case CMSG_SIGNED:
1103         msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
1104          pszInnerContentObjID, pStreamInfo);
1105         break;
1106     case CMSG_ENVELOPED:
1107         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(dwMsgType));
1108         break;
1109     case CMSG_SIGNED_AND_ENVELOPED:
1110     case CMSG_ENCRYPTED:
1111         /* defined but invalid, fall through */
1112     default:
1113         SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1114     }
1115     return msg;
1116 }
1117
1118 typedef struct _CDecodeMsg
1119 {
1120     CryptMsgBase           base;
1121     DWORD                  type;
1122     HCRYPTPROV             crypt_prov;
1123     HCRYPTHASH             hash;
1124     CRYPT_DATA_BLOB        msg_data;
1125     PCONTEXT_PROPERTY_LIST properties;
1126 } CDecodeMsg;
1127
1128 static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
1129 {
1130     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1131
1132     if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
1133         CryptReleaseContext(msg->crypt_prov, 0);
1134     CryptDestroyHash(msg->hash);
1135     CryptMemFree(msg->msg_data.pbData);
1136     ContextPropertyList_Free(msg->properties);
1137 }
1138
1139 static BOOL CDecodeMsg_CopyData(CDecodeMsg *msg, const BYTE *pbData,
1140  DWORD cbData)
1141 {
1142     BOOL ret = TRUE;
1143
1144     if (cbData)
1145     {
1146         if (msg->msg_data.cbData)
1147             msg->msg_data.pbData = CryptMemRealloc(msg->msg_data.pbData,
1148              msg->msg_data.cbData + cbData);
1149         else
1150             msg->msg_data.pbData = CryptMemAlloc(cbData);
1151         if (msg->msg_data.pbData)
1152         {
1153             memcpy(msg->msg_data.pbData + msg->msg_data.cbData, pbData, cbData);
1154             msg->msg_data.cbData += cbData;
1155         }
1156         else
1157             ret = FALSE;
1158     }
1159     return ret;
1160 }
1161
1162 static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
1163 {
1164     BOOL ret;
1165     CRYPT_DATA_BLOB *data;
1166     DWORD size;
1167
1168     ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1169      blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, (LPBYTE)&data,
1170      &size);
1171     if (ret)
1172     {
1173         ret = ContextPropertyList_SetProperty(msg->properties,
1174          CMSG_CONTENT_PARAM, data->pbData, data->cbData);
1175         LocalFree(data);
1176     }
1177     return ret;
1178 }
1179
1180 static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
1181  const CRYPT_ALGORITHM_IDENTIFIER *id)
1182 {
1183     static const BYTE nullParams[] = { ASN_NULL, 0 };
1184     CRYPT_ALGORITHM_IDENTIFIER *copy;
1185     DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);
1186
1187     /* Linearize algorithm id */
1188     len += strlen(id->pszObjId) + 1;
1189     len += id->Parameters.cbData;
1190     copy = CryptMemAlloc(len);
1191     if (copy)
1192     {
1193         copy->pszObjId =
1194          (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1195         strcpy(copy->pszObjId, id->pszObjId);
1196         copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
1197          + 1;
1198         /* Trick:  omit NULL parameters */
1199         if (id->Parameters.cbData == sizeof(nullParams) &&
1200          !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
1201         {
1202             copy->Parameters.cbData = 0;
1203             len -= sizeof(nullParams);
1204         }
1205         else
1206             copy->Parameters.cbData = id->Parameters.cbData;
1207         if (copy->Parameters.cbData)
1208             memcpy(copy->Parameters.pbData, id->Parameters.pbData,
1209              id->Parameters.cbData);
1210         ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
1211          len);
1212         CryptMemFree(copy);
1213     }
1214 }
1215
1216 static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
1217 {
1218     id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
1219     id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
1220 }
1221
1222 static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
1223  CRYPT_DER_BLOB *blob)
1224 {
1225     BOOL ret;
1226     CRYPT_DIGESTED_DATA *digestedData;
1227     DWORD size;
1228
1229     ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
1230      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
1231      &size);
1232     if (ret)
1233     {
1234         ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
1235          (const BYTE *)&digestedData->version, sizeof(digestedData->version));
1236         CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
1237          &digestedData->DigestAlgorithm);
1238         ContextPropertyList_SetProperty(msg->properties,
1239          CMSG_INNER_CONTENT_TYPE_PARAM,
1240          (const BYTE *)digestedData->ContentInfo.pszObjId,
1241          digestedData->ContentInfo.pszObjId ?
1242          strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
1243         if (digestedData->ContentInfo.Content.cbData)
1244             CDecodeMsg_DecodeDataContent(msg,
1245              &digestedData->ContentInfo.Content);
1246         else
1247             ContextPropertyList_SetProperty(msg->properties,
1248              CMSG_CONTENT_PARAM, NULL, 0);
1249         ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
1250          digestedData->hash.pbData, digestedData->hash.cbData);
1251         LocalFree(digestedData);
1252     }
1253     return ret;
1254 }
1255
1256 static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
1257  CRYPT_DER_BLOB *blob)
1258 {
1259     BOOL ret;
1260     CRYPT_SIGNED_INFO *signedInfo;
1261     DWORD size;
1262
1263     ret = CRYPT_AsnDecodePKCSSignedInfo(blob->pbData, blob->cbData,
1264      CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
1265      &size);
1266     if (ret)
1267     {
1268         FIXME("store properties in message\n");
1269         LocalFree(signedInfo);
1270     }
1271     return ret;
1272 }
1273 /* Decodes the content in blob as the type given, and updates the value
1274  * (type, parameters, etc.) of msg based on what blob contains.
1275  * It doesn't just use msg's type, to allow a recursive call from an implicitly
1276  * typed message once the outer content info has been decoded.
1277  */
1278 static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob,
1279  DWORD type)
1280 {
1281     BOOL ret;
1282
1283     switch (type)
1284     {
1285     case CMSG_DATA:
1286         if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
1287             msg->type = CMSG_DATA;
1288         break;
1289     case CMSG_HASHED:
1290         if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
1291             msg->type = CMSG_HASHED;
1292         break;
1293     case CMSG_ENVELOPED:
1294         FIXME("unimplemented for type %s\n", MSG_TYPE_STR(type));
1295         ret = TRUE;
1296         break;
1297     case CMSG_SIGNED:
1298         if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
1299             msg->type = CMSG_HASHED;
1300         break;
1301     default:
1302     {
1303         CRYPT_CONTENT_INFO *info;
1304         DWORD size;
1305
1306         ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
1307          msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
1308          NULL, (LPBYTE)&info, &size);
1309         if (ret)
1310         {
1311             if (!strcmp(info->pszObjId, szOID_RSA_data))
1312                 ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
1313             else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
1314                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1315                  CMSG_HASHED);
1316             else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
1317                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1318                  CMSG_ENVELOPED);
1319             else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
1320                 ret = CDecodeMsg_DecodeContent(msg, &info->Content,
1321                  CMSG_SIGNED);
1322             else
1323             {
1324                 SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1325                 ret = FALSE;
1326             }
1327             LocalFree(info);
1328         }
1329     }
1330     }
1331     return ret;
1332 }
1333
1334 static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1335  DWORD cbData, BOOL fFinal)
1336 {
1337     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1338     BOOL ret = FALSE;
1339
1340     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
1341
1342     if (msg->base.streamed)
1343     {
1344         ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1345         FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
1346          cbData, fFinal);
1347     }
1348     else
1349     {
1350         if (!fFinal)
1351             SetLastError(CRYPT_E_MSG_ERROR);
1352         else
1353         {
1354             ret = CDecodeMsg_CopyData(msg, pbData, cbData);
1355             if (ret)
1356                 ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
1357
1358         }
1359     }
1360     return ret;
1361 }
1362
1363 static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1364  DWORD dwIndex, void *pvData, DWORD *pcbData)
1365 {
1366     CDecodeMsg *msg = (CDecodeMsg *)hCryptMsg;
1367     BOOL ret = FALSE;
1368
1369     switch (dwParamType)
1370     {
1371     case CMSG_TYPE_PARAM:
1372         ret = CRYPT_CopyParam(pvData, pcbData, (const BYTE *)&msg->type,
1373          sizeof(msg->type));
1374         break;
1375     case CMSG_HASH_ALGORITHM_PARAM:
1376     {
1377         CRYPT_DATA_BLOB blob;
1378
1379         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1380          &blob);
1381         if (ret)
1382         {
1383             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1384             if (ret && pvData)
1385                 CRYPT_FixUpAlgorithmID((CRYPT_ALGORITHM_IDENTIFIER *)pvData);
1386         }
1387         else
1388             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1389         break;
1390     }
1391     case CMSG_COMPUTED_HASH_PARAM:
1392         if (!msg->hash)
1393         {
1394             CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
1395             DWORD size = 0;
1396             ALG_ID algID = 0;
1397
1398             CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
1399             hashAlgoID = CryptMemAlloc(size);
1400             ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0,
1401              hashAlgoID, &size);
1402             if (ret)
1403                 algID = CertOIDToAlgId(hashAlgoID->pszObjId);
1404             ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->hash);
1405             if (ret)
1406             {
1407                 CRYPT_DATA_BLOB content;
1408
1409                 ret = ContextPropertyList_FindProperty(msg->properties,
1410                  CMSG_CONTENT_PARAM, &content);
1411                 if (ret)
1412                     ret = CryptHashData(msg->hash, content.pbData,
1413                      content.cbData, 0);
1414             }
1415             CryptMemFree(hashAlgoID);
1416         }
1417         else
1418             ret = TRUE;
1419         if (ret)
1420             ret = CryptGetHashParam(msg->hash, HP_HASHVAL, pvData, pcbData, 0);
1421         break;
1422     default:
1423     {
1424         CRYPT_DATA_BLOB blob;
1425
1426         ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
1427          &blob);
1428         if (ret)
1429             ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1430         else
1431             SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1432     }
1433     }
1434     return ret;
1435 }
1436
1437 HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
1438  DWORD dwMsgType, HCRYPTPROV hCryptProv, PCERT_INFO pRecipientInfo,
1439  PCMSG_STREAM_INFO pStreamInfo)
1440 {
1441     CDecodeMsg *msg;
1442
1443     TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
1444      dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
1445
1446     if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
1447     {
1448         SetLastError(E_INVALIDARG);
1449         return NULL;
1450     }
1451     msg = CryptMemAlloc(sizeof(CDecodeMsg));
1452     if (msg)
1453     {
1454         CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
1455          CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update);
1456         msg->type = dwMsgType;
1457         if (hCryptProv)
1458             msg->crypt_prov = hCryptProv;
1459         else
1460         {
1461             msg->crypt_prov = CRYPT_GetDefaultProvider();
1462             msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
1463         }
1464         msg->hash = 0;
1465         msg->msg_data.cbData = 0;
1466         msg->msg_data.pbData = NULL;
1467         msg->properties = ContextPropertyList_Create();
1468     }
1469     return msg;
1470 }
1471
1472 HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
1473 {
1474     TRACE("(%p)\n", hCryptMsg);
1475
1476     if (hCryptMsg)
1477     {
1478         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
1479
1480         InterlockedIncrement(&msg->ref);
1481     }
1482     return hCryptMsg;
1483 }
1484
1485 BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
1486 {
1487     TRACE("(%p)\n", hCryptMsg);
1488
1489     if (hCryptMsg)
1490     {
1491         CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
1492
1493         if (InterlockedDecrement(&msg->ref) == 0)
1494         {
1495             TRACE("freeing %p\n", msg);
1496             if (msg->close)
1497                 msg->close(msg);
1498             CryptMemFree(msg);
1499         }
1500     }
1501     return TRUE;
1502 }
1503
1504 BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
1505  DWORD cbData, BOOL fFinal)
1506 {
1507     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
1508     BOOL ret = FALSE;
1509
1510     TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
1511
1512     if (msg->state == MsgStateFinalized)
1513         SetLastError(CRYPT_E_MSG_ERROR);
1514     else
1515     {
1516         ret = msg->update(hCryptMsg, pbData, cbData, fFinal);
1517         msg->state = MsgStateUpdated;
1518         if (fFinal)
1519             msg->state = MsgStateFinalized;
1520     }
1521     return ret;
1522 }
1523
1524 BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
1525  DWORD dwIndex, void *pvData, DWORD *pcbData)
1526 {
1527     CryptMsgBase *msg = (CryptMsgBase *)hCryptMsg;
1528
1529     TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
1530      pvData, pcbData);
1531     return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
1532 }