crypt32: Support CRYPT_DECODE_TO_BE_SIGNED_FLAG.
[wine] / dlls / crypt32 / decode.c
1 /*
2  * Copyright 2005 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  * This file implements ASN.1 DER decoding of a limited set of types.
19  * It isn't a full ASN.1 implementation.  Microsoft implements BER
20  * encoding of many of the basic types in msasn1.dll, but that interface is
21  * undocumented, so I implement them here.
22  *
23  * References:
24  * "A Layman's Guide to a Subset of ASN.1, BER, and DER", by Burton Kaliski
25  * (available online, look for a PDF copy as the HTML versions tend to have
26  * translation errors.)
27  *
28  * RFC3280, http://www.faqs.org/rfcs/rfc3280.html
29  *
30  * MSDN, especially:
31  * http://msdn.microsoft.com/library/en-us/seccrypto/security/constants_for_cryptencodeobject_and_cryptdecodeobject.asp
32  */
33
34 #include <assert.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38
39 #define NONAMELESSUNION
40
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wincrypt.h"
44 #include "winnls.h"
45 #include "snmp.h"
46 #include "wine/debug.h"
47 #include "wine/exception.h"
48 #include "crypt32_private.h"
49
50 /* This is a bit arbitrary, but to set some limit: */
51 #define MAX_ENCODED_LEN 0x02000000
52
53 #define ASN_FLAGS_MASK 0xe0
54 #define ASN_TYPE_MASK  0x1f
55
56 WINE_DEFAULT_DEBUG_CHANNEL(cryptasn);
57 WINE_DECLARE_DEBUG_CHANNEL(crypt);
58
59 struct GenericArray
60 {
61     DWORD cItems;
62     BYTE *rgItems;
63 };
64
65 typedef BOOL (WINAPI *CryptDecodeObjectFunc)(DWORD, LPCSTR, const BYTE *,
66  DWORD, DWORD, void *, DWORD *);
67 typedef BOOL (WINAPI *CryptDecodeObjectExFunc)(DWORD, LPCSTR, const BYTE *,
68  DWORD, DWORD, PCRYPT_DECODE_PARA, void *, DWORD *);
69
70 /* Prototypes for built-in decoders.  They follow the Ex style prototypes.
71  * The dwCertEncodingType and lpszStructType are ignored by the built-in
72  * functions, but the parameters are retained to simplify CryptDecodeObjectEx,
73  * since it must call functions in external DLLs that follow these signatures.
74  */
75 static BOOL WINAPI CRYPT_AsnDecodeChoiceOfTime(DWORD dwCertEncodingType,
76  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
77  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
78 static BOOL WINAPI CRYPT_AsnDecodePubKeyInfoInternal(DWORD dwCertEncodingType,
79  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
80  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
81 /* Like CRYPT_AsnDecodeExtensions, except assumes rgExtension is set ahead of
82  * time, doesn't do memory allocation, and doesn't do exception handling.
83  * (This isn't intended to be the externally-called one.)
84  */
85 static BOOL WINAPI CRYPT_AsnDecodeExtensionsInternal(DWORD dwCertEncodingType,
86  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
87  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
88 /* Assumes algo->Parameters.pbData is set ahead of time.  Internal func. */
89 static BOOL WINAPI CRYPT_AsnDecodeAlgorithmId(DWORD dwCertEncodingType,
90  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
91  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
92 /* Internal function */
93 static BOOL WINAPI CRYPT_AsnDecodeBool(DWORD dwCertEncodingType,
94  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
95  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
96 /* Assumes the CRYPT_DATA_BLOB's pbData member has been initialized */
97 static BOOL WINAPI CRYPT_AsnDecodeOctetsInternal(DWORD dwCertEncodingType,
98  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
99  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
100 /* Like CRYPT_AsnDecodeBits, but assumes the CRYPT_INTEGER_BLOB's pbData
101  * member has been initialized, doesn't do exception handling, and doesn't do
102  * memory allocation.
103  */
104 static BOOL WINAPI CRYPT_AsnDecodeBitsInternal(DWORD dwCertEncodingType,
105  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
106  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
107 static BOOL WINAPI CRYPT_AsnDecodeBits(DWORD dwCertEncodingType,
108  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
109  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
110 static BOOL WINAPI CRYPT_AsnDecodeInt(DWORD dwCertEncodingType,
111  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
112  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
113 /* Like CRYPT_AsnDecodeInteger, but assumes the CRYPT_INTEGER_BLOB's pbData
114  * member has been initialized, doesn't do exception handling, and doesn't do
115  * memory allocation.  Also doesn't check tag, assumes the caller has checked
116  * it.
117  */
118 static BOOL WINAPI CRYPT_AsnDecodeIntegerInternal(DWORD dwCertEncodingType,
119  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
120  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo);
121 /* Like CRYPT_AsnDecodeInteger, but unsigned.  */
122 static BOOL WINAPI CRYPT_AsnDecodeUnsignedIntegerInternal(
123  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
124  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
125  void *pvStructInfo, DWORD *pcbStructInfo);
126
127 /* Gets the number of length bytes from the given (leading) length byte */
128 #define GET_LEN_BYTES(b) ((b) <= 0x7f ? 1 : 1 + ((b) & 0x7f))
129
130 /* Helper function to get the encoded length of the data starting at pbEncoded,
131  * where pbEncoded[0] is the tag.  If the data are too short to contain a
132  * length or if the length is too large for cbEncoded, sets an appropriate
133  * error code and returns FALSE.
134  */
135 static BOOL WINAPI CRYPT_GetLen(const BYTE *pbEncoded, DWORD cbEncoded,
136  DWORD *len)
137 {
138     BOOL ret;
139
140     if (cbEncoded <= 1)
141     {
142         SetLastError(CRYPT_E_ASN1_CORRUPT);
143         ret = FALSE;
144     }
145     else if (pbEncoded[1] <= 0x7f)
146     {
147         if (pbEncoded[1] + 1 > cbEncoded)
148         {
149             SetLastError(CRYPT_E_ASN1_EOD);
150             ret = FALSE;
151         }
152         else
153         {
154             *len = pbEncoded[1];
155             ret = TRUE;
156         }
157     }
158     else if (pbEncoded[1] == 0x80)
159     {
160         FIXME("unimplemented for indefinite-length encoding\n");
161         SetLastError(CRYPT_E_ASN1_CORRUPT);
162         ret = FALSE;
163     }
164     else
165     {
166         BYTE lenLen = GET_LEN_BYTES(pbEncoded[1]);
167
168         if (lenLen > sizeof(DWORD) + 1)
169         {
170             SetLastError(CRYPT_E_ASN1_LARGE);
171             ret = FALSE;
172         }
173         else if (lenLen + 2 > cbEncoded)
174         {
175             SetLastError(CRYPT_E_ASN1_CORRUPT);
176             ret = FALSE;
177         }
178         else
179         {
180             DWORD out = 0;
181
182             pbEncoded += 2;
183             while (--lenLen)
184             {
185                 out <<= 8;
186                 out |= *pbEncoded++;
187             }
188             if (out + lenLen + 1 > cbEncoded)
189             {
190                 SetLastError(CRYPT_E_ASN1_EOD);
191                 ret = FALSE;
192             }
193             else
194             {
195                 *len = out;
196                 ret = TRUE;
197             }
198         }
199     }
200     return ret;
201 }
202
203 /* Helper function to check *pcbStructInfo, set it to the required size, and
204  * optionally to allocate memory.  Assumes pvStructInfo is not NULL.
205  * If CRYPT_DECODE_ALLOC_FLAG is set in dwFlags, *pvStructInfo will be set to a
206  * pointer to the newly allocated memory.
207  */
208 static BOOL CRYPT_DecodeEnsureSpace(DWORD dwFlags,
209  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo,
210  DWORD bytesNeeded)
211 {
212     BOOL ret = TRUE;
213
214     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
215     {
216         if (pDecodePara && pDecodePara->pfnAlloc)
217             *(BYTE **)pvStructInfo = pDecodePara->pfnAlloc(bytesNeeded);
218         else
219             *(BYTE **)pvStructInfo = LocalAlloc(0, bytesNeeded);
220         if (!*(BYTE **)pvStructInfo)
221             ret = FALSE;
222         else
223             *pcbStructInfo = bytesNeeded;
224     }
225     else if (*pcbStructInfo < bytesNeeded)
226     {
227         *pcbStructInfo = bytesNeeded;
228         SetLastError(ERROR_MORE_DATA);
229         ret = FALSE;
230     }
231     return ret;
232 }
233
234 /* tag:
235  *     The expected tag of the item.  If tag is 0, decodeFunc is called
236  *     regardless of the tag value seen.
237  * offset:
238  *     A sequence is decoded into a struct.  The offset member is the
239  *     offset of this item within that struct.
240  * decodeFunc:
241  *     The decoder function to use.  If this is NULL, then the member isn't
242  *     decoded, but minSize space is reserved for it.
243  * minSize:
244  *     The minimum amount of space occupied after decoding.  You must set this.
245  * optional:
246  *     If true, and the tag doesn't match the expected tag for this item,
247  *     or the decodeFunc fails with CRYPT_E_ASN1_BADTAG, then minSize space is
248  *     filled with 0 for this member.
249  * hasPointer, pointerOffset:
250  *     If the item has dynamic data, set hasPointer to TRUE, pointerOffset to
251  *     the offset within the struct of the data pointer (or to the
252  *     first data pointer, if more than one exist).
253  * size:
254  *     Used by CRYPT_AsnDecodeSequence, not for your use.
255  */
256 struct AsnDecodeSequenceItem
257 {
258     BYTE                    tag;
259     DWORD                   offset;
260     CryptDecodeObjectExFunc decodeFunc;
261     DWORD                   minSize;
262     BOOL                    optional;
263     BOOL                    hasPointer;
264     DWORD                   pointerOffset;
265     DWORD                   size;
266 };
267
268 /* Decodes the items in a sequence, where the items are described in items,
269  * the encoded data are in pbEncoded with length cbEncoded.  Decodes into
270  * pvStructInfo.  nextData is a pointer to the memory location at which the
271  * first decoded item with a dynamic pointer should point.
272  * Upon decoding, *cbDecoded is the total number of bytes decoded.
273  */
274 static BOOL CRYPT_AsnDecodeSequenceItems(DWORD dwCertEncodingType,
275  struct AsnDecodeSequenceItem items[], DWORD cItem, const BYTE *pbEncoded,
276  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, BYTE *nextData,
277  DWORD *cbDecoded)
278 {
279     BOOL ret;
280     DWORD i, decoded = 0;
281     const BYTE *ptr = pbEncoded;
282
283     TRACE("%p, %d, %p, %d, %08x, %p, %p, %p\n", items, cItem, pbEncoded,
284      cbEncoded, dwFlags, pvStructInfo, nextData, cbDecoded);
285
286     for (i = 0, ret = TRUE; ret && i < cItem; i++)
287     {
288         if (cbEncoded - (ptr - pbEncoded) != 0)
289         {
290             DWORD nextItemLen;
291
292             if ((ret = CRYPT_GetLen(ptr, cbEncoded - (ptr - pbEncoded),
293              &nextItemLen)))
294             {
295                 BYTE nextItemLenBytes = GET_LEN_BYTES(ptr[1]);
296
297                 if (ptr[0] == items[i].tag || !items[i].tag)
298                 {
299                     if (nextData && pvStructInfo && items[i].hasPointer)
300                     {
301                         TRACE("Setting next pointer to %p\n",
302                          nextData);
303                         *(BYTE **)((BYTE *)pvStructInfo +
304                          items[i].pointerOffset) = nextData;
305                     }
306                     if (items[i].decodeFunc)
307                     {
308                         if (pvStructInfo)
309                             TRACE("decoding item %d\n", i);
310                         else
311                             TRACE("sizing item %d\n", i);
312                         ret = items[i].decodeFunc(dwCertEncodingType,
313                          NULL, ptr, 1 + nextItemLenBytes + nextItemLen,
314                          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL,
315                          pvStructInfo ?  (BYTE *)pvStructInfo + items[i].offset
316                          : NULL, &items[i].size);
317                         if (ret)
318                         {
319                             /* Account for alignment padding */
320                             if (items[i].size % sizeof(DWORD))
321                                 items[i].size += sizeof(DWORD) -
322                                  items[i].size % sizeof(DWORD);
323                             TRACE("item %d size: %d\n", i, items[i].size);
324                             if (nextData && items[i].hasPointer &&
325                              items[i].size > items[i].minSize)
326                                 nextData += items[i].size - items[i].minSize;
327                             ptr += 1 + nextItemLenBytes + nextItemLen;
328                             decoded += 1 + nextItemLenBytes + nextItemLen;
329                             TRACE("item %d: decoded %d bytes\n", i,
330                              1 + nextItemLenBytes + nextItemLen);
331                         }
332                         else if (items[i].optional &&
333                          GetLastError() == CRYPT_E_ASN1_BADTAG)
334                         {
335                             TRACE("skipping optional item %d\n", i);
336                             items[i].size = items[i].minSize;
337                             SetLastError(NOERROR);
338                             ret = TRUE;
339                         }
340                         else
341                             TRACE("item %d failed: %08x\n", i,
342                              GetLastError());
343                     }
344                     else
345                     {
346                         TRACE("item %d: decoded %d bytes\n", i,
347                          1 + nextItemLenBytes + nextItemLen);
348                         ptr += 1 + nextItemLenBytes + nextItemLen;
349                         decoded += 1 + nextItemLenBytes + nextItemLen;
350                         items[i].size = items[i].minSize;
351                     }
352                 }
353                 else if (items[i].optional)
354                 {
355                     TRACE("skipping optional item %d\n", i);
356                     items[i].size = items[i].minSize;
357                 }
358                 else
359                 {
360                     TRACE("item %d: tag %02x doesn't match expected %02x\n",
361                      i, ptr[0], items[i].tag);
362                     SetLastError(CRYPT_E_ASN1_BADTAG);
363                     ret = FALSE;
364                 }
365             }
366         }
367         else if (items[i].optional)
368         {
369             TRACE("missing optional item %d, skipping\n", i);
370             items[i].size = items[i].minSize;
371         }
372         else
373         {
374             TRACE("not enough bytes for item %d, failing\n", i);
375             SetLastError(CRYPT_E_ASN1_CORRUPT);
376             ret = FALSE;
377         }
378     }
379     if (ret)
380         *cbDecoded = decoded;
381     TRACE("returning %d\n", ret);
382     return ret;
383 }
384
385 /* This decodes an arbitrary sequence into a contiguous block of memory
386  * (basically, a struct.)  Each element being decoded is described by a struct
387  * AsnDecodeSequenceItem, see above.
388  * startingPointer is an optional pointer to the first place where dynamic
389  * data will be stored.  If you know the starting offset, you may pass it
390  * here.  Otherwise, pass NULL, and one will be inferred from the items.
391  * Each item decoder is never called with CRYPT_DECODE_ALLOC_FLAG set.
392  */
393 static BOOL CRYPT_AsnDecodeSequence(DWORD dwCertEncodingType,
394  struct AsnDecodeSequenceItem items[], DWORD cItem, const BYTE *pbEncoded,
395  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
396  void *pvStructInfo, DWORD *pcbStructInfo, void *startingPointer)
397 {
398     BOOL ret;
399
400     TRACE("%p, %d, %p, %d, %08x, %p, %p, %d, %p\n", items, cItem, pbEncoded,
401      cbEncoded, dwFlags, pDecodePara, pvStructInfo, *pcbStructInfo,
402      startingPointer);
403
404     if (pbEncoded[0] == ASN_SEQUENCE)
405     {
406         DWORD dataLen;
407
408         if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
409         {
410             DWORD lenBytes = GET_LEN_BYTES(pbEncoded[1]), cbDecoded;
411             const BYTE *ptr = pbEncoded + 1 + lenBytes;
412
413             cbEncoded -= 1 + lenBytes;
414             if (cbEncoded < dataLen)
415             {
416                 TRACE("dataLen %d exceeds cbEncoded %d, failing\n", dataLen,
417                  cbEncoded);
418                 SetLastError(CRYPT_E_ASN1_CORRUPT);
419                 ret = FALSE;
420             }
421             else
422                 ret = CRYPT_AsnDecodeSequenceItems(dwFlags, items, cItem, ptr,
423                  cbEncoded, dwFlags, NULL, NULL, &cbDecoded);
424             if (ret && cbDecoded != dataLen)
425             {
426                 TRACE("expected %d decoded, got %d, failing\n", dataLen,
427                  cbDecoded);
428                 SetLastError(CRYPT_E_ASN1_CORRUPT);
429                 ret = FALSE;
430             }
431             if (ret)
432             {
433                 DWORD i, bytesNeeded = 0, structSize = 0;
434
435                 for (i = 0; i < cItem; i++)
436                 {
437                     bytesNeeded += items[i].size;
438                     structSize += items[i].minSize;
439                 }
440                 if (!pvStructInfo)
441                     *pcbStructInfo = bytesNeeded;
442                 else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags,
443                  pDecodePara, pvStructInfo, pcbStructInfo, bytesNeeded)))
444                 {
445                     BYTE *nextData;
446
447                     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
448                         pvStructInfo = *(BYTE **)pvStructInfo;
449                     if (startingPointer)
450                         nextData = (BYTE *)startingPointer;
451                     else
452                         nextData = (BYTE *)pvStructInfo + structSize;
453                     memset(pvStructInfo, 0, structSize);
454                     ret = CRYPT_AsnDecodeSequenceItems(dwFlags, items, cItem,
455                      ptr, cbEncoded, dwFlags, pvStructInfo, nextData,
456                      &cbDecoded);
457                 }
458             }
459         }
460     }
461     else
462     {
463         SetLastError(CRYPT_E_ASN1_BADTAG);
464         ret = FALSE;
465     }
466     TRACE("returning %d (%08x)\n", ret, GetLastError());
467     return ret;
468 }
469
470 /* tag:
471  *     The expected tag of the entire encoded array (usually a variant
472  *     of ASN_SETOF or ASN_SEQUENCEOF.)  If tag is 0, decodeFunc is called
473  *     regardless of the tag seen.
474  * decodeFunc:
475  *     used to decode each item in the array
476  * itemSize:
477  *      is the minimum size of each decoded item
478  * hasPointer:
479  *      indicates whether each item has a dynamic pointer
480  * pointerOffset:
481  *     indicates the offset within itemSize at which the pointer exists
482  */
483 struct AsnArrayDescriptor
484 {
485     BYTE                    tag;
486     CryptDecodeObjectExFunc decodeFunc;
487     DWORD                   itemSize;
488     BOOL                    hasPointer;
489     DWORD                   pointerOffset;
490 };
491
492 struct AsnArrayItemSize
493 {
494     DWORD encodedLen;
495     DWORD size;
496 };
497
498 /* Decodes an array of like types into a struct GenericArray.
499  * The layout and decoding of the array are described by a struct
500  * AsnArrayDescriptor.
501  */
502 static BOOL CRYPT_AsnDecodeArray(const struct AsnArrayDescriptor *arrayDesc,
503  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
504  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo,
505  void *startingPointer)
506 {
507     BOOL ret = TRUE;
508
509     TRACE("%p, %p, %d, %08x, %p, %p, %d, %p\n", arrayDesc, pbEncoded,
510      cbEncoded, dwFlags, pDecodePara, pvStructInfo, *pcbStructInfo,
511      startingPointer);
512
513     if (!arrayDesc->tag || pbEncoded[0] == arrayDesc->tag)
514     {
515         DWORD dataLen;
516
517         if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
518         {
519             DWORD bytesNeeded, cItems = 0;
520             BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
521             /* There can be arbitrarily many items, but there is often only one.
522              */
523             struct AsnArrayItemSize itemSize = { 0 }, *itemSizes = &itemSize;
524
525             bytesNeeded = sizeof(struct GenericArray);
526             if (dataLen)
527             {
528                 const BYTE *ptr;
529
530                 for (ptr = pbEncoded + 1 + lenBytes; ret &&
531                  ptr - pbEncoded - 1 - lenBytes < dataLen; )
532                 {
533                     DWORD itemLenBytes, itemDataLen, size = 0;
534
535                     itemLenBytes = GET_LEN_BYTES(ptr[1]);
536                     /* Each item decoded may not tolerate extraneous bytes, so
537                      * get the length of the next element and pass it directly.
538                      */
539                     ret = CRYPT_GetLen(ptr, cbEncoded - (ptr - pbEncoded),
540                      &itemDataLen);
541                     if (ret)
542                         ret = arrayDesc->decodeFunc(X509_ASN_ENCODING, 0, ptr,
543                          1 + itemLenBytes + itemDataLen,
544                          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL,
545                          &size);
546                     if (ret)
547                     {
548                         DWORD nextLen;
549
550                         cItems++;
551                         if (itemSizes != &itemSize)
552                             itemSizes = CryptMemRealloc(itemSizes,
553                              cItems * sizeof(struct AsnArrayItemSize));
554                         else
555                         {
556                             itemSizes =
557                              CryptMemAlloc(
558                              cItems * sizeof(struct AsnArrayItemSize));
559                             if (itemSizes)
560                                 memcpy(itemSizes, &itemSize, sizeof(itemSize));
561                         }
562                         if (itemSizes)
563                         {
564                             itemSizes[cItems - 1].encodedLen = 1 + itemLenBytes
565                              + itemDataLen;
566                             itemSizes[cItems - 1].size = size;
567                             bytesNeeded += size;
568                             ret = CRYPT_GetLen(ptr,
569                              cbEncoded - (ptr - pbEncoded), &nextLen);
570                             if (ret)
571                                 ptr += nextLen + 1 + GET_LEN_BYTES(ptr[1]);
572                         }
573                         else
574                             ret = FALSE;
575                     }
576                 }
577             }
578             if (ret)
579             {
580                 if (!pvStructInfo)
581                     *pcbStructInfo = bytesNeeded;
582                 else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags,
583                  pDecodePara, pvStructInfo, pcbStructInfo, bytesNeeded)))
584                 {
585                     DWORD i;
586                     BYTE *nextData;
587                     const BYTE *ptr;
588                     struct GenericArray *array;
589
590                     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
591                         pvStructInfo = *(BYTE **)pvStructInfo;
592                     array = (struct GenericArray *)pvStructInfo;
593                     array->cItems = cItems;
594                     if (startingPointer)
595                         array->rgItems = startingPointer;
596                     else
597                         array->rgItems = (BYTE *)array +
598                          sizeof(struct GenericArray);
599                     nextData = (BYTE *)array->rgItems +
600                      array->cItems * arrayDesc->itemSize;
601                     for (i = 0, ptr = pbEncoded + 1 + lenBytes; ret &&
602                      i < cItems && ptr - pbEncoded - 1 - lenBytes <
603                      dataLen; i++)
604                     {
605                         if (arrayDesc->hasPointer)
606                             *(BYTE **)(array->rgItems + i * arrayDesc->itemSize
607                              + arrayDesc->pointerOffset) = nextData;
608                         ret = arrayDesc->decodeFunc(X509_ASN_ENCODING, 0, ptr,
609                          itemSizes[i].encodedLen,
610                          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL,
611                          array->rgItems + i * arrayDesc->itemSize,
612                          &itemSizes[i].size);
613                         if (ret)
614                         {
615                             DWORD nextLen;
616
617                             nextData += itemSizes[i].size - arrayDesc->itemSize;
618                             ret = CRYPT_GetLen(ptr,
619                              cbEncoded - (ptr - pbEncoded), &nextLen);
620                             if (ret)
621                                 ptr += nextLen + 1 + GET_LEN_BYTES(ptr[1]);
622                         }
623                     }
624                 }
625             }
626             if (itemSizes != &itemSize)
627                 CryptMemFree(itemSizes);
628         }
629     }
630     else
631     {
632         SetLastError(CRYPT_E_ASN1_BADTAG);
633         ret = FALSE;
634     }
635     return ret;
636 }
637
638 /* Decodes a DER-encoded BLOB into a CRYPT_DER_BLOB struct pointed to by
639  * pvStructInfo.  The BLOB must be non-empty, otherwise the last error is set
640  * to CRYPT_E_ASN1_CORRUPT.
641  * Warning: assumes the CRYPT_DER_BLOB pointed to by pvStructInfo has pbData
642  * set!
643  */
644 static BOOL WINAPI CRYPT_AsnDecodeDerBlob(DWORD dwCertEncodingType,
645  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
646  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
647 {
648     BOOL ret;
649     DWORD dataLen;
650
651     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
652     {
653         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
654         DWORD bytesNeeded = sizeof(CRYPT_DER_BLOB);
655        
656         if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
657             bytesNeeded += 1 + lenBytes + dataLen;
658
659         if (!pvStructInfo)
660             *pcbStructInfo = bytesNeeded;
661         else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, 
662          pvStructInfo, pcbStructInfo, bytesNeeded)))
663         {
664             CRYPT_DER_BLOB *blob;
665
666             if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
667                 pvStructInfo = *(BYTE **)pvStructInfo;
668             blob = (CRYPT_DER_BLOB *)pvStructInfo;
669             blob->cbData = 1 + lenBytes + dataLen;
670             if (blob->cbData)
671             {
672                 if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
673                     blob->pbData = (BYTE *)pbEncoded;
674                 else
675                 {
676                     assert(blob->pbData);
677                     memcpy(blob->pbData, pbEncoded, blob->cbData);
678                 }
679             }
680             else
681             {
682                 SetLastError(CRYPT_E_ASN1_CORRUPT);
683                 ret = FALSE;
684             }
685         }
686     }
687     return ret;
688 }
689
690 /* Like CRYPT_AsnDecodeBitsInternal, but swaps the bytes */
691 static BOOL WINAPI CRYPT_AsnDecodeBitsSwapBytes(DWORD dwCertEncodingType,
692  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
693  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
694 {
695     BOOL ret;
696
697     TRACE("(%p, %d, 0x%08x, %p, %p, %d)\n", pbEncoded, cbEncoded, dwFlags,
698      pDecodePara, pvStructInfo, *pcbStructInfo);
699
700     /* Can't use the CRYPT_DECODE_NOCOPY_FLAG, because we modify the bytes in-
701      * place.
702      */
703     ret = CRYPT_AsnDecodeBitsInternal(dwCertEncodingType, lpszStructType,
704      pbEncoded, cbEncoded, dwFlags & ~CRYPT_DECODE_NOCOPY_FLAG, pDecodePara,
705      pvStructInfo, pcbStructInfo);
706     if (ret && pvStructInfo)
707     {
708         CRYPT_BIT_BLOB *blob = (CRYPT_BIT_BLOB *)pvStructInfo;
709
710         if (blob->cbData)
711         {
712             DWORD i;
713             BYTE temp;
714
715             for (i = 0; i < blob->cbData / 2; i++)
716             {
717                 temp = blob->pbData[i];
718                 blob->pbData[i] = blob->pbData[blob->cbData - i - 1];
719                 blob->pbData[blob->cbData - i - 1] = temp;
720             }
721         }
722     }
723     TRACE("returning %d (%08x)\n", ret, GetLastError());
724     return ret;
725 }
726
727 static BOOL WINAPI CRYPT_AsnDecodeCertSignedContent(DWORD dwCertEncodingType,
728  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
729  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
730 {
731     BOOL ret = TRUE;
732
733     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
734      pDecodePara, pvStructInfo, *pcbStructInfo);
735
736     __TRY
737     {
738         struct AsnDecodeSequenceItem items[] = {
739          { 0, offsetof(CERT_SIGNED_CONTENT_INFO, ToBeSigned),
740            CRYPT_AsnDecodeDerBlob, sizeof(CRYPT_DER_BLOB), FALSE, TRUE,
741            offsetof(CERT_SIGNED_CONTENT_INFO, ToBeSigned.pbData), 0 },
742          { ASN_SEQUENCEOF, offsetof(CERT_SIGNED_CONTENT_INFO,
743            SignatureAlgorithm), CRYPT_AsnDecodeAlgorithmId,
744            sizeof(CRYPT_ALGORITHM_IDENTIFIER), FALSE, TRUE,
745            offsetof(CERT_SIGNED_CONTENT_INFO, SignatureAlgorithm.pszObjId), 0 },
746          { ASN_BITSTRING, offsetof(CERT_SIGNED_CONTENT_INFO, Signature),
747            CRYPT_AsnDecodeBitsSwapBytes, sizeof(CRYPT_BIT_BLOB), FALSE, TRUE,
748            offsetof(CERT_SIGNED_CONTENT_INFO, Signature.pbData), 0 },
749         };
750
751         if (dwFlags & CRYPT_DECODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG)
752             items[2].decodeFunc = CRYPT_AsnDecodeBitsInternal;
753         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
754          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
755          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
756     }
757     __EXCEPT_PAGE_FAULT
758     {
759         SetLastError(STATUS_ACCESS_VIOLATION);
760         ret = FALSE;
761     }
762     __ENDTRY
763
764     TRACE("Returning %d (%08x)\n", ret, GetLastError());
765     return ret;
766 }
767
768 /* Internal function */
769 static BOOL WINAPI CRYPT_AsnDecodeCertVersion(DWORD dwCertEncodingType,
770  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
771  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
772 {
773     BOOL ret;
774     DWORD dataLen;
775
776     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
777     {
778         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
779
780         ret = CRYPT_AsnDecodeInt(dwCertEncodingType, X509_INTEGER,
781          pbEncoded + 1 + lenBytes, dataLen, dwFlags, pDecodePara,
782          pvStructInfo, pcbStructInfo);
783     }
784     return ret;
785 }
786
787 static BOOL WINAPI CRYPT_AsnDecodeValidity(DWORD dwCertEncodingType,
788  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
789  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
790 {
791     BOOL ret;
792
793     struct AsnDecodeSequenceItem items[] = {
794      { 0, offsetof(CERT_PRIVATE_KEY_VALIDITY, NotBefore),
795        CRYPT_AsnDecodeChoiceOfTime, sizeof(FILETIME), FALSE, FALSE, 0 },
796      { 0, offsetof(CERT_PRIVATE_KEY_VALIDITY, NotAfter),
797        CRYPT_AsnDecodeChoiceOfTime, sizeof(FILETIME), FALSE, FALSE, 0 },
798     };
799
800     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
801      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
802      pDecodePara, pvStructInfo, pcbStructInfo, NULL);
803     return ret;
804 }
805
806 /* Internal function */
807 static BOOL WINAPI CRYPT_AsnDecodeCertExtensions(DWORD dwCertEncodingType,
808  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
809  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
810 {
811     BOOL ret;
812     DWORD dataLen;
813
814     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
815     {
816         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
817
818         ret = CRYPT_AsnDecodeExtensionsInternal(dwCertEncodingType,
819          X509_EXTENSIONS, pbEncoded + 1 + lenBytes, dataLen, dwFlags,
820          pDecodePara, pvStructInfo, pcbStructInfo);
821     }
822     return ret;
823 }
824
825 static BOOL WINAPI CRYPT_AsnDecodeCertInfo(DWORD dwCertEncodingType,
826  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
827  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
828 {
829     BOOL ret = TRUE;
830     struct AsnDecodeSequenceItem items[] = {
831      { ASN_CONTEXT | ASN_CONSTRUCTOR, offsetof(CERT_INFO, dwVersion),
832        CRYPT_AsnDecodeCertVersion, sizeof(DWORD), TRUE, FALSE, 0, 0 },
833      { ASN_INTEGER, offsetof(CERT_INFO, SerialNumber),
834        CRYPT_AsnDecodeIntegerInternal, sizeof(CRYPT_INTEGER_BLOB), FALSE,
835        TRUE, offsetof(CERT_INFO, SerialNumber.pbData), 0 },
836      { ASN_SEQUENCEOF, offsetof(CERT_INFO, SignatureAlgorithm),
837        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
838        FALSE, TRUE, offsetof(CERT_INFO, SignatureAlgorithm.pszObjId), 0 },
839      { 0, offsetof(CERT_INFO, Issuer), CRYPT_AsnDecodeDerBlob,
840        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CERT_INFO,
841        Issuer.pbData) },
842      { ASN_SEQUENCEOF, offsetof(CERT_INFO, NotBefore),
843        CRYPT_AsnDecodeValidity, sizeof(CERT_PRIVATE_KEY_VALIDITY), FALSE,
844        FALSE, 0 },
845      { 0, offsetof(CERT_INFO, Subject), CRYPT_AsnDecodeDerBlob,
846        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CERT_INFO,
847        Subject.pbData) },
848      { ASN_SEQUENCEOF, offsetof(CERT_INFO, SubjectPublicKeyInfo),
849        CRYPT_AsnDecodePubKeyInfoInternal, sizeof(CERT_PUBLIC_KEY_INFO),
850        FALSE, TRUE, offsetof(CERT_INFO,
851        SubjectPublicKeyInfo.Algorithm.Parameters.pbData), 0 },
852      { ASN_BITSTRING, offsetof(CERT_INFO, IssuerUniqueId),
853        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), TRUE, TRUE,
854        offsetof(CERT_INFO, IssuerUniqueId.pbData), 0 },
855      { ASN_BITSTRING, offsetof(CERT_INFO, SubjectUniqueId),
856        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), TRUE, TRUE,
857        offsetof(CERT_INFO, SubjectUniqueId.pbData), 0 },
858      { ASN_CONTEXT | ASN_CONSTRUCTOR | 3, offsetof(CERT_INFO, cExtension),
859        CRYPT_AsnDecodeCertExtensions, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
860        offsetof(CERT_INFO, rgExtension), 0 },
861     };
862
863     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
864      pDecodePara, pvStructInfo, *pcbStructInfo);
865
866     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
867      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
868      pDecodePara, pvStructInfo, pcbStructInfo, NULL);
869     if (ret && pvStructInfo)
870     {
871         CERT_INFO *info;
872
873         if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
874             info = *(CERT_INFO **)pvStructInfo;
875         else
876             info = (CERT_INFO *)pvStructInfo;
877         if (!info->SerialNumber.cbData || !info->Issuer.cbData ||
878          !info->Subject.cbData)
879         {
880             SetLastError(CRYPT_E_ASN1_CORRUPT);
881             /* Don't need to deallocate, because it should have failed on the
882              * first pass (and no memory was allocated.)
883              */
884             ret = FALSE;
885         }
886     }
887
888     TRACE("Returning %d (%08x)\n", ret, GetLastError());
889     return ret;
890 }
891
892 static BOOL WINAPI CRYPT_AsnDecodeCert(DWORD dwCertEncodingType,
893  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
894  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
895 {
896     BOOL ret = FALSE;
897
898     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
899      pDecodePara, pvStructInfo, *pcbStructInfo);
900
901     __TRY
902     {
903         DWORD size = 0;
904
905         /* Unless told not to, first try to decode it as a signed cert. */
906         if (!(dwFlags & CRYPT_DECODE_TO_BE_SIGNED_FLAG))
907         {
908             PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
909
910             ret = CRYPT_AsnDecodeCertSignedContent(dwCertEncodingType,
911              X509_CERT, pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
912              (BYTE *)&signedCert, &size);
913             if (ret)
914             {
915                 size = 0;
916                 ret = CRYPT_AsnDecodeCertInfo(dwCertEncodingType,
917                  X509_CERT_TO_BE_SIGNED, signedCert->ToBeSigned.pbData,
918                  signedCert->ToBeSigned.cbData, dwFlags, pDecodePara,
919                  pvStructInfo, pcbStructInfo);
920                 LocalFree(signedCert);
921             }
922         }
923         /* Failing that, try it as an unsigned cert */
924         if (!ret)
925         {
926             size = 0;
927             ret = CRYPT_AsnDecodeCertInfo(dwCertEncodingType,
928              X509_CERT_TO_BE_SIGNED, pbEncoded, cbEncoded, dwFlags,
929              pDecodePara, pvStructInfo, pcbStructInfo);
930         }
931     }
932     __EXCEPT_PAGE_FAULT
933     {
934         SetLastError(STATUS_ACCESS_VIOLATION);
935     }
936     __ENDTRY
937
938     TRACE("Returning %d (%08x)\n", ret, GetLastError());
939     return ret;
940 }
941
942 static BOOL WINAPI CRYPT_AsnDecodeCRLEntry(DWORD dwCertEncodingType,
943  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
944  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
945 {
946     BOOL ret;
947     struct AsnDecodeSequenceItem items[] = {
948      { ASN_INTEGER, offsetof(CRL_ENTRY, SerialNumber),
949        CRYPT_AsnDecodeIntegerInternal, sizeof(CRYPT_INTEGER_BLOB), FALSE, TRUE,
950        offsetof(CRL_ENTRY, SerialNumber.pbData), 0 },
951      { 0, offsetof(CRL_ENTRY, RevocationDate), CRYPT_AsnDecodeChoiceOfTime,
952        sizeof(FILETIME), FALSE, FALSE, 0 },
953      { ASN_SEQUENCEOF, offsetof(CRL_ENTRY, cExtension),
954        CRYPT_AsnDecodeExtensionsInternal, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
955        offsetof(CRL_ENTRY, rgExtension), 0 },
956     };
957     PCRL_ENTRY entry = (PCRL_ENTRY)pvStructInfo;
958
959     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags, entry,
960      *pcbStructInfo);
961
962     ret = CRYPT_AsnDecodeSequence(X509_ASN_ENCODING, items,
963      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
964      NULL, entry, pcbStructInfo, entry ? entry->SerialNumber.pbData : NULL);
965     return ret;
966 }
967
968 /* Warning: assumes pvStructInfo is a struct GenericArray whose rgItems has
969  * been set prior to calling.
970  */
971 static BOOL WINAPI CRYPT_AsnDecodeCRLEntries(DWORD dwCertEncodingType,
972  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
973  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
974 {
975     BOOL ret;
976     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
977      CRYPT_AsnDecodeCRLEntry, sizeof(CRL_ENTRY), TRUE,
978      offsetof(CRL_ENTRY, SerialNumber.pbData) };
979     struct GenericArray *entries = (struct GenericArray *)pvStructInfo;
980
981     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
982      pDecodePara, pvStructInfo, *pcbStructInfo);
983
984     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
985      pDecodePara, pvStructInfo, pcbStructInfo,
986      entries ? entries->rgItems : NULL);
987     TRACE("Returning %d (%08x)\n", ret, GetLastError());
988     return ret;
989 }
990
991 static BOOL WINAPI CRYPT_AsnDecodeCRLInfo(DWORD dwCertEncodingType,
992  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
993  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
994 {
995     struct AsnDecodeSequenceItem items[] = {
996      { ASN_INTEGER, offsetof(CRL_INFO, dwVersion),
997        CRYPT_AsnDecodeInt, sizeof(DWORD), TRUE, FALSE, 0, 0 },
998      { ASN_SEQUENCEOF, offsetof(CRL_INFO, SignatureAlgorithm),
999        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
1000        FALSE, TRUE, offsetof(CRL_INFO, SignatureAlgorithm.pszObjId), 0 },
1001      { 0, offsetof(CRL_INFO, Issuer), CRYPT_AsnDecodeDerBlob,
1002        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CRL_INFO,
1003        Issuer.pbData) },
1004      { 0, offsetof(CRL_INFO, ThisUpdate), CRYPT_AsnDecodeChoiceOfTime,
1005        sizeof(FILETIME), FALSE, FALSE, 0 },
1006      { 0, offsetof(CRL_INFO, NextUpdate), CRYPT_AsnDecodeChoiceOfTime,
1007        sizeof(FILETIME), TRUE, FALSE, 0 },
1008      { ASN_SEQUENCEOF, offsetof(CRL_INFO, cCRLEntry),
1009        CRYPT_AsnDecodeCRLEntries, sizeof(struct GenericArray), TRUE, TRUE,
1010        offsetof(CRL_INFO, rgCRLEntry), 0 },
1011      { ASN_CONTEXT | ASN_CONSTRUCTOR | 0, offsetof(CRL_INFO, cExtension),
1012        CRYPT_AsnDecodeCertExtensions, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
1013        offsetof(CRL_INFO, rgExtension), 0 },
1014     };
1015     BOOL ret = TRUE;
1016
1017     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1018      pDecodePara, pvStructInfo, *pcbStructInfo);
1019
1020     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
1021      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
1022      pDecodePara, pvStructInfo, pcbStructInfo, NULL);
1023
1024     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1025     return ret;
1026 }
1027
1028 static BOOL WINAPI CRYPT_AsnDecodeCRL(DWORD dwCertEncodingType,
1029  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1030  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1031 {
1032     BOOL ret = FALSE;
1033
1034     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1035      pDecodePara, pvStructInfo, *pcbStructInfo);
1036
1037     __TRY
1038     {
1039         DWORD size = 0;
1040
1041         /* Unless told not to, first try to decode it as a signed crl. */
1042         if (!(dwFlags & CRYPT_DECODE_TO_BE_SIGNED_FLAG))
1043         {
1044             PCERT_SIGNED_CONTENT_INFO signedCrl = NULL;
1045
1046             ret = CRYPT_AsnDecodeCertSignedContent(dwCertEncodingType,
1047              X509_CERT, pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
1048              (BYTE *)&signedCrl, &size);
1049             if (ret)
1050             {
1051                 size = 0;
1052                 ret = CRYPT_AsnDecodeCRLInfo(dwCertEncodingType,
1053                  X509_CERT_CRL_TO_BE_SIGNED, signedCrl->ToBeSigned.pbData,
1054                  signedCrl->ToBeSigned.cbData, dwFlags, pDecodePara,
1055                  pvStructInfo, pcbStructInfo);
1056                 LocalFree(signedCrl);
1057             }
1058         }
1059         /* Failing that, try it as an unsigned crl */
1060         if (!ret)
1061         {
1062             size = 0;
1063             ret = CRYPT_AsnDecodeCRLInfo(dwCertEncodingType,
1064              X509_CERT_CRL_TO_BE_SIGNED, pbEncoded, cbEncoded,
1065              dwFlags, pDecodePara, pvStructInfo, pcbStructInfo);
1066         }
1067     }
1068     __EXCEPT_PAGE_FAULT
1069     {
1070         SetLastError(STATUS_ACCESS_VIOLATION);
1071     }
1072     __ENDTRY
1073
1074     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1075     return ret;
1076 }
1077
1078 static BOOL WINAPI CRYPT_AsnDecodeOidIgnoreTag(DWORD dwCertEncodingType,
1079  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1080  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1081 {
1082     BOOL ret = TRUE;
1083     DWORD dataLen;
1084
1085     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1086      pDecodePara, pvStructInfo, *pcbStructInfo);
1087
1088     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
1089     {
1090         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1091         DWORD bytesNeeded = sizeof(LPSTR);
1092
1093         if (dataLen)
1094         {
1095             /* The largest possible string for the first two components
1096              * is 2.175 (= 2 * 40 + 175 = 255), so this is big enough.
1097              */
1098             char firstTwo[6];
1099             const BYTE *ptr;
1100
1101             snprintf(firstTwo, sizeof(firstTwo), "%d.%d",
1102              pbEncoded[1 + lenBytes] / 40,
1103              pbEncoded[1 + lenBytes] - (pbEncoded[1 + lenBytes] / 40)
1104              * 40);
1105             bytesNeeded += strlen(firstTwo) + 1;
1106             for (ptr = pbEncoded + 2 + lenBytes; ret &&
1107              ptr - pbEncoded - 1 - lenBytes < dataLen; )
1108             {
1109                 /* large enough for ".4000000" */
1110                 char str[9];
1111                 int val = 0;
1112
1113                 while (ptr - pbEncoded - 1 - lenBytes < dataLen &&
1114                  (*ptr & 0x80))
1115                 {
1116                     val <<= 7;
1117                     val |= *ptr & 0x7f;
1118                     ptr++;
1119                 }
1120                 if (ptr - pbEncoded - 1 - lenBytes >= dataLen ||
1121                  (*ptr & 0x80))
1122                 {
1123                     SetLastError(CRYPT_E_ASN1_CORRUPT);
1124                     ret = FALSE;
1125                 }
1126                 else
1127                 {
1128                     val <<= 7;
1129                     val |= *ptr++;
1130                     snprintf(str, sizeof(str), ".%d", val);
1131                     bytesNeeded += strlen(str);
1132                 }
1133             }
1134         }
1135         if (!pvStructInfo)
1136             *pcbStructInfo = bytesNeeded;
1137         else if (*pcbStructInfo < bytesNeeded)
1138         {
1139             *pcbStructInfo = bytesNeeded;
1140             SetLastError(ERROR_MORE_DATA);
1141             ret = FALSE;
1142         }
1143         else
1144         {
1145             if (dataLen)
1146             {
1147                 const BYTE *ptr;
1148                 LPSTR pszObjId = *(LPSTR *)pvStructInfo;
1149
1150                 *pszObjId = 0;
1151                 sprintf(pszObjId, "%d.%d", pbEncoded[1 + lenBytes] / 40,
1152                  pbEncoded[1 + lenBytes] - (pbEncoded[1 + lenBytes] /
1153                  40) * 40);
1154                 pszObjId += strlen(pszObjId);
1155                 for (ptr = pbEncoded + 2 + lenBytes; ret &&
1156                  ptr - pbEncoded - 1 - lenBytes < dataLen; )
1157                 {
1158                     int val = 0;
1159
1160                     while (ptr - pbEncoded - 1 - lenBytes < dataLen &&
1161                      (*ptr & 0x80))
1162                     {
1163                         val <<= 7;
1164                         val |= *ptr & 0x7f;
1165                         ptr++;
1166                     }
1167                     val <<= 7;
1168                     val |= *ptr++;
1169                     sprintf(pszObjId, ".%d", val);
1170                     pszObjId += strlen(pszObjId);
1171                 }
1172             }
1173             else
1174                 *(LPSTR *)pvStructInfo = NULL;
1175             *pcbStructInfo = bytesNeeded;
1176         }
1177     }
1178     return ret;
1179 }
1180
1181 static BOOL WINAPI CRYPT_AsnDecodeOidInternal(DWORD dwCertEncodingType,
1182  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1183  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1184 {
1185     BOOL ret;
1186
1187     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1188      pDecodePara, pvStructInfo, *pcbStructInfo);
1189
1190     if (pbEncoded[0] == ASN_OBJECTIDENTIFIER)
1191         ret = CRYPT_AsnDecodeOidIgnoreTag(dwCertEncodingType, lpszStructType,
1192          pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
1193          pcbStructInfo);
1194     else
1195     {
1196         SetLastError(CRYPT_E_ASN1_BADTAG);
1197         ret = FALSE;
1198     }
1199     return ret;
1200 }
1201
1202 /* Warning:  assumes pvStructInfo is a CERT_EXTENSION whose pszObjId is set
1203  * ahead of time!
1204  */
1205 static BOOL WINAPI CRYPT_AsnDecodeExtension(DWORD dwCertEncodingType,
1206  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1207  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1208 {
1209     struct AsnDecodeSequenceItem items[] = {
1210      { ASN_OBJECTIDENTIFIER, offsetof(CERT_EXTENSION, pszObjId),
1211        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1212        offsetof(CERT_EXTENSION, pszObjId), 0 },
1213      { ASN_BOOL, offsetof(CERT_EXTENSION, fCritical), CRYPT_AsnDecodeBool,
1214        sizeof(BOOL), TRUE, FALSE, 0, 0 },
1215      { ASN_OCTETSTRING, offsetof(CERT_EXTENSION, Value),
1216        CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_OBJID_BLOB), FALSE, TRUE,
1217        offsetof(CERT_EXTENSION, Value.pbData) },
1218     };
1219     BOOL ret = TRUE;
1220     PCERT_EXTENSION ext = (PCERT_EXTENSION)pvStructInfo;
1221
1222     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags, ext,
1223      *pcbStructInfo);
1224
1225     if (ext)
1226         TRACE("ext->pszObjId is %p\n", ext->pszObjId);
1227     ret = CRYPT_AsnDecodeSequence(X509_ASN_ENCODING, items,
1228      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags, NULL,
1229      ext, pcbStructInfo, ext ? ext->pszObjId : NULL);
1230     if (ext)
1231         TRACE("ext->pszObjId is %p (%s)\n", ext->pszObjId,
1232          debugstr_a(ext->pszObjId));
1233     TRACE("returning %d (%08x)\n", ret, GetLastError());
1234     return ret;
1235 }
1236
1237 static BOOL WINAPI CRYPT_AsnDecodeExtensionsInternal(DWORD dwCertEncodingType,
1238  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1239  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1240 {
1241     BOOL ret = TRUE;
1242     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1243      CRYPT_AsnDecodeExtension, sizeof(CERT_EXTENSION), TRUE,
1244      offsetof(CERT_EXTENSION, pszObjId) };
1245     PCERT_EXTENSIONS exts = (PCERT_EXTENSIONS)pvStructInfo;
1246
1247     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1248      pDecodePara, pvStructInfo, *pcbStructInfo);
1249
1250     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1251      pDecodePara, pvStructInfo, pcbStructInfo, exts ? exts->rgExtension : NULL);
1252     return ret;
1253 }
1254
1255 static BOOL WINAPI CRYPT_AsnDecodeExtensions(DWORD dwCertEncodingType,
1256  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1257  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1258 {
1259     BOOL ret = TRUE;
1260
1261     __TRY
1262     {
1263         ret = CRYPT_AsnDecodeExtensionsInternal(dwCertEncodingType,
1264          lpszStructType, pbEncoded, cbEncoded,
1265          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, pcbStructInfo);
1266         if (ret && pvStructInfo)
1267         {
1268             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1269              pcbStructInfo, *pcbStructInfo);
1270             if (ret)
1271             {
1272                 CERT_EXTENSIONS *exts;
1273
1274                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1275                     pvStructInfo = *(BYTE **)pvStructInfo;
1276                 exts = (CERT_EXTENSIONS *)pvStructInfo;
1277                 exts->rgExtension = (CERT_EXTENSION *)((BYTE *)exts +
1278                  sizeof(CERT_EXTENSIONS));
1279                 ret = CRYPT_AsnDecodeExtensionsInternal(dwCertEncodingType,
1280                  lpszStructType, pbEncoded, cbEncoded,
1281                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
1282                  pcbStructInfo);
1283             }
1284         }
1285     }
1286     __EXCEPT_PAGE_FAULT
1287     {
1288         SetLastError(STATUS_ACCESS_VIOLATION);
1289         ret = FALSE;
1290     }
1291     __ENDTRY
1292     return ret;
1293 }
1294
1295 /* Warning: this assumes the address of value->Value.pbData is already set, in
1296  * order to avoid overwriting memory.  (In some cases, it may change it, if it
1297  * doesn't copy anything to memory.)  Be sure to set it correctly!
1298  */
1299 static BOOL WINAPI CRYPT_AsnDecodeNameValueInternal(DWORD dwCertEncodingType,
1300  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1301  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1302 {
1303     BOOL ret = TRUE;
1304     DWORD dataLen;
1305     CERT_NAME_VALUE *value = (CERT_NAME_VALUE *)pvStructInfo;
1306
1307     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
1308     {
1309         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1310         DWORD bytesNeeded = sizeof(CERT_NAME_VALUE), valueType;
1311
1312         switch (pbEncoded[0])
1313         {
1314         case ASN_OCTETSTRING:
1315             valueType = CERT_RDN_OCTET_STRING;
1316             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1317                 bytesNeeded += dataLen;
1318             break;
1319         case ASN_NUMERICSTRING:
1320             valueType = CERT_RDN_NUMERIC_STRING;
1321             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1322                 bytesNeeded += dataLen;
1323             break;
1324         case ASN_PRINTABLESTRING:
1325             valueType = CERT_RDN_PRINTABLE_STRING;
1326             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1327                 bytesNeeded += dataLen;
1328             break;
1329         case ASN_IA5STRING:
1330             valueType = CERT_RDN_IA5_STRING;
1331             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1332                 bytesNeeded += dataLen;
1333             break;
1334         case ASN_T61STRING:
1335             valueType = CERT_RDN_T61_STRING;
1336             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1337                 bytesNeeded += dataLen;
1338             break;
1339         case ASN_VIDEOTEXSTRING:
1340             valueType = CERT_RDN_VIDEOTEX_STRING;
1341             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1342                 bytesNeeded += dataLen;
1343             break;
1344         case ASN_GRAPHICSTRING:
1345             valueType = CERT_RDN_GRAPHIC_STRING;
1346             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1347                 bytesNeeded += dataLen;
1348             break;
1349         case ASN_VISIBLESTRING:
1350             valueType = CERT_RDN_VISIBLE_STRING;
1351             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1352                 bytesNeeded += dataLen;
1353             break;
1354         case ASN_GENERALSTRING:
1355             valueType = CERT_RDN_GENERAL_STRING;
1356             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1357                 bytesNeeded += dataLen;
1358             break;
1359         case ASN_UNIVERSALSTRING:
1360             FIXME("ASN_UNIVERSALSTRING: unimplemented\n");
1361             SetLastError(CRYPT_E_ASN1_BADTAG);
1362             return FALSE;
1363         case ASN_BMPSTRING:
1364             valueType = CERT_RDN_BMP_STRING;
1365             bytesNeeded += dataLen;
1366             break;
1367         case ASN_UTF8STRING:
1368             valueType = CERT_RDN_UTF8_STRING;
1369             bytesNeeded += MultiByteToWideChar(CP_UTF8, 0,
1370              (LPCSTR)pbEncoded + 1 + lenBytes, dataLen, NULL, 0) * 2;
1371             break;
1372         default:
1373             SetLastError(CRYPT_E_ASN1_BADTAG);
1374             return FALSE;
1375         }
1376
1377         if (!value)
1378             *pcbStructInfo = bytesNeeded;
1379         else if (*pcbStructInfo < bytesNeeded)
1380         {
1381             *pcbStructInfo = bytesNeeded;
1382             SetLastError(ERROR_MORE_DATA);
1383             ret = FALSE;
1384         }
1385         else
1386         {
1387             *pcbStructInfo = bytesNeeded;
1388             value->dwValueType = valueType;
1389             if (dataLen)
1390             {
1391                 DWORD i;
1392
1393                 assert(value->Value.pbData);
1394                 switch (pbEncoded[0])
1395                 {
1396                 case ASN_OCTETSTRING:
1397                 case ASN_NUMERICSTRING:
1398                 case ASN_PRINTABLESTRING:
1399                 case ASN_IA5STRING:
1400                 case ASN_T61STRING:
1401                 case ASN_VIDEOTEXSTRING:
1402                 case ASN_GRAPHICSTRING:
1403                 case ASN_VISIBLESTRING:
1404                 case ASN_GENERALSTRING:
1405                     value->Value.cbData = dataLen;
1406                     if (dataLen)
1407                     {
1408                         if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1409                             memcpy(value->Value.pbData,
1410                              pbEncoded + 1 + lenBytes, dataLen);
1411                         else
1412                             value->Value.pbData = (LPBYTE)pbEncoded + 1 +
1413                              lenBytes;
1414                     }
1415                     break;
1416                 case ASN_BMPSTRING:
1417                 {
1418                     LPWSTR str = (LPWSTR)value->Value.pbData;
1419
1420                     value->Value.cbData = dataLen;
1421                     for (i = 0; i < dataLen / 2; i++)
1422                         str[i] = (pbEncoded[1 + lenBytes + 2 * i] << 8) |
1423                          pbEncoded[1 + lenBytes + 2 * i + 1];
1424                     break;
1425                 }
1426                 case ASN_UTF8STRING:
1427                 {
1428                     LPWSTR str = (LPWSTR)value->Value.pbData;
1429
1430                     value->Value.cbData = MultiByteToWideChar(CP_UTF8, 0,
1431                      (LPCSTR)pbEncoded + 1 + lenBytes, dataLen, 
1432                      str, bytesNeeded - sizeof(CERT_NAME_VALUE)) * 2;
1433                     break;
1434                 }
1435                 }
1436             }
1437             else
1438             {
1439                 value->Value.cbData = 0;
1440                 value->Value.pbData = NULL;
1441             }
1442         }
1443     }
1444     return ret;
1445 }
1446
1447 static BOOL WINAPI CRYPT_AsnDecodeNameValue(DWORD dwCertEncodingType,
1448  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1449  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1450 {
1451     BOOL ret = TRUE;
1452
1453     __TRY
1454     {
1455         ret = CRYPT_AsnDecodeNameValueInternal(dwCertEncodingType,
1456          lpszStructType, pbEncoded, cbEncoded,
1457          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, pcbStructInfo);
1458         if (ret && pvStructInfo)
1459         {
1460             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1461              pcbStructInfo, *pcbStructInfo);
1462             if (ret)
1463             {
1464                 CERT_NAME_VALUE *value;
1465
1466                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1467                     pvStructInfo = *(BYTE **)pvStructInfo;
1468                 value = (CERT_NAME_VALUE *)pvStructInfo;
1469                 value->Value.pbData = ((BYTE *)value + sizeof(CERT_NAME_VALUE));
1470                 ret = CRYPT_AsnDecodeNameValueInternal(dwCertEncodingType,
1471                  lpszStructType, pbEncoded, cbEncoded,
1472                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
1473                  pcbStructInfo);
1474             }
1475         }
1476     }
1477     __EXCEPT_PAGE_FAULT
1478     {
1479         SetLastError(STATUS_ACCESS_VIOLATION);
1480         ret = FALSE;
1481     }
1482     __ENDTRY
1483     return ret;
1484 }
1485
1486 static BOOL WINAPI CRYPT_AsnDecodeUnicodeNameValueInternal(
1487  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
1488  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
1489  void *pvStructInfo, DWORD *pcbStructInfo)
1490 {
1491     BOOL ret = TRUE;
1492     DWORD dataLen;
1493     CERT_NAME_VALUE *value = (CERT_NAME_VALUE *)pvStructInfo;
1494
1495     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
1496     {
1497         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1498         DWORD bytesNeeded = sizeof(CERT_NAME_VALUE), valueType;
1499
1500         switch (pbEncoded[0])
1501         {
1502         case ASN_NUMERICSTRING:
1503             valueType = CERT_RDN_NUMERIC_STRING;
1504             bytesNeeded += dataLen * 2;
1505             break;
1506         case ASN_PRINTABLESTRING:
1507             valueType = CERT_RDN_PRINTABLE_STRING;
1508             bytesNeeded += dataLen * 2;
1509             break;
1510         case ASN_IA5STRING:
1511             valueType = CERT_RDN_IA5_STRING;
1512             bytesNeeded += dataLen * 2;
1513             break;
1514         case ASN_T61STRING:
1515             valueType = CERT_RDN_T61_STRING;
1516             bytesNeeded += dataLen * 2;
1517             break;
1518         case ASN_VIDEOTEXSTRING:
1519             valueType = CERT_RDN_VIDEOTEX_STRING;
1520             bytesNeeded += dataLen * 2;
1521             break;
1522         case ASN_GRAPHICSTRING:
1523             valueType = CERT_RDN_GRAPHIC_STRING;
1524             bytesNeeded += dataLen * 2;
1525             break;
1526         case ASN_VISIBLESTRING:
1527             valueType = CERT_RDN_VISIBLE_STRING;
1528             bytesNeeded += dataLen * 2;
1529             break;
1530         case ASN_GENERALSTRING:
1531             valueType = CERT_RDN_GENERAL_STRING;
1532             bytesNeeded += dataLen * 2;
1533             break;
1534         case ASN_UNIVERSALSTRING:
1535             valueType = CERT_RDN_UNIVERSAL_STRING;
1536             bytesNeeded += dataLen / 2;
1537             break;
1538         case ASN_BMPSTRING:
1539             valueType = CERT_RDN_BMP_STRING;
1540             bytesNeeded += dataLen;
1541             break;
1542         case ASN_UTF8STRING:
1543             valueType = CERT_RDN_UTF8_STRING;
1544             bytesNeeded += MultiByteToWideChar(CP_UTF8, 0,
1545              (LPCSTR)pbEncoded + 1 + lenBytes, dataLen, NULL, 0) * 2;
1546             break;
1547         default:
1548             SetLastError(CRYPT_E_ASN1_BADTAG);
1549             return FALSE;
1550         }
1551
1552         if (!value)
1553             *pcbStructInfo = bytesNeeded;
1554         else if (*pcbStructInfo < bytesNeeded)
1555         {
1556             *pcbStructInfo = bytesNeeded;
1557             SetLastError(ERROR_MORE_DATA);
1558             ret = FALSE;
1559         }
1560         else
1561         {
1562             *pcbStructInfo = bytesNeeded;
1563             value->dwValueType = valueType;
1564             if (dataLen)
1565             {
1566                 DWORD i;
1567                 LPWSTR str = (LPWSTR)value->Value.pbData;
1568
1569                 assert(value->Value.pbData);
1570                 switch (pbEncoded[0])
1571                 {
1572                 case ASN_NUMERICSTRING:
1573                 case ASN_PRINTABLESTRING:
1574                 case ASN_IA5STRING:
1575                 case ASN_T61STRING:
1576                 case ASN_VIDEOTEXSTRING:
1577                 case ASN_GRAPHICSTRING:
1578                 case ASN_VISIBLESTRING:
1579                 case ASN_GENERALSTRING:
1580                     value->Value.cbData = dataLen * 2;
1581                     for (i = 0; i < dataLen; i++)
1582                         str[i] = pbEncoded[1 + lenBytes + i];
1583                     break;
1584                 case ASN_UNIVERSALSTRING:
1585                     value->Value.cbData = dataLen / 2;
1586                     for (i = 0; i < dataLen / 4; i++)
1587                         str[i] = (pbEncoded[1 + lenBytes + 2 * i + 2] << 8)
1588                          | pbEncoded[1 + lenBytes + 2 * i + 3];
1589                     break;
1590                 case ASN_BMPSTRING:
1591                     value->Value.cbData = dataLen;
1592                     for (i = 0; i < dataLen / 2; i++)
1593                         str[i] = (pbEncoded[1 + lenBytes + 2 * i] << 8) |
1594                          pbEncoded[1 + lenBytes + 2 * i + 1];
1595                     break;
1596                 case ASN_UTF8STRING:
1597                     value->Value.cbData = MultiByteToWideChar(CP_UTF8, 0,
1598                      (LPCSTR)pbEncoded + 1 + lenBytes, dataLen,
1599                      str, bytesNeeded - sizeof(CERT_NAME_VALUE)) * 2;
1600                     break;
1601                 }
1602             }
1603             else
1604             {
1605                 value->Value.cbData = 0;
1606                 value->Value.pbData = NULL;
1607             }
1608         }
1609     }
1610     return ret;
1611 }
1612
1613 static BOOL WINAPI CRYPT_AsnDecodeUnicodeNameValue(DWORD dwCertEncodingType,
1614  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1615  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1616 {
1617     BOOL ret = TRUE;
1618
1619     __TRY
1620     {
1621         ret = CRYPT_AsnDecodeUnicodeNameValueInternal(dwCertEncodingType,
1622          lpszStructType, pbEncoded, cbEncoded,
1623          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, pcbStructInfo);
1624         if (ret && pvStructInfo)
1625         {
1626             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1627              pcbStructInfo, *pcbStructInfo);
1628             if (ret)
1629             {
1630                 CERT_NAME_VALUE *value;
1631
1632                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1633                     pvStructInfo = *(BYTE **)pvStructInfo;
1634                 value = (CERT_NAME_VALUE *)pvStructInfo;
1635                 value->Value.pbData = ((BYTE *)value + sizeof(CERT_NAME_VALUE));
1636                 ret = CRYPT_AsnDecodeUnicodeNameValueInternal(
1637                  dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded,
1638                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
1639                  pcbStructInfo);
1640             }
1641         }
1642     }
1643     __EXCEPT_PAGE_FAULT
1644     {
1645         SetLastError(STATUS_ACCESS_VIOLATION);
1646         ret = FALSE;
1647     }
1648     __ENDTRY
1649     return ret;
1650 }
1651
1652 static BOOL WINAPI CRYPT_AsnDecodeRdnAttr(DWORD dwCertEncodingType,
1653  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1654  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1655 {
1656     BOOL ret;
1657     struct AsnDecodeSequenceItem items[] = {
1658      { ASN_OBJECTIDENTIFIER, offsetof(CERT_RDN_ATTR, pszObjId),
1659        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1660        offsetof(CERT_RDN_ATTR, pszObjId), 0 },
1661      { 0, offsetof(CERT_RDN_ATTR, dwValueType),
1662        CRYPT_AsnDecodeNameValueInternal, sizeof(CERT_NAME_VALUE),
1663        FALSE, TRUE, offsetof(CERT_RDN_ATTR, Value.pbData), 0 },
1664     };
1665     CERT_RDN_ATTR *attr = (CERT_RDN_ATTR *)pvStructInfo;
1666
1667     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1668      pvStructInfo, *pcbStructInfo);
1669
1670     if (attr)
1671         TRACE("attr->pszObjId is %p\n", attr->pszObjId);
1672     ret = CRYPT_AsnDecodeSequence(X509_ASN_ENCODING, items,
1673      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags, NULL,
1674      attr, pcbStructInfo, attr ? attr->pszObjId : NULL);
1675     if (attr)
1676     {
1677         TRACE("attr->pszObjId is %p (%s)\n", attr->pszObjId,
1678          debugstr_a(attr->pszObjId));
1679         TRACE("attr->dwValueType is %d\n", attr->dwValueType);
1680     }
1681     TRACE("returning %d (%08x)\n", ret, GetLastError());
1682     return ret;
1683 }
1684
1685 static BOOL WINAPI CRYPT_AsnDecodeRdn(DWORD dwCertEncodingType,
1686  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1687  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1688 {
1689     BOOL ret = TRUE;
1690     struct AsnArrayDescriptor arrayDesc = { ASN_CONSTRUCTOR | ASN_SETOF,
1691      CRYPT_AsnDecodeRdnAttr, sizeof(CERT_RDN_ATTR), TRUE,
1692      offsetof(CERT_RDN_ATTR, pszObjId) };
1693     PCERT_RDN rdn = (PCERT_RDN)pvStructInfo;
1694
1695     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1696      pDecodePara, pvStructInfo, pcbStructInfo, rdn ? rdn->rgRDNAttr : NULL);
1697     return ret;
1698 }
1699
1700 static BOOL WINAPI CRYPT_AsnDecodeName(DWORD dwCertEncodingType,
1701  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1702  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1703 {
1704     BOOL ret = TRUE;
1705
1706     __TRY
1707     {
1708         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1709          CRYPT_AsnDecodeRdn, sizeof(CERT_RDN), TRUE,
1710          offsetof(CERT_RDN, rgRDNAttr) };
1711
1712         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1713          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
1714     }
1715     __EXCEPT_PAGE_FAULT
1716     {
1717         SetLastError(STATUS_ACCESS_VIOLATION);
1718         ret = FALSE;
1719     }
1720     __ENDTRY
1721     return ret;
1722 }
1723
1724 static BOOL WINAPI CRYPT_AsnDecodeUnicodeRdnAttr(DWORD dwCertEncodingType,
1725  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1726  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1727 {
1728     BOOL ret;
1729     struct AsnDecodeSequenceItem items[] = {
1730      { ASN_OBJECTIDENTIFIER, offsetof(CERT_RDN_ATTR, pszObjId),
1731        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1732        offsetof(CERT_RDN_ATTR, pszObjId), 0 },
1733      { 0, offsetof(CERT_RDN_ATTR, dwValueType),
1734        CRYPT_AsnDecodeUnicodeNameValueInternal, sizeof(CERT_NAME_VALUE),
1735        FALSE, TRUE, offsetof(CERT_RDN_ATTR, Value.pbData), 0 },
1736     };
1737     CERT_RDN_ATTR *attr = (CERT_RDN_ATTR *)pvStructInfo;
1738
1739     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1740      pvStructInfo, *pcbStructInfo);
1741
1742     if (attr)
1743         TRACE("attr->pszObjId is %p\n", attr->pszObjId);
1744     ret = CRYPT_AsnDecodeSequence(X509_ASN_ENCODING, items,
1745      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags, NULL,
1746      attr, pcbStructInfo, attr ? attr->pszObjId : NULL);
1747     if (attr)
1748     {
1749         TRACE("attr->pszObjId is %p (%s)\n", attr->pszObjId,
1750          debugstr_a(attr->pszObjId));
1751         TRACE("attr->dwValueType is %d\n", attr->dwValueType);
1752     }
1753     TRACE("returning %d (%08x)\n", ret, GetLastError());
1754     return ret;
1755 }
1756
1757 static BOOL WINAPI CRYPT_AsnDecodeUnicodeRdn(DWORD dwCertEncodingType,
1758  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1759  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1760 {
1761     BOOL ret = TRUE;
1762     struct AsnArrayDescriptor arrayDesc = { ASN_CONSTRUCTOR | ASN_SETOF,
1763      CRYPT_AsnDecodeUnicodeRdnAttr, sizeof(CERT_RDN_ATTR), TRUE,
1764      offsetof(CERT_RDN_ATTR, pszObjId) };
1765     PCERT_RDN rdn = (PCERT_RDN)pvStructInfo;
1766
1767     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1768      pDecodePara, pvStructInfo, pcbStructInfo, rdn ? rdn->rgRDNAttr : NULL);
1769     return ret;
1770 }
1771
1772 static BOOL WINAPI CRYPT_AsnDecodeUnicodeName(DWORD dwCertEncodingType,
1773  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1774  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1775 {
1776     BOOL ret = TRUE;
1777
1778     __TRY
1779     {
1780         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1781          CRYPT_AsnDecodeUnicodeRdn, sizeof(CERT_RDN), TRUE,
1782          offsetof(CERT_RDN, rgRDNAttr) };
1783
1784         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1785          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
1786     }
1787     __EXCEPT_PAGE_FAULT
1788     {
1789         SetLastError(STATUS_ACCESS_VIOLATION);
1790         ret = FALSE;
1791     }
1792     __ENDTRY
1793     return ret;
1794 }
1795
1796 static BOOL WINAPI CRYPT_AsnDecodeCopyBytes(DWORD dwCertEncodingType,
1797  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1798  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1799 {
1800     BOOL ret = TRUE;
1801     DWORD bytesNeeded = sizeof(CRYPT_OBJID_BLOB);
1802
1803     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1804      pDecodePara, pvStructInfo, *pcbStructInfo);
1805
1806     if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1807         bytesNeeded += cbEncoded;
1808     if (!pvStructInfo)
1809         *pcbStructInfo = bytesNeeded;
1810     else if (*pcbStructInfo < bytesNeeded)
1811     {
1812         SetLastError(ERROR_MORE_DATA);
1813         *pcbStructInfo = bytesNeeded;
1814         ret = FALSE;
1815     }
1816     else
1817     {
1818         PCRYPT_OBJID_BLOB blob = (PCRYPT_OBJID_BLOB)pvStructInfo;
1819
1820         *pcbStructInfo = bytesNeeded;
1821         blob->cbData = cbEncoded;
1822         if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
1823             blob->pbData = (LPBYTE)pbEncoded;
1824         else
1825         {
1826             assert(blob->pbData);
1827             memcpy(blob->pbData, pbEncoded, blob->cbData);
1828         }
1829     }
1830     return ret;
1831 }
1832
1833 static BOOL WINAPI CRYPT_DecodeDERArray(DWORD dwCertEncodingType,
1834  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1835  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1836 {
1837     BOOL ret;
1838     struct AsnArrayDescriptor arrayDesc = { 0, CRYPT_AsnDecodeCopyBytes,
1839      sizeof(CRYPT_DER_BLOB), TRUE, offsetof(CRYPT_DER_BLOB, pbData) };
1840     struct GenericArray *array = (struct GenericArray *)pvStructInfo;
1841
1842     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1843      pDecodePara, pvStructInfo, *pcbStructInfo);
1844
1845     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1846      pDecodePara, pvStructInfo, pcbStructInfo, array ? array->rgItems : NULL);
1847     return ret;
1848 }
1849
1850 static BOOL WINAPI CRYPT_AsnDecodePKCSAttribute(DWORD dwCertEncodingType,
1851  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1852  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1853 {
1854     BOOL ret = FALSE;
1855
1856     __TRY
1857     {
1858         struct AsnDecodeSequenceItem items[] = {
1859          { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_ATTRIBUTE, pszObjId),
1860            CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1861            offsetof(CRYPT_ATTRIBUTE, pszObjId), 0 },
1862          { ASN_CONSTRUCTOR | ASN_SETOF, offsetof(CRYPT_ATTRIBUTE, cValue),
1863            CRYPT_DecodeDERArray, sizeof(struct GenericArray), FALSE, TRUE,
1864            offsetof(CRYPT_ATTRIBUTE, rgValue), 0 },
1865         };
1866         PCRYPT_ATTRIBUTE attr = (PCRYPT_ATTRIBUTE)pvStructInfo;
1867
1868         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
1869          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
1870          pDecodePara, pvStructInfo, pcbStructInfo, attr ? attr->pszObjId :
1871          NULL);
1872     }
1873     __EXCEPT_PAGE_FAULT
1874     {
1875         SetLastError(STATUS_ACCESS_VIOLATION);
1876     }
1877     __ENDTRY
1878     TRACE("returning %d\n", ret);
1879     return ret;
1880 }
1881
1882 static BOOL WINAPI CRYPT_AsnDecodePKCSAttributesInternal(
1883  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
1884  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
1885  void *pvStructInfo, DWORD *pcbStructInfo)
1886 {
1887     struct AsnArrayDescriptor arrayDesc = { 0, CRYPT_AsnDecodePKCSAttribute,
1888      sizeof(CRYPT_ATTRIBUTE), TRUE, offsetof(CRYPT_ATTRIBUTE, pszObjId) };
1889     PCRYPT_ATTRIBUTES attrs = (PCRYPT_ATTRIBUTES)pvStructInfo;
1890     BOOL ret;
1891
1892     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1893      pDecodePara, pvStructInfo, pcbStructInfo, attrs ? attrs->rgAttr :
1894      NULL);
1895     return ret;
1896 }
1897
1898 static BOOL WINAPI CRYPT_AsnDecodePKCSAttributes(DWORD dwCertEncodingType,
1899  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1900  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1901 {
1902     BOOL ret = FALSE;
1903
1904     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1905      pDecodePara, pvStructInfo, *pcbStructInfo);
1906
1907     __TRY
1908     {
1909         DWORD bytesNeeded;
1910
1911         if (!cbEncoded)
1912             SetLastError(CRYPT_E_ASN1_EOD);
1913         else if (pbEncoded[0] != (ASN_CONSTRUCTOR | ASN_SETOF))
1914             SetLastError(CRYPT_E_ASN1_CORRUPT);
1915         else if ((ret = CRYPT_AsnDecodePKCSAttributesInternal(
1916          dwCertEncodingType, lpszStructType, pbEncoded, cbEncoded,
1917          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, &bytesNeeded)))
1918         {
1919             if (!pvStructInfo)
1920                 *pcbStructInfo = bytesNeeded;
1921             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
1922              pvStructInfo, pcbStructInfo, bytesNeeded)))
1923             {
1924                 PCRYPT_ATTRIBUTES attrs;
1925
1926                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1927                     pvStructInfo = *(BYTE **)pvStructInfo;
1928                 attrs = (PCRYPT_ATTRIBUTES)pvStructInfo;
1929                 attrs->rgAttr = (PCRYPT_ATTRIBUTE)((BYTE *)pvStructInfo +
1930                  sizeof(CRYPT_ATTRIBUTES));
1931                 ret = CRYPT_AsnDecodePKCSAttributesInternal(dwCertEncodingType,
1932                  lpszStructType, pbEncoded, cbEncoded,
1933                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
1934                  &bytesNeeded);
1935             }
1936         }
1937     }
1938     __EXCEPT_PAGE_FAULT
1939     {
1940         SetLastError(STATUS_ACCESS_VIOLATION);
1941     }
1942     __ENDTRY
1943     TRACE("returning %d\n", ret);
1944     return ret;
1945 }
1946
1947 static BOOL WINAPI CRYPT_AsnDecodeAlgorithmId(DWORD dwCertEncodingType,
1948  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1949  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1950 {
1951     CRYPT_ALGORITHM_IDENTIFIER *algo =
1952      (CRYPT_ALGORITHM_IDENTIFIER *)pvStructInfo;
1953     BOOL ret = TRUE;
1954     struct AsnDecodeSequenceItem items[] = {
1955      { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_ALGORITHM_IDENTIFIER, pszObjId),
1956        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1957        offsetof(CRYPT_ALGORITHM_IDENTIFIER, pszObjId), 0 },
1958      { 0, offsetof(CRYPT_ALGORITHM_IDENTIFIER, Parameters),
1959        CRYPT_AsnDecodeCopyBytes, sizeof(CRYPT_OBJID_BLOB), TRUE, TRUE, 
1960        offsetof(CRYPT_ALGORITHM_IDENTIFIER, Parameters.pbData), 0 },
1961     };
1962
1963     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1964      pDecodePara, pvStructInfo, *pcbStructInfo);
1965
1966     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
1967      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
1968      pDecodePara, pvStructInfo, pcbStructInfo, algo ? algo->pszObjId : NULL);
1969     if (ret && pvStructInfo)
1970     {
1971         TRACE("pszObjId is %p (%s)\n", algo->pszObjId,
1972          debugstr_a(algo->pszObjId));
1973     }
1974     return ret;
1975 }
1976
1977 static BOOL WINAPI CRYPT_AsnDecodePubKeyInfoInternal(DWORD dwCertEncodingType,
1978  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1979  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1980 {
1981     BOOL ret = TRUE;
1982     struct AsnDecodeSequenceItem items[] = {
1983      { ASN_SEQUENCEOF, offsetof(CERT_PUBLIC_KEY_INFO, Algorithm),
1984        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
1985        FALSE, TRUE, offsetof(CERT_PUBLIC_KEY_INFO,
1986        Algorithm.pszObjId) },
1987      { ASN_BITSTRING, offsetof(CERT_PUBLIC_KEY_INFO, PublicKey),
1988        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), FALSE, TRUE,
1989        offsetof(CERT_PUBLIC_KEY_INFO, PublicKey.pbData) },
1990     };
1991     PCERT_PUBLIC_KEY_INFO info = (PCERT_PUBLIC_KEY_INFO)pvStructInfo;
1992
1993     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
1994      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
1995      pDecodePara, pvStructInfo, pcbStructInfo, info ?
1996      info->Algorithm.Parameters.pbData : NULL);
1997     return ret;
1998 }
1999
2000 static BOOL WINAPI CRYPT_AsnDecodePubKeyInfo(DWORD dwCertEncodingType,
2001  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2002  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2003 {
2004     BOOL ret = TRUE;
2005
2006     __TRY
2007     {
2008         DWORD bytesNeeded;
2009
2010         if ((ret = CRYPT_AsnDecodePubKeyInfoInternal(dwCertEncodingType,
2011          lpszStructType, pbEncoded, cbEncoded,
2012          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, &bytesNeeded)))
2013         {
2014             if (!pvStructInfo)
2015                 *pcbStructInfo = bytesNeeded;
2016             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2017              pvStructInfo, pcbStructInfo, bytesNeeded)))
2018             {
2019                 PCERT_PUBLIC_KEY_INFO info;
2020
2021                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2022                     pvStructInfo = *(BYTE **)pvStructInfo;
2023                 info = (PCERT_PUBLIC_KEY_INFO)pvStructInfo;
2024                 info->Algorithm.Parameters.pbData = (BYTE *)pvStructInfo +
2025                  sizeof(CERT_PUBLIC_KEY_INFO);
2026                 ret = CRYPT_AsnDecodePubKeyInfoInternal(dwCertEncodingType,
2027                  lpszStructType, pbEncoded, cbEncoded,
2028                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
2029                  &bytesNeeded);
2030             }
2031         }
2032     }
2033     __EXCEPT_PAGE_FAULT
2034     {
2035         SetLastError(STATUS_ACCESS_VIOLATION);
2036         ret = FALSE;
2037     }
2038     __ENDTRY
2039     return ret;
2040 }
2041
2042 static BOOL WINAPI CRYPT_AsnDecodeBool(DWORD dwCertEncodingType,
2043  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2044  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2045 {
2046     BOOL ret;
2047
2048     if (cbEncoded < 3)
2049     {
2050         SetLastError(CRYPT_E_ASN1_CORRUPT);
2051         return FALSE;
2052     }
2053     if (GET_LEN_BYTES(pbEncoded[1]) > 1)
2054     {
2055         SetLastError(CRYPT_E_ASN1_CORRUPT);
2056         return FALSE;
2057     }
2058     if (pbEncoded[1] > 1)
2059     {
2060         SetLastError(CRYPT_E_ASN1_CORRUPT);
2061         return FALSE;
2062     }
2063     if (!pvStructInfo)
2064     {
2065         *pcbStructInfo = sizeof(BOOL);
2066         ret = TRUE;
2067     }
2068     else if (*pcbStructInfo < sizeof(BOOL))
2069     {
2070         *pcbStructInfo = sizeof(BOOL);
2071         SetLastError(ERROR_MORE_DATA);
2072         ret = FALSE;
2073     }
2074     else
2075     {
2076         *(BOOL *)pvStructInfo = pbEncoded[2] ? TRUE : FALSE;
2077         ret = TRUE;
2078     }
2079     TRACE("returning %d (%08x)\n", ret, GetLastError());
2080     return ret;
2081 }
2082
2083 static BOOL WINAPI CRYPT_AsnDecodeAltNameEntry(DWORD dwCertEncodingType,
2084  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2085  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2086 {
2087     PCERT_ALT_NAME_ENTRY entry = (PCERT_ALT_NAME_ENTRY)pvStructInfo;
2088     DWORD dataLen, lenBytes, bytesNeeded = sizeof(CERT_ALT_NAME_ENTRY);
2089     BOOL ret;
2090
2091     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2092      pDecodePara, pvStructInfo, *pcbStructInfo);
2093
2094     if (cbEncoded < 2)
2095     {
2096         SetLastError(CRYPT_E_ASN1_CORRUPT);
2097         return FALSE;
2098     }
2099     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2100     if (1 + lenBytes > cbEncoded)
2101     {
2102         SetLastError(CRYPT_E_ASN1_CORRUPT);
2103         return FALSE;
2104     }
2105     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2106     {
2107         switch (pbEncoded[0] & ASN_TYPE_MASK)
2108         {
2109         case 1: /* rfc822Name */
2110         case 2: /* dNSName */
2111         case 6: /* uniformResourceIdentifier */
2112             bytesNeeded += (dataLen + 1) * sizeof(WCHAR);
2113             break;
2114         case 4: /* directoryName */
2115         case 7: /* iPAddress */
2116             bytesNeeded += dataLen;
2117             break;
2118         case 8: /* registeredID */
2119             ret = CRYPT_AsnDecodeOidIgnoreTag(dwCertEncodingType, NULL,
2120              pbEncoded, cbEncoded, 0, NULL, NULL, &dataLen);
2121             if (ret)
2122             {
2123                 /* FIXME: ugly, shouldn't need to know internals of OID decode
2124                  * function to use it.
2125                  */
2126                 bytesNeeded += dataLen - sizeof(LPSTR);
2127             }
2128             break;
2129         case 0: /* otherName */
2130             FIXME("%d: stub\n", pbEncoded[0] & ASN_TYPE_MASK);
2131             SetLastError(CRYPT_E_ASN1_BADTAG);
2132             ret = FALSE;
2133             break;
2134         case 3: /* x400Address, unimplemented */
2135         case 5: /* ediPartyName, unimplemented */
2136             TRACE("type %d unimplemented\n", pbEncoded[0] & ASN_TYPE_MASK);
2137             SetLastError(CRYPT_E_ASN1_BADTAG);
2138             ret = FALSE;
2139             break;
2140         default:
2141             TRACE("type %d bad\n", pbEncoded[0] & ASN_TYPE_MASK);
2142             SetLastError(CRYPT_E_ASN1_CORRUPT);
2143             ret = FALSE;
2144         }
2145         if (ret)
2146         {
2147             if (!entry)
2148                 *pcbStructInfo = bytesNeeded;
2149             else if (*pcbStructInfo < bytesNeeded)
2150             {
2151                 *pcbStructInfo = bytesNeeded;
2152                 SetLastError(ERROR_MORE_DATA);
2153                 ret = FALSE;
2154             }
2155             else
2156             {
2157                 *pcbStructInfo = bytesNeeded;
2158                 /* MS used values one greater than the asn1 ones.. sigh */
2159                 entry->dwAltNameChoice = (pbEncoded[0] & 0x7f) + 1;
2160                 switch (pbEncoded[0] & ASN_TYPE_MASK)
2161                 {
2162                 case 1: /* rfc822Name */
2163                 case 2: /* dNSName */
2164                 case 6: /* uniformResourceIdentifier */
2165                 {
2166                     DWORD i;
2167
2168                     for (i = 0; i < dataLen; i++)
2169                         entry->u.pwszURL[i] =
2170                          (WCHAR)pbEncoded[1 + lenBytes + i];
2171                     entry->u.pwszURL[i] = 0;
2172                     TRACE("URL is %p (%s)\n", entry->u.pwszURL,
2173                      debugstr_w(entry->u.pwszURL));
2174                     break;
2175                 }
2176                 case 4: /* directoryName */
2177                     entry->dwAltNameChoice = CERT_ALT_NAME_DIRECTORY_NAME;
2178                     /* The data are memory-equivalent with the IPAddress case,
2179                      * fall-through
2180                      */
2181                 case 7: /* iPAddress */
2182                     /* The next data pointer is in the pwszURL spot, that is,
2183                      * the first 4 bytes.  Need to move it to the next spot.
2184                      */
2185                     entry->u.IPAddress.pbData = (LPBYTE)entry->u.pwszURL;
2186                     entry->u.IPAddress.cbData = dataLen;
2187                     memcpy(entry->u.IPAddress.pbData, pbEncoded + 1 + lenBytes,
2188                      dataLen);
2189                     break;
2190                 case 8: /* registeredID */
2191                     ret = CRYPT_AsnDecodeOidIgnoreTag(dwCertEncodingType, NULL,
2192                      pbEncoded, cbEncoded, 0, NULL, &entry->u.pszRegisteredID,
2193                      &dataLen);
2194                     break;
2195                 }
2196             }
2197         }
2198     }
2199     return ret;
2200 }
2201
2202 static BOOL WINAPI CRYPT_AsnDecodeAltNameInternal(DWORD dwCertEncodingType,
2203  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2204  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2205 {
2206     BOOL ret = TRUE;
2207     struct AsnArrayDescriptor arrayDesc = { 0,
2208      CRYPT_AsnDecodeAltNameEntry, sizeof(CERT_ALT_NAME_ENTRY), TRUE,
2209      offsetof(CERT_ALT_NAME_ENTRY, u.pwszURL) };
2210     PCERT_ALT_NAME_INFO info = (PCERT_ALT_NAME_INFO)pvStructInfo;
2211
2212     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2213      pDecodePara, pvStructInfo, *pcbStructInfo);
2214
2215     if (info)
2216         TRACE("info->rgAltEntry is %p\n", info->rgAltEntry);
2217     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2218      pDecodePara, pvStructInfo, pcbStructInfo, info ? info->rgAltEntry : NULL);
2219     return ret;
2220 }
2221
2222 /* Like CRYPT_AsnDecodeIntegerInternal, but swaps the bytes */
2223 static BOOL WINAPI CRYPT_AsnDecodeIntegerSwapBytes(DWORD dwCertEncodingType,
2224  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2225  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2226 {
2227     BOOL ret;
2228
2229     TRACE("(%p, %d, 0x%08x, %p, %p, %d)\n", pbEncoded, cbEncoded, dwFlags,
2230      pDecodePara, pvStructInfo, *pcbStructInfo);
2231
2232     /* Can't use the CRYPT_DECODE_NOCOPY_FLAG, because we modify the bytes in-
2233      * place.
2234      */
2235     ret = CRYPT_AsnDecodeIntegerInternal(dwCertEncodingType, lpszStructType,
2236      pbEncoded, cbEncoded, dwFlags & ~CRYPT_DECODE_NOCOPY_FLAG, pDecodePara,
2237      pvStructInfo, pcbStructInfo);
2238     if (ret && pvStructInfo)
2239     {
2240         CRYPT_DATA_BLOB *blob = (CRYPT_DATA_BLOB *)pvStructInfo;
2241
2242         if (blob->cbData)
2243         {
2244             DWORD i;
2245             BYTE temp;
2246
2247             for (i = 0; i < blob->cbData / 2; i++)
2248             {
2249                 temp = blob->pbData[i];
2250                 blob->pbData[i] = blob->pbData[blob->cbData - i - 1];
2251                 blob->pbData[blob->cbData - i - 1] = temp;
2252             }
2253         }
2254     }
2255     TRACE("returning %d (%08x)\n", ret, GetLastError());
2256     return ret;
2257 }
2258
2259 static BOOL WINAPI CRYPT_AsnDecodeAuthorityKeyId(DWORD dwCertEncodingType,
2260  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2261  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2262 {
2263     BOOL ret;
2264
2265     __TRY
2266     {
2267         struct AsnDecodeSequenceItem items[] = {
2268          { ASN_CONTEXT | 0, offsetof(CERT_AUTHORITY_KEY_ID_INFO, KeyId),
2269            CRYPT_AsnDecodeIntegerSwapBytes, sizeof(CRYPT_DATA_BLOB),
2270            TRUE, TRUE, offsetof(CERT_AUTHORITY_KEY_ID_INFO, KeyId.pbData), 0 },
2271          { ASN_CONTEXT | ASN_CONSTRUCTOR| 1,
2272            offsetof(CERT_AUTHORITY_KEY_ID_INFO, CertIssuer),
2273            CRYPT_AsnDecodeOctetsInternal, sizeof(CERT_NAME_BLOB), TRUE, TRUE,
2274            offsetof(CERT_AUTHORITY_KEY_ID_INFO, CertIssuer.pbData), 0 },
2275          { ASN_CONTEXT | 2, offsetof(CERT_AUTHORITY_KEY_ID_INFO,
2276            CertSerialNumber), CRYPT_AsnDecodeIntegerInternal,
2277            sizeof(CRYPT_INTEGER_BLOB), TRUE, TRUE,
2278            offsetof(CERT_AUTHORITY_KEY_ID_INFO, CertSerialNumber.pbData), 0 },
2279         };
2280
2281         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
2282          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2283          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
2284     }
2285     __EXCEPT_PAGE_FAULT
2286     {
2287         SetLastError(STATUS_ACCESS_VIOLATION);
2288         ret = FALSE;
2289     }
2290     __ENDTRY
2291     return ret;
2292 }
2293
2294 static BOOL WINAPI CRYPT_AsnDecodeAuthorityKeyId2(DWORD dwCertEncodingType,
2295  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2296  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2297 {
2298     BOOL ret;
2299
2300     __TRY
2301     {
2302         struct AsnDecodeSequenceItem items[] = {
2303          { ASN_CONTEXT | 0, offsetof(CERT_AUTHORITY_KEY_ID2_INFO, KeyId),
2304            CRYPT_AsnDecodeIntegerSwapBytes, sizeof(CRYPT_DATA_BLOB),
2305            TRUE, TRUE, offsetof(CERT_AUTHORITY_KEY_ID2_INFO, KeyId.pbData), 0 },
2306          { ASN_CONTEXT | ASN_CONSTRUCTOR| 1,
2307            offsetof(CERT_AUTHORITY_KEY_ID2_INFO, AuthorityCertIssuer),
2308            CRYPT_AsnDecodeAltNameInternal, sizeof(CERT_ALT_NAME_INFO), TRUE,
2309            TRUE, offsetof(CERT_AUTHORITY_KEY_ID2_INFO,
2310            AuthorityCertIssuer.rgAltEntry), 0 },
2311          { ASN_CONTEXT | 2, offsetof(CERT_AUTHORITY_KEY_ID2_INFO,
2312            AuthorityCertSerialNumber), CRYPT_AsnDecodeIntegerInternal,
2313            sizeof(CRYPT_INTEGER_BLOB), TRUE, TRUE,
2314            offsetof(CERT_AUTHORITY_KEY_ID2_INFO,
2315            AuthorityCertSerialNumber.pbData), 0 },
2316         };
2317
2318         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
2319          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2320          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
2321     }
2322     __EXCEPT_PAGE_FAULT
2323     {
2324         SetLastError(STATUS_ACCESS_VIOLATION);
2325         ret = FALSE;
2326     }
2327     __ENDTRY
2328     return ret;
2329 }
2330
2331 static BOOL WINAPI CRYPT_AsnDecodePKCSContent(DWORD dwCertEncodingType,
2332  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2333  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2334 {
2335     BOOL ret;
2336     DWORD dataLen;
2337
2338     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2339      pDecodePara, pvStructInfo, *pcbStructInfo);
2340
2341     /* The caller has already checked the tag, no need to check it again.
2342      * Check the outer length is valid by calling CRYPT_GetLen:
2343      */
2344     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2345     {
2346         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2347         DWORD innerLen;
2348
2349         pbEncoded += 1 + lenBytes;
2350         /* Check the inner length is valid by calling CRYPT_GetLen again: */
2351         if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &innerLen)))
2352         {
2353             ret = CRYPT_AsnDecodeCopyBytes(dwCertEncodingType, NULL,
2354              pbEncoded, dataLen, dwFlags, pDecodePara, pvStructInfo,
2355              pcbStructInfo);
2356         }
2357     }
2358     return ret;
2359 }
2360
2361 static BOOL WINAPI CRYPT_AsnDecodePKCSContentInfoInternal(
2362  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
2363  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
2364  void *pvStructInfo, DWORD *pcbStructInfo)
2365 {
2366     CRYPT_CONTENT_INFO *info = (CRYPT_CONTENT_INFO *)pvStructInfo;
2367     struct AsnDecodeSequenceItem items[] = {
2368      { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_CONTENT_INFO, pszObjId),
2369        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
2370        offsetof(CRYPT_CONTENT_INFO, pszObjId), 0 },
2371      { ASN_CONTEXT | ASN_CONSTRUCTOR | 0,
2372        offsetof(CRYPT_CONTENT_INFO, Content), CRYPT_AsnDecodePKCSContent,
2373        sizeof(CRYPT_DER_BLOB), TRUE, TRUE,
2374        offsetof(CRYPT_CONTENT_INFO, Content.pbData), 0 },
2375     };
2376     BOOL ret;
2377
2378     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2379      pDecodePara, pvStructInfo, *pcbStructInfo);
2380
2381     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
2382      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2383      pDecodePara, pvStructInfo, pcbStructInfo, info ? info->pszObjId : NULL);
2384     return ret;
2385 }
2386
2387 static BOOL WINAPI CRYPT_AsnDecodePKCSContentInfo(DWORD dwCertEncodingType,
2388  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2389  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2390 {
2391     BOOL ret = FALSE;
2392
2393     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2394      pDecodePara, pvStructInfo, *pcbStructInfo);
2395
2396     __TRY
2397     {
2398         ret = CRYPT_AsnDecodePKCSContentInfoInternal(dwCertEncodingType,
2399          lpszStructType, pbEncoded, cbEncoded,
2400          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, pcbStructInfo);
2401         if (ret && pvStructInfo)
2402         {
2403             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2404              pcbStructInfo, *pcbStructInfo);
2405             if (ret)
2406             {
2407                 CRYPT_CONTENT_INFO *info;
2408
2409                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2410                     pvStructInfo = *(BYTE **)pvStructInfo;
2411                 info = (CRYPT_CONTENT_INFO *)pvStructInfo;
2412                 info->pszObjId = (LPSTR)((BYTE *)info +
2413                  sizeof(CRYPT_CONTENT_INFO));
2414                 ret = CRYPT_AsnDecodePKCSContentInfoInternal(dwCertEncodingType,
2415                  lpszStructType, pbEncoded, cbEncoded,
2416                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
2417                  pcbStructInfo);
2418             }
2419         }
2420     }
2421     __EXCEPT_PAGE_FAULT
2422     {
2423         SetLastError(STATUS_ACCESS_VIOLATION);
2424     }
2425     __ENDTRY
2426     return ret;
2427 }
2428
2429 BOOL CRYPT_AsnDecodePKCSDigestedData(const BYTE *pbEncoded, DWORD cbEncoded,
2430  DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
2431  CRYPT_DIGESTED_DATA *digestedData, DWORD *pcbDigestedData)
2432 {
2433     BOOL ret;
2434     struct AsnDecodeSequenceItem items[] = {
2435      { ASN_INTEGER, offsetof(CRYPT_DIGESTED_DATA, version), CRYPT_AsnDecodeInt,
2436        sizeof(DWORD), FALSE, FALSE, 0, 0 },
2437      { ASN_SEQUENCEOF, offsetof(CRYPT_DIGESTED_DATA, DigestAlgorithm),
2438        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
2439        FALSE, TRUE, offsetof(CRYPT_DIGESTED_DATA, DigestAlgorithm.pszObjId),
2440        0 },
2441      { ASN_SEQUENCEOF, offsetof(CRYPT_DIGESTED_DATA, ContentInfo),
2442        CRYPT_AsnDecodePKCSContentInfoInternal,
2443        sizeof(CRYPT_CONTENT_INFO), FALSE, TRUE, offsetof(CRYPT_DIGESTED_DATA,
2444        ContentInfo.pszObjId), 0 },
2445      { ASN_OCTETSTRING, offsetof(CRYPT_DIGESTED_DATA, hash),
2446        CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_HASH_BLOB), FALSE, TRUE,
2447        offsetof(CRYPT_DIGESTED_DATA, hash.pbData), 0 },
2448     };
2449
2450     ret = CRYPT_AsnDecodeSequence(X509_ASN_ENCODING, items,
2451      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2452      pDecodePara, digestedData, pcbDigestedData, NULL);
2453     return ret;
2454 }
2455
2456 static BOOL WINAPI CRYPT_AsnDecodeAltName(DWORD dwCertEncodingType,
2457  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2458  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2459 {
2460     BOOL ret = TRUE;
2461
2462     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2463      pDecodePara, pvStructInfo, *pcbStructInfo);
2464
2465     __TRY
2466     {
2467         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
2468          CRYPT_AsnDecodeAltNameEntry, sizeof(CERT_ALT_NAME_ENTRY), TRUE,
2469          offsetof(CERT_ALT_NAME_ENTRY, u.pwszURL) };
2470
2471         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2472          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
2473     }
2474     __EXCEPT_PAGE_FAULT
2475     {
2476         SetLastError(STATUS_ACCESS_VIOLATION);
2477         ret = FALSE;
2478     }
2479     __ENDTRY
2480     return ret;
2481 }
2482
2483 struct PATH_LEN_CONSTRAINT
2484 {
2485     BOOL  fPathLenConstraint;
2486     DWORD dwPathLenConstraint;
2487 };
2488
2489 static BOOL WINAPI CRYPT_AsnDecodePathLenConstraint(DWORD dwCertEncodingType,
2490  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2491  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2492 {
2493     BOOL ret = TRUE;
2494
2495     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2496      pvStructInfo, *pcbStructInfo);
2497
2498     if (cbEncoded)
2499     {
2500         if (pbEncoded[0] == ASN_INTEGER)
2501         {
2502             DWORD bytesNeeded = sizeof(struct PATH_LEN_CONSTRAINT);
2503
2504             if (!pvStructInfo)
2505                 *pcbStructInfo = bytesNeeded;
2506             else if (*pcbStructInfo < bytesNeeded)
2507             {
2508                 SetLastError(ERROR_MORE_DATA);
2509                 *pcbStructInfo = bytesNeeded;
2510                 ret = FALSE;
2511             }
2512             else
2513             {
2514                 struct PATH_LEN_CONSTRAINT *constraint =
2515                  (struct PATH_LEN_CONSTRAINT *)pvStructInfo;
2516                 DWORD size = sizeof(constraint->dwPathLenConstraint);
2517
2518                 ret = CRYPT_AsnDecodeInt(dwCertEncodingType, X509_INTEGER,
2519                  pbEncoded, cbEncoded, 0, NULL,
2520                  &constraint->dwPathLenConstraint, &size);
2521                 if (ret)
2522                     constraint->fPathLenConstraint = TRUE;
2523                 TRACE("got an int, dwPathLenConstraint is %d\n",
2524                  constraint->dwPathLenConstraint);
2525             }
2526         }
2527         else
2528         {
2529             SetLastError(CRYPT_E_ASN1_CORRUPT);
2530             ret = FALSE;
2531         }
2532     }
2533     TRACE("returning %d (%08x)\n", ret, GetLastError());
2534     return ret;
2535 }
2536
2537 static BOOL WINAPI CRYPT_AsnDecodeSubtreeConstraints(DWORD dwCertEncodingType,
2538  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2539  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2540 {
2541     BOOL ret;
2542     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
2543      CRYPT_AsnDecodeCopyBytes, sizeof(CERT_NAME_BLOB), TRUE,
2544      offsetof(CERT_NAME_BLOB, pbData) };
2545     struct GenericArray *entries = (struct GenericArray *)pvStructInfo;
2546
2547     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2548      pDecodePara, pvStructInfo, *pcbStructInfo);
2549
2550     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2551      pDecodePara, pvStructInfo, pcbStructInfo,
2552      entries ? entries->rgItems : NULL);
2553     TRACE("Returning %d (%08x)\n", ret, GetLastError());
2554     return ret;
2555 }
2556
2557 static BOOL WINAPI CRYPT_AsnDecodeBasicConstraints(DWORD dwCertEncodingType,
2558  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2559  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2560 {
2561     BOOL ret;
2562
2563     __TRY
2564     {
2565         struct AsnDecodeSequenceItem items[] = {
2566          { ASN_BITSTRING, offsetof(CERT_BASIC_CONSTRAINTS_INFO, SubjectType),
2567            CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), FALSE, TRUE, 
2568            offsetof(CERT_BASIC_CONSTRAINTS_INFO, SubjectType.pbData), 0 },
2569          { ASN_INTEGER, offsetof(CERT_BASIC_CONSTRAINTS_INFO,
2570            fPathLenConstraint), CRYPT_AsnDecodePathLenConstraint,
2571            sizeof(struct PATH_LEN_CONSTRAINT), TRUE, FALSE, 0, 0 },
2572          { ASN_SEQUENCEOF, offsetof(CERT_BASIC_CONSTRAINTS_INFO,
2573            cSubtreesConstraint), CRYPT_AsnDecodeSubtreeConstraints,
2574            sizeof(struct GenericArray), TRUE, TRUE,
2575            offsetof(CERT_BASIC_CONSTRAINTS_INFO, rgSubtreesConstraint), 0 },
2576         };
2577
2578         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
2579          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2580          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
2581     }
2582     __EXCEPT_PAGE_FAULT
2583     {
2584         SetLastError(STATUS_ACCESS_VIOLATION);
2585         ret = FALSE;
2586     }
2587     __ENDTRY
2588     return ret;
2589 }
2590
2591 static BOOL WINAPI CRYPT_AsnDecodeBasicConstraints2(DWORD dwCertEncodingType,
2592  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2593  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2594 {
2595     BOOL ret;
2596
2597     __TRY
2598     {
2599         struct AsnDecodeSequenceItem items[] = {
2600          { ASN_BOOL, offsetof(CERT_BASIC_CONSTRAINTS2_INFO, fCA),
2601            CRYPT_AsnDecodeBool, sizeof(BOOL), TRUE, FALSE, 0, 0 },
2602          { ASN_INTEGER, offsetof(CERT_BASIC_CONSTRAINTS2_INFO,
2603            fPathLenConstraint), CRYPT_AsnDecodePathLenConstraint,
2604            sizeof(struct PATH_LEN_CONSTRAINT), TRUE, FALSE, 0, 0 },
2605         };
2606
2607         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
2608          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2609          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
2610     }
2611     __EXCEPT_PAGE_FAULT
2612     {
2613         SetLastError(STATUS_ACCESS_VIOLATION);
2614         ret = FALSE;
2615     }
2616     __ENDTRY
2617     return ret;
2618 }
2619
2620 #define RSA1_MAGIC 0x31415352
2621
2622 struct DECODED_RSA_PUB_KEY
2623 {
2624     DWORD              pubexp;
2625     CRYPT_INTEGER_BLOB modulus;
2626 };
2627
2628 static BOOL WINAPI CRYPT_AsnDecodeRsaPubKey(DWORD dwCertEncodingType,
2629  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2630  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2631 {
2632     BOOL ret;
2633
2634     __TRY
2635     {
2636         struct AsnDecodeSequenceItem items[] = {
2637          { ASN_INTEGER, offsetof(struct DECODED_RSA_PUB_KEY, modulus),
2638            CRYPT_AsnDecodeUnsignedIntegerInternal, sizeof(CRYPT_INTEGER_BLOB),
2639            FALSE, TRUE, offsetof(struct DECODED_RSA_PUB_KEY, modulus.pbData),
2640            0 },
2641          { ASN_INTEGER, offsetof(struct DECODED_RSA_PUB_KEY, pubexp),
2642            CRYPT_AsnDecodeInt, sizeof(DWORD), FALSE, FALSE, 0, 0 },
2643         };
2644         struct DECODED_RSA_PUB_KEY *decodedKey = NULL;
2645         DWORD size = 0;
2646
2647         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
2648          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded,
2649          CRYPT_DECODE_ALLOC_FLAG, NULL, &decodedKey, &size, NULL);
2650         if (ret)
2651         {
2652             DWORD bytesNeeded = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) +
2653              decodedKey->modulus.cbData;
2654
2655             if (!pvStructInfo)
2656             {
2657                 *pcbStructInfo = bytesNeeded;
2658                 ret = TRUE;
2659             }
2660             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2661              pvStructInfo, pcbStructInfo, bytesNeeded)))
2662             {
2663                 BLOBHEADER *hdr;
2664                 RSAPUBKEY *rsaPubKey;
2665
2666                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2667                     pvStructInfo = *(BYTE **)pvStructInfo;
2668                 hdr = (BLOBHEADER *)pvStructInfo;
2669                 hdr->bType = PUBLICKEYBLOB;
2670                 hdr->bVersion = CUR_BLOB_VERSION;
2671                 hdr->reserved = 0;
2672                 hdr->aiKeyAlg = CALG_RSA_KEYX;
2673                 rsaPubKey = (RSAPUBKEY *)((BYTE *)pvStructInfo +
2674                  sizeof(BLOBHEADER));
2675                 rsaPubKey->magic = RSA1_MAGIC;
2676                 rsaPubKey->pubexp = decodedKey->pubexp;
2677                 rsaPubKey->bitlen = decodedKey->modulus.cbData * 8;
2678                 memcpy((BYTE *)pvStructInfo + sizeof(BLOBHEADER) +
2679                  sizeof(RSAPUBKEY), decodedKey->modulus.pbData,
2680                  decodedKey->modulus.cbData);
2681             }
2682             LocalFree(decodedKey);
2683         }
2684     }
2685     __EXCEPT_PAGE_FAULT
2686     {
2687         SetLastError(STATUS_ACCESS_VIOLATION);
2688         ret = FALSE;
2689     }
2690     __ENDTRY
2691     return ret;
2692 }
2693
2694 static BOOL WINAPI CRYPT_AsnDecodeOctetsInternal(DWORD dwCertEncodingType,
2695  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2696  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2697 {
2698     BOOL ret;
2699     DWORD bytesNeeded, dataLen;
2700
2701     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2702      pDecodePara, pvStructInfo, *pcbStructInfo);
2703
2704     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2705     {
2706         if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
2707             bytesNeeded = sizeof(CRYPT_DATA_BLOB);
2708         else
2709             bytesNeeded = dataLen + sizeof(CRYPT_DATA_BLOB);
2710         if (!pvStructInfo)
2711             *pcbStructInfo = bytesNeeded;
2712         else if (*pcbStructInfo < bytesNeeded)
2713         {
2714             SetLastError(ERROR_MORE_DATA);
2715             *pcbStructInfo = bytesNeeded;
2716             ret = FALSE;
2717         }
2718         else
2719         {
2720             CRYPT_DATA_BLOB *blob;
2721             BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2722
2723             blob = (CRYPT_DATA_BLOB *)pvStructInfo;
2724             blob->cbData = dataLen;
2725             if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
2726                 blob->pbData = (BYTE *)pbEncoded + 1 + lenBytes;
2727             else
2728             {
2729                 assert(blob->pbData);
2730                 if (blob->cbData)
2731                     memcpy(blob->pbData, pbEncoded + 1 + lenBytes,
2732                      blob->cbData);
2733             }
2734         }
2735     }
2736     return ret;
2737 }
2738
2739 static BOOL WINAPI CRYPT_AsnDecodeOctets(DWORD dwCertEncodingType,
2740  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2741  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2742 {
2743     BOOL ret;
2744
2745     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2746      pDecodePara, pvStructInfo, *pcbStructInfo);
2747
2748     __TRY
2749     {
2750         DWORD bytesNeeded;
2751
2752         if (!cbEncoded)
2753         {
2754             SetLastError(CRYPT_E_ASN1_CORRUPT);
2755             ret = FALSE;
2756         }
2757         else if (pbEncoded[0] != ASN_OCTETSTRING)
2758         {
2759             SetLastError(CRYPT_E_ASN1_BADTAG);
2760             ret = FALSE;
2761         }
2762         else if ((ret = CRYPT_AsnDecodeOctetsInternal(dwCertEncodingType,
2763          lpszStructType, pbEncoded, cbEncoded,
2764          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, &bytesNeeded)))
2765         {
2766             if (!pvStructInfo)
2767                 *pcbStructInfo = bytesNeeded;
2768             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2769              pvStructInfo, pcbStructInfo, bytesNeeded)))
2770             {
2771                 CRYPT_DATA_BLOB *blob;
2772
2773                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2774                     pvStructInfo = *(BYTE **)pvStructInfo;
2775                 blob = (CRYPT_DATA_BLOB *)pvStructInfo;
2776                 blob->pbData = (BYTE *)pvStructInfo + sizeof(CRYPT_DATA_BLOB);
2777                 ret = CRYPT_AsnDecodeOctetsInternal(dwCertEncodingType,
2778                  lpszStructType, pbEncoded, cbEncoded,
2779                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
2780                  &bytesNeeded);
2781             }
2782         }
2783     }
2784     __EXCEPT_PAGE_FAULT
2785     {
2786         SetLastError(STATUS_ACCESS_VIOLATION);
2787         ret = FALSE;
2788     }
2789     __ENDTRY
2790     return ret;
2791 }
2792
2793 static BOOL WINAPI CRYPT_AsnDecodeBitsInternal(DWORD dwCertEncodingType,
2794  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2795  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2796 {
2797     BOOL ret;
2798
2799     TRACE("(%p, %d, 0x%08x, %p, %p, %d)\n", pbEncoded, cbEncoded, dwFlags,
2800      pDecodePara, pvStructInfo, *pcbStructInfo);
2801
2802     if (pbEncoded[0] == ASN_BITSTRING)
2803     {
2804         DWORD bytesNeeded, dataLen;
2805
2806         if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2807         {
2808             if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
2809                 bytesNeeded = sizeof(CRYPT_BIT_BLOB);
2810             else
2811                 bytesNeeded = dataLen - 1 + sizeof(CRYPT_BIT_BLOB);
2812             if (!pvStructInfo)
2813                 *pcbStructInfo = bytesNeeded;
2814             else if (*pcbStructInfo < bytesNeeded)
2815             {
2816                 *pcbStructInfo = bytesNeeded;
2817                 SetLastError(ERROR_MORE_DATA);
2818                 ret = FALSE;
2819             }
2820             else
2821             {
2822                 CRYPT_BIT_BLOB *blob;
2823
2824                 blob = (CRYPT_BIT_BLOB *)pvStructInfo;
2825                 blob->cbData = dataLen - 1;
2826                 blob->cUnusedBits = *(pbEncoded + 1 +
2827                  GET_LEN_BYTES(pbEncoded[1]));
2828                 if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
2829                 {
2830                     blob->pbData = (BYTE *)pbEncoded + 2 +
2831                      GET_LEN_BYTES(pbEncoded[1]);
2832                 }
2833                 else
2834                 {
2835                     assert(blob->pbData);
2836                     if (blob->cbData)
2837                     {
2838                         BYTE mask = 0xff << blob->cUnusedBits;
2839
2840                         memcpy(blob->pbData, pbEncoded + 2 +
2841                          GET_LEN_BYTES(pbEncoded[1]), blob->cbData);
2842                         blob->pbData[blob->cbData - 1] &= mask;
2843                     }
2844                 }
2845             }
2846         }
2847     }
2848     else
2849     {
2850         SetLastError(CRYPT_E_ASN1_BADTAG);
2851         ret = FALSE;
2852     }
2853     TRACE("returning %d (%08x)\n", ret, GetLastError());
2854     return ret;
2855 }
2856
2857 static BOOL WINAPI CRYPT_AsnDecodeBits(DWORD dwCertEncodingType,
2858  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2859  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2860 {
2861     BOOL ret;
2862
2863     TRACE("(%p, %d, 0x%08x, %p, %p, %p)\n", pbEncoded, cbEncoded, dwFlags,
2864      pDecodePara, pvStructInfo, pcbStructInfo);
2865
2866     __TRY
2867     {
2868         DWORD bytesNeeded;
2869
2870         if ((ret = CRYPT_AsnDecodeBitsInternal(dwCertEncodingType,
2871          lpszStructType, pbEncoded, cbEncoded,
2872          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, &bytesNeeded)))
2873         {
2874             if (!pvStructInfo)
2875                 *pcbStructInfo = bytesNeeded;
2876             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2877              pvStructInfo, pcbStructInfo, bytesNeeded)))
2878             {
2879                 CRYPT_BIT_BLOB *blob;
2880
2881                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2882                     pvStructInfo = *(BYTE **)pvStructInfo;
2883                 blob = (CRYPT_BIT_BLOB *)pvStructInfo;
2884                 blob->pbData = (BYTE *)pvStructInfo + sizeof(CRYPT_BIT_BLOB);
2885                 ret = CRYPT_AsnDecodeBitsInternal(dwCertEncodingType,
2886                  lpszStructType, pbEncoded, cbEncoded,
2887                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
2888                  &bytesNeeded);
2889             }
2890         }
2891     }
2892     __EXCEPT_PAGE_FAULT
2893     {
2894         SetLastError(STATUS_ACCESS_VIOLATION);
2895         ret = FALSE;
2896     }
2897     __ENDTRY
2898     TRACE("returning %d (%08x)\n", ret, GetLastError());
2899     return ret;
2900 }
2901
2902 static BOOL WINAPI CRYPT_AsnDecodeInt(DWORD dwCertEncodingType,
2903  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2904  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2905 {
2906     BOOL ret;
2907
2908     if (!pvStructInfo)
2909     {
2910         *pcbStructInfo = sizeof(int);
2911         return TRUE;
2912     }
2913     __TRY
2914     {
2915         BYTE buf[sizeof(CRYPT_INTEGER_BLOB) + sizeof(int)];
2916         CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)buf;
2917         DWORD size = sizeof(buf);
2918
2919         blob->pbData = buf + sizeof(CRYPT_INTEGER_BLOB);
2920         if (pbEncoded[0] != ASN_INTEGER)
2921         {
2922             SetLastError(CRYPT_E_ASN1_BADTAG);
2923             ret = FALSE;
2924         }
2925         else
2926             ret = CRYPT_AsnDecodeIntegerInternal(dwCertEncodingType,
2927              X509_MULTI_BYTE_INTEGER, pbEncoded, cbEncoded, 0, NULL, &buf,
2928              &size);
2929         if (ret)
2930         {
2931             if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2932              pvStructInfo, pcbStructInfo, sizeof(int))))
2933             {
2934                 int val, i;
2935
2936                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2937                     pvStructInfo = *(BYTE **)pvStructInfo;
2938                 if (blob->pbData[blob->cbData - 1] & 0x80)
2939                 {
2940                     /* initialize to a negative value to sign-extend */
2941                     val = -1;
2942                 }
2943                 else
2944                     val = 0;
2945                 for (i = 0; i < blob->cbData; i++)
2946                 {
2947                     val <<= 8;
2948                     val |= blob->pbData[blob->cbData - i - 1];
2949                 }
2950                 memcpy(pvStructInfo, &val, sizeof(int));
2951             }
2952         }
2953         else if (GetLastError() == ERROR_MORE_DATA)
2954             SetLastError(CRYPT_E_ASN1_LARGE);
2955     }
2956     __EXCEPT_PAGE_FAULT
2957     {
2958         SetLastError(STATUS_ACCESS_VIOLATION);
2959         ret = FALSE;
2960     }
2961     __ENDTRY
2962     return ret;
2963 }
2964
2965 static BOOL WINAPI CRYPT_AsnDecodeIntegerInternal(DWORD dwCertEncodingType,
2966  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2967  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2968 {
2969     BOOL ret;
2970     DWORD bytesNeeded, dataLen;
2971
2972     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2973     {
2974         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2975
2976         bytesNeeded = dataLen + sizeof(CRYPT_INTEGER_BLOB);
2977         if (!pvStructInfo)
2978             *pcbStructInfo = bytesNeeded;
2979         else if (*pcbStructInfo < bytesNeeded)
2980         {
2981             *pcbStructInfo = bytesNeeded;
2982             SetLastError(ERROR_MORE_DATA);
2983             ret = FALSE;
2984         }
2985         else
2986         {
2987             CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
2988
2989             blob->cbData = dataLen;
2990             assert(blob->pbData);
2991             if (blob->cbData)
2992             {
2993                 DWORD i;
2994
2995                 for (i = 0; i < blob->cbData; i++)
2996                 {
2997                     blob->pbData[i] = *(pbEncoded + 1 + lenBytes +
2998                      dataLen - i - 1);
2999                 }
3000             }
3001         }
3002     }
3003     return ret;
3004 }
3005
3006 static BOOL WINAPI CRYPT_AsnDecodeInteger(DWORD dwCertEncodingType,
3007  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3008  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3009 {
3010     BOOL ret;
3011
3012     __TRY
3013     {
3014         DWORD bytesNeeded;
3015
3016         if (pbEncoded[0] != ASN_INTEGER)
3017         {
3018             SetLastError(CRYPT_E_ASN1_BADTAG);
3019             ret = FALSE;
3020         }
3021         else
3022             ret = CRYPT_AsnDecodeIntegerInternal(dwCertEncodingType,
3023              lpszStructType, pbEncoded, cbEncoded,
3024              dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, NULL, &bytesNeeded);
3025         if (ret)
3026         {
3027             if (!pvStructInfo)
3028                 *pcbStructInfo = bytesNeeded;
3029             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
3030              pvStructInfo, pcbStructInfo, bytesNeeded)))
3031             {
3032                 CRYPT_INTEGER_BLOB *blob;
3033
3034                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3035                     pvStructInfo = *(BYTE **)pvStructInfo;
3036                 blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
3037                 blob->pbData = (BYTE *)pvStructInfo +
3038                  sizeof(CRYPT_INTEGER_BLOB);
3039                 ret = CRYPT_AsnDecodeIntegerInternal(dwCertEncodingType,
3040                  lpszStructType, pbEncoded, cbEncoded,
3041                  dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, pvStructInfo,
3042                  &bytesNeeded);
3043             }
3044         }
3045     }
3046     __EXCEPT_PAGE_FAULT
3047     {
3048         SetLastError(STATUS_ACCESS_VIOLATION);
3049         ret = FALSE;
3050     }
3051     __ENDTRY
3052     return ret;
3053 }
3054
3055 static BOOL WINAPI CRYPT_AsnDecodeUnsignedIntegerInternal(
3056  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
3057  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
3058  void *pvStructInfo, DWORD *pcbStructInfo)
3059 {
3060     BOOL ret;
3061
3062     if (pbEncoded[0] == ASN_INTEGER)
3063     {
3064         DWORD bytesNeeded, dataLen;
3065
3066         if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
3067         {
3068             BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
3069
3070             bytesNeeded = dataLen + sizeof(CRYPT_INTEGER_BLOB);
3071             if (!pvStructInfo)
3072                 *pcbStructInfo = bytesNeeded;
3073             else if (*pcbStructInfo < bytesNeeded)
3074             {
3075                 *pcbStructInfo = bytesNeeded;
3076                 SetLastError(ERROR_MORE_DATA);
3077                 ret = FALSE;
3078             }
3079             else
3080             {
3081                 CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
3082
3083                 blob->cbData = dataLen;
3084                 assert(blob->pbData);
3085                 /* remove leading zero byte if it exists */
3086                 if (blob->cbData && *(pbEncoded + 1 + lenBytes) == 0)
3087                 {
3088                     blob->cbData--;
3089                     blob->pbData++;
3090                 }
3091                 if (blob->cbData)
3092                 {
3093                     DWORD i;
3094
3095                     for (i = 0; i < blob->cbData; i++)
3096                     {
3097                         blob->pbData[i] = *(pbEncoded + 1 + lenBytes +
3098                          dataLen - i - 1);
3099                     }
3100                 }
3101             }
3102         }
3103     }
3104     else
3105     {
3106         SetLastError(CRYPT_E_ASN1_BADTAG);
3107         ret = FALSE;
3108     }
3109     return ret;
3110 }
3111
3112 static BOOL WINAPI CRYPT_AsnDecodeUnsignedInteger(DWORD dwCertEncodingType,
3113  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3114  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3115 {
3116     BOOL ret;
3117
3118     __TRY
3119     {
3120         DWORD bytesNeeded;
3121
3122         if ((ret = CRYPT_AsnDecodeUnsignedIntegerInternal(dwCertEncodingType,
3123          lpszStructType, pbEncoded, cbEncoded,
3124          dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, NULL, &bytesNeeded)))
3125         {
3126             if (!pvStructInfo)
3127                 *pcbStructInfo = bytesNeeded;
3128             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
3129              pvStructInfo, pcbStructInfo, bytesNeeded)))
3130             {
3131                 CRYPT_INTEGER_BLOB *blob;
3132
3133                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3134                     pvStructInfo = *(BYTE **)pvStructInfo;
3135                 blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
3136                 blob->pbData = (BYTE *)pvStructInfo +
3137                  sizeof(CRYPT_INTEGER_BLOB);
3138                 ret = CRYPT_AsnDecodeUnsignedIntegerInternal(dwCertEncodingType,
3139                  lpszStructType, pbEncoded, cbEncoded,
3140                  dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, pvStructInfo,
3141                  &bytesNeeded);
3142             }
3143         }
3144     }
3145     __EXCEPT_PAGE_FAULT
3146     {
3147         SetLastError(STATUS_ACCESS_VIOLATION);
3148         ret = FALSE;
3149     }
3150     __ENDTRY
3151     return ret;
3152 }
3153
3154 static BOOL WINAPI CRYPT_AsnDecodeEnumerated(DWORD dwCertEncodingType,
3155  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3156  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3157 {
3158     BOOL ret;
3159
3160     if (!pvStructInfo)
3161     {
3162         *pcbStructInfo = sizeof(int);
3163         return TRUE;
3164     }
3165     __TRY
3166     {
3167         if (pbEncoded[0] == ASN_ENUMERATED)
3168         {
3169             unsigned int val = 0, i;
3170
3171             if (cbEncoded <= 1)
3172             {
3173                 SetLastError(CRYPT_E_ASN1_EOD);
3174                 ret = FALSE;
3175             }
3176             else if (pbEncoded[1] == 0)
3177             {
3178                 SetLastError(CRYPT_E_ASN1_CORRUPT);
3179                 ret = FALSE;
3180             }
3181             else
3182             {
3183                 /* A little strange looking, but we have to accept a sign byte:
3184                  * 0xffffffff gets encoded as 0a 05 00 ff ff ff ff.  Also,
3185                  * assuming a small length is okay here, it has to be in short
3186                  * form.
3187                  */
3188                 if (pbEncoded[1] > sizeof(unsigned int) + 1)
3189                 {
3190                     SetLastError(CRYPT_E_ASN1_LARGE);
3191                     return FALSE;
3192                 }
3193                 for (i = 0; i < pbEncoded[1]; i++)
3194                 {
3195                     val <<= 8;
3196                     val |= pbEncoded[2 + i];
3197                 }
3198                 if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
3199                  pvStructInfo, pcbStructInfo, sizeof(unsigned int))))
3200                 {
3201                     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3202                         pvStructInfo = *(BYTE **)pvStructInfo;
3203                     memcpy(pvStructInfo, &val, sizeof(unsigned int));
3204                 }
3205             }
3206         }
3207         else
3208         {
3209             SetLastError(CRYPT_E_ASN1_BADTAG);
3210             ret = FALSE;
3211         }
3212     }
3213     __EXCEPT_PAGE_FAULT
3214     {
3215         SetLastError(STATUS_ACCESS_VIOLATION);
3216         ret = FALSE;
3217     }
3218     __ENDTRY
3219     return ret;
3220 }
3221
3222 /* Modifies word, pbEncoded, and len, and magically sets a value ret to FALSE
3223  * if it fails.
3224  */
3225 #define CRYPT_TIME_GET_DIGITS(pbEncoded, len, numDigits, word) \
3226  do { \
3227     BYTE i; \
3228  \
3229     (word) = 0; \
3230     for (i = 0; (len) > 0 && i < (numDigits); i++, (len)--) \
3231     { \
3232         if (!isdigit(*(pbEncoded))) \
3233         { \
3234             SetLastError(CRYPT_E_ASN1_CORRUPT); \
3235             ret = FALSE; \
3236         } \
3237         else \
3238         { \
3239             (word) *= 10; \
3240             (word) += *(pbEncoded)++ - '0'; \
3241         } \
3242     } \
3243  } while (0)
3244
3245 static BOOL CRYPT_AsnDecodeTimeZone(const BYTE *pbEncoded, DWORD len,
3246  SYSTEMTIME *sysTime)
3247 {
3248     BOOL ret;
3249
3250     __TRY
3251     {
3252         ret = TRUE;
3253         if (len >= 3 && (*pbEncoded == '+' || *pbEncoded == '-'))
3254         {
3255             WORD hours, minutes = 0;
3256             BYTE sign = *pbEncoded++;
3257
3258             len--;
3259             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, hours);
3260             if (ret && hours >= 24)
3261             {
3262                 SetLastError(CRYPT_E_ASN1_CORRUPT);
3263                 ret = FALSE;
3264             }
3265             else if (len >= 2)
3266             {
3267                 CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, minutes);
3268                 if (ret && minutes >= 60)
3269                 {
3270                     SetLastError(CRYPT_E_ASN1_CORRUPT);
3271                     ret = FALSE;
3272                 }
3273             }
3274             if (ret)
3275             {
3276                 if (sign == '+')
3277                 {
3278                     sysTime->wHour += hours;
3279                     sysTime->wMinute += minutes;
3280                 }
3281                 else
3282                 {
3283                     if (hours > sysTime->wHour)
3284                     {
3285                         sysTime->wDay--;
3286                         sysTime->wHour = 24 - (hours - sysTime->wHour);
3287                     }
3288                     else
3289                         sysTime->wHour -= hours;
3290                     if (minutes > sysTime->wMinute)
3291                     {
3292                         sysTime->wHour--;
3293                         sysTime->wMinute = 60 - (minutes - sysTime->wMinute);
3294                     }
3295                     else
3296                         sysTime->wMinute -= minutes;
3297                 }
3298             }
3299         }
3300     }
3301     __EXCEPT_PAGE_FAULT
3302     {
3303         SetLastError(STATUS_ACCESS_VIOLATION);
3304         ret = FALSE;
3305     }
3306     __ENDTRY
3307     return ret;
3308 }
3309
3310 #define MIN_ENCODED_TIME_LENGTH 10
3311
3312 static BOOL WINAPI CRYPT_AsnDecodeUtcTime(DWORD dwCertEncodingType,
3313  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3314  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3315 {
3316     BOOL ret;
3317
3318     if (!pvStructInfo)
3319     {
3320         *pcbStructInfo = sizeof(FILETIME);
3321         return TRUE;
3322     }
3323     __TRY
3324     {
3325         ret = TRUE;
3326         if (pbEncoded[0] == ASN_UTCTIME)
3327         {
3328             if (cbEncoded <= 1)
3329             {
3330                 SetLastError(CRYPT_E_ASN1_EOD);
3331                 ret = FALSE;
3332             }
3333             else if (pbEncoded[1] > 0x7f)
3334             {
3335                 /* long-form date strings really can't be valid */
3336                 SetLastError(CRYPT_E_ASN1_CORRUPT);
3337                 ret = FALSE;
3338             }
3339             else
3340             {
3341                 SYSTEMTIME sysTime = { 0 };
3342                 BYTE len = pbEncoded[1];
3343
3344                 if (len < MIN_ENCODED_TIME_LENGTH)
3345                 {
3346                     SetLastError(CRYPT_E_ASN1_CORRUPT);
3347                     ret = FALSE;
3348                 }
3349                 else
3350                 {
3351                     pbEncoded += 2;
3352                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wYear);
3353                     if (sysTime.wYear >= 50)
3354                         sysTime.wYear += 1900;
3355                     else
3356                         sysTime.wYear += 2000;
3357                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMonth);
3358                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wDay);
3359                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wHour);
3360                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMinute);
3361                     if (ret && len > 0)
3362                     {
3363                         if (len >= 2 && isdigit(*pbEncoded) &&
3364                          isdigit(*(pbEncoded + 1)))
3365                             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2,
3366                              sysTime.wSecond);
3367                         else if (isdigit(*pbEncoded))
3368                             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 1,
3369                              sysTime.wSecond);
3370                         if (ret)
3371                             ret = CRYPT_AsnDecodeTimeZone(pbEncoded, len,
3372                              &sysTime);
3373                     }
3374                     if (ret && (ret = CRYPT_DecodeEnsureSpace(dwFlags,
3375                      pDecodePara, pvStructInfo, pcbStructInfo,
3376                      sizeof(FILETIME))))
3377                     {
3378                         if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3379                             pvStructInfo = *(BYTE **)pvStructInfo;
3380                         ret = SystemTimeToFileTime(&sysTime,
3381                          (FILETIME *)pvStructInfo);
3382                     }
3383                 }
3384             }
3385         }
3386         else
3387         {
3388             SetLastError(CRYPT_E_ASN1_BADTAG);
3389             ret = FALSE;
3390         }
3391     }
3392     __EXCEPT_PAGE_FAULT
3393     {
3394         SetLastError(STATUS_ACCESS_VIOLATION);
3395         ret = FALSE;
3396     }
3397     __ENDTRY
3398     return ret;
3399 }
3400
3401 static BOOL WINAPI CRYPT_AsnDecodeGeneralizedTime(DWORD dwCertEncodingType,
3402  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3403  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3404 {
3405     BOOL ret;
3406
3407     if (!pvStructInfo)
3408     {
3409         *pcbStructInfo = sizeof(FILETIME);
3410         return TRUE;
3411     }
3412     __TRY
3413     {
3414         ret = TRUE;
3415         if (pbEncoded[0] == ASN_GENERALTIME)
3416         {
3417             if (cbEncoded <= 1)
3418             {
3419                 SetLastError(CRYPT_E_ASN1_EOD);
3420                 ret = FALSE;
3421             }
3422             else if (pbEncoded[1] > 0x7f)
3423             {
3424                 /* long-form date strings really can't be valid */
3425                 SetLastError(CRYPT_E_ASN1_CORRUPT);
3426                 ret = FALSE;
3427             }
3428             else
3429             {
3430                 BYTE len = pbEncoded[1];
3431
3432                 if (len < MIN_ENCODED_TIME_LENGTH)
3433                 {
3434                     SetLastError(CRYPT_E_ASN1_CORRUPT);
3435                     ret = FALSE;
3436                 }
3437                 else
3438                 {
3439                     SYSTEMTIME sysTime = { 0 };
3440
3441                     pbEncoded += 2;
3442                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 4, sysTime.wYear);
3443                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMonth);
3444                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wDay);
3445                     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wHour);
3446                     if (ret && len > 0)
3447                     {
3448                         CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2,
3449                          sysTime.wMinute);
3450                         if (ret && len > 0)
3451                             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2,
3452                              sysTime.wSecond);
3453                         if (ret && len > 0 && (*pbEncoded == '.' ||
3454                          *pbEncoded == ','))
3455                         {
3456                             BYTE digits;
3457
3458                             pbEncoded++;
3459                             len--;
3460                             /* workaround macro weirdness */
3461                             digits = min(len, 3);
3462                             CRYPT_TIME_GET_DIGITS(pbEncoded, len, digits,
3463                              sysTime.wMilliseconds);
3464                         }
3465                         if (ret)
3466                             ret = CRYPT_AsnDecodeTimeZone(pbEncoded, len,
3467                              &sysTime);
3468                     }
3469                     if (ret && (ret = CRYPT_DecodeEnsureSpace(dwFlags,
3470                      pDecodePara, pvStructInfo, pcbStructInfo,
3471                      sizeof(FILETIME))))
3472                     {
3473                         if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3474                             pvStructInfo = *(BYTE **)pvStructInfo;
3475                         ret = SystemTimeToFileTime(&sysTime,
3476                          (FILETIME *)pvStructInfo);
3477                     }
3478                 }
3479             }
3480         }
3481         else
3482         {
3483             SetLastError(CRYPT_E_ASN1_BADTAG);
3484             ret = FALSE;
3485         }
3486     }
3487     __EXCEPT_PAGE_FAULT
3488     {
3489         SetLastError(STATUS_ACCESS_VIOLATION);
3490         ret = FALSE;
3491     }
3492     __ENDTRY
3493     return ret;
3494 }
3495
3496 static BOOL WINAPI CRYPT_AsnDecodeChoiceOfTime(DWORD dwCertEncodingType,
3497  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3498  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3499 {
3500     BOOL ret;
3501
3502     __TRY
3503     {
3504         if (pbEncoded[0] == ASN_UTCTIME)
3505             ret = CRYPT_AsnDecodeUtcTime(dwCertEncodingType, lpszStructType,
3506              pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
3507              pcbStructInfo);
3508         else if (pbEncoded[0] == ASN_GENERALTIME)
3509             ret = CRYPT_AsnDecodeGeneralizedTime(dwCertEncodingType,
3510              lpszStructType, pbEncoded, cbEncoded, dwFlags, pDecodePara,
3511              pvStructInfo, pcbStructInfo);
3512         else
3513         {
3514             SetLastError(CRYPT_E_ASN1_BADTAG);
3515             ret = FALSE;
3516         }
3517     }
3518     __EXCEPT_PAGE_FAULT
3519     {
3520         SetLastError(STATUS_ACCESS_VIOLATION);
3521         ret = FALSE;
3522     }
3523     __ENDTRY
3524     return ret;
3525 }
3526
3527 static BOOL WINAPI CRYPT_AsnDecodeSequenceOfAny(DWORD dwCertEncodingType,
3528  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3529  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3530 {
3531     BOOL ret = TRUE;
3532
3533     __TRY
3534     {
3535         if (pbEncoded[0] == ASN_SEQUENCEOF)
3536         {
3537             DWORD bytesNeeded, dataLen, remainingLen, cValue;
3538
3539             if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
3540             {
3541                 BYTE lenBytes;
3542                 const BYTE *ptr;
3543
3544                 lenBytes = GET_LEN_BYTES(pbEncoded[1]);
3545                 bytesNeeded = sizeof(CRYPT_SEQUENCE_OF_ANY);
3546                 cValue = 0;
3547                 ptr = pbEncoded + 1 + lenBytes;
3548                 remainingLen = dataLen;
3549                 while (ret && remainingLen)
3550                 {
3551                     DWORD nextLen;
3552
3553                     ret = CRYPT_GetLen(ptr, remainingLen, &nextLen);
3554                     if (ret)
3555                     {
3556                         DWORD nextLenBytes = GET_LEN_BYTES(ptr[1]);
3557
3558                         remainingLen -= 1 + nextLenBytes + nextLen;
3559                         ptr += 1 + nextLenBytes + nextLen;
3560                         bytesNeeded += sizeof(CRYPT_DER_BLOB);
3561                         if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
3562                             bytesNeeded += 1 + nextLenBytes + nextLen;
3563                         cValue++;
3564                     }
3565                 }
3566                 if (ret)
3567                 {
3568                     CRYPT_SEQUENCE_OF_ANY *seq;
3569                     BYTE *nextPtr;
3570                     DWORD i;
3571
3572                     if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
3573                      pvStructInfo, pcbStructInfo, bytesNeeded)))
3574                     {
3575                         if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3576                             pvStructInfo = *(BYTE **)pvStructInfo;
3577                         seq = (CRYPT_SEQUENCE_OF_ANY *)pvStructInfo;
3578                         seq->cValue = cValue;
3579                         seq->rgValue = (CRYPT_DER_BLOB *)((BYTE *)seq +
3580                          sizeof(*seq));
3581                         nextPtr = (BYTE *)seq->rgValue +
3582                          cValue * sizeof(CRYPT_DER_BLOB);
3583                         ptr = pbEncoded + 1 + lenBytes;
3584                         remainingLen = dataLen;
3585                         i = 0;
3586                         while (ret && remainingLen)
3587                         {
3588                             DWORD nextLen;
3589
3590                             ret = CRYPT_GetLen(ptr, remainingLen, &nextLen);
3591                             if (ret)
3592                             {
3593                                 DWORD nextLenBytes = GET_LEN_BYTES(ptr[1]);
3594
3595                                 seq->rgValue[i].cbData = 1 + nextLenBytes +
3596                                  nextLen;
3597                                 if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
3598                                     seq->rgValue[i].pbData = (BYTE *)ptr;
3599                                 else
3600                                 {
3601                                     seq->rgValue[i].pbData = nextPtr;
3602                                     memcpy(nextPtr, ptr, 1 + nextLenBytes +
3603                                      nextLen);
3604                                     nextPtr += 1 + nextLenBytes + nextLen;
3605                                 }
3606                                 remainingLen -= 1 + nextLenBytes + nextLen;
3607                                 ptr += 1 + nextLenBytes + nextLen;
3608                                 i++;
3609                             }
3610                         }
3611                     }
3612                 }
3613             }
3614         }
3615         else
3616         {
3617             SetLastError(CRYPT_E_ASN1_BADTAG);
3618             ret = FALSE;
3619         }
3620     }
3621     __EXCEPT_PAGE_FAULT
3622     {
3623         SetLastError(STATUS_ACCESS_VIOLATION);
3624         ret = FALSE;
3625     }
3626     __ENDTRY
3627     return ret;
3628 }
3629
3630 static BOOL WINAPI CRYPT_AsnDecodeDistPointName(DWORD dwCertEncodingType,
3631  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3632  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3633 {
3634     BOOL ret;
3635
3636     if (pbEncoded[0] == (ASN_CONTEXT | ASN_CONSTRUCTOR | 0))
3637     {
3638         DWORD bytesNeeded, dataLen;
3639
3640         if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
3641         {
3642             struct AsnArrayDescriptor arrayDesc = {
3643              ASN_CONTEXT | ASN_CONSTRUCTOR | 0, CRYPT_AsnDecodeAltNameEntry,
3644              sizeof(CERT_ALT_NAME_ENTRY), TRUE,
3645              offsetof(CERT_ALT_NAME_ENTRY, u.pwszURL) };
3646             BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
3647
3648             if (dataLen)
3649             {
3650                 DWORD nameLen;
3651
3652                 ret = CRYPT_AsnDecodeArray(&arrayDesc,
3653                  pbEncoded + 1 + lenBytes, cbEncoded - 1 - lenBytes,
3654                  0, NULL, NULL, &nameLen, NULL);
3655                 bytesNeeded = sizeof(CRL_DIST_POINT_NAME) + nameLen;
3656             }
3657             else
3658                 bytesNeeded = sizeof(CRL_DIST_POINT_NAME);
3659             if (!pvStructInfo)
3660                 *pcbStructInfo = bytesNeeded;
3661             else if (*pcbStructInfo < bytesNeeded)
3662             {
3663                 *pcbStructInfo = bytesNeeded;
3664                 SetLastError(ERROR_MORE_DATA);
3665                 ret = FALSE;
3666             }
3667             else
3668             {
3669                 CRL_DIST_POINT_NAME *name = (CRL_DIST_POINT_NAME *)pvStructInfo;
3670
3671                 if (dataLen)
3672                 {
3673                     name->dwDistPointNameChoice = CRL_DIST_POINT_FULL_NAME;
3674                     ret = CRYPT_AsnDecodeArray(&arrayDesc,
3675                      pbEncoded + 1 + lenBytes, cbEncoded - 1 - lenBytes,
3676                      0, NULL, &name->u.FullName, pcbStructInfo,
3677                      name->u.FullName.rgAltEntry);
3678                 }
3679                 else
3680                     name->dwDistPointNameChoice = CRL_DIST_POINT_NO_NAME;
3681             }
3682         }
3683     }
3684     else
3685     {
3686         SetLastError(CRYPT_E_ASN1_BADTAG);
3687         ret = FALSE;
3688     }
3689     return ret;
3690 }
3691
3692 static BOOL WINAPI CRYPT_AsnDecodeDistPoint(DWORD dwCertEncodingType,
3693  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3694  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3695 {
3696     struct AsnDecodeSequenceItem items[] = {
3697      { ASN_CONTEXT | ASN_CONSTRUCTOR | 0, offsetof(CRL_DIST_POINT,
3698        DistPointName), CRYPT_AsnDecodeDistPointName,
3699        sizeof(CRL_DIST_POINT_NAME), TRUE, TRUE, offsetof(CRL_DIST_POINT,
3700        DistPointName.u.FullName.rgAltEntry), 0 },
3701      { ASN_CONTEXT | 1, offsetof(CRL_DIST_POINT, ReasonFlags),
3702        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), TRUE, TRUE,
3703        offsetof(CRL_DIST_POINT, ReasonFlags.pbData), 0 },
3704      { ASN_CONTEXT | ASN_CONSTRUCTOR | 2, offsetof(CRL_DIST_POINT, CRLIssuer),
3705        CRYPT_AsnDecodeAltNameInternal, sizeof(CERT_ALT_NAME_INFO), TRUE, TRUE,
3706        offsetof(CRL_DIST_POINT, CRLIssuer.rgAltEntry), 0 },
3707     };
3708     BOOL ret;
3709
3710     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
3711      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded,
3712      dwFlags, pDecodePara, pvStructInfo, pcbStructInfo, NULL);
3713     return ret;
3714 }
3715
3716 static BOOL WINAPI CRYPT_AsnDecodeCRLDistPoints(DWORD dwCertEncodingType,
3717  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3718  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3719 {
3720     BOOL ret;
3721
3722     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3723      pDecodePara, pvStructInfo, *pcbStructInfo);
3724
3725     __TRY
3726     {
3727         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
3728          CRYPT_AsnDecodeDistPoint, sizeof(CRL_DIST_POINT), TRUE,
3729          offsetof(CRL_DIST_POINT, DistPointName.u.FullName.rgAltEntry) };
3730
3731         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
3732          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
3733     }
3734     __EXCEPT_PAGE_FAULT
3735     {
3736         SetLastError(STATUS_ACCESS_VIOLATION);
3737         ret = FALSE;
3738     }
3739     __ENDTRY
3740     return ret;
3741 }
3742
3743 static BOOL WINAPI CRYPT_AsnDecodeEnhancedKeyUsage(DWORD dwCertEncodingType,
3744  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3745  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3746 {
3747     BOOL ret;
3748
3749     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3750      pDecodePara, pvStructInfo, *pcbStructInfo);
3751
3752     __TRY
3753     {
3754         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
3755          CRYPT_AsnDecodeOidInternal, sizeof(LPSTR), TRUE, 0 };
3756
3757         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
3758          pDecodePara, pvStructInfo, pcbStructInfo, NULL);
3759     }
3760     __EXCEPT_PAGE_FAULT
3761     {
3762         SetLastError(STATUS_ACCESS_VIOLATION);
3763         ret = FALSE;
3764     }
3765     __ENDTRY
3766     return ret;
3767 }
3768
3769 static BOOL WINAPI CRYPT_AsnDecodeIssuingDistPoint(DWORD dwCertEncodingType,
3770  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3771  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3772 {
3773     BOOL ret;
3774
3775     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3776      pDecodePara, pvStructInfo, *pcbStructInfo);
3777
3778     __TRY
3779     {
3780         struct AsnDecodeSequenceItem items[] = {
3781          { ASN_CONTEXT | ASN_CONSTRUCTOR | 0, offsetof(CRL_ISSUING_DIST_POINT,
3782            DistPointName), CRYPT_AsnDecodeDistPointName,
3783            sizeof(CRL_DIST_POINT_NAME), TRUE, TRUE,
3784            offsetof(CRL_ISSUING_DIST_POINT,
3785            DistPointName.u.FullName.rgAltEntry), 0 },
3786          { ASN_CONTEXT | 1, offsetof(CRL_ISSUING_DIST_POINT,
3787            fOnlyContainsUserCerts), CRYPT_AsnDecodeBool, sizeof(BOOL), TRUE,
3788            FALSE, 0 },
3789          { ASN_CONTEXT | 2, offsetof(CRL_ISSUING_DIST_POINT,
3790            fOnlyContainsCACerts), CRYPT_AsnDecodeBool, sizeof(BOOL), TRUE,
3791            FALSE, 0 },
3792          { ASN_CONTEXT | 3, offsetof(CRL_ISSUING_DIST_POINT,
3793            OnlySomeReasonFlags), CRYPT_AsnDecodeBitsInternal,
3794            sizeof(CRYPT_BIT_BLOB), TRUE, TRUE, offsetof(CRL_ISSUING_DIST_POINT,
3795            OnlySomeReasonFlags.pbData), 0 },
3796          { ASN_CONTEXT | 4, offsetof(CRL_ISSUING_DIST_POINT,
3797            fIndirectCRL), CRYPT_AsnDecodeBool, sizeof(BOOL), TRUE, FALSE, 0 },
3798         };
3799
3800         ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
3801          sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded,
3802          dwFlags, pDecodePara, pvStructInfo, pcbStructInfo, NULL);
3803     }
3804     __EXCEPT_PAGE_FAULT
3805     {
3806         SetLastError(STATUS_ACCESS_VIOLATION);
3807         ret = FALSE;
3808     }
3809     __ENDTRY
3810     return ret;
3811 }
3812
3813 static BOOL WINAPI CRYPT_AsnDecodeIssuerSerialNumber(DWORD dwCertEncodingType,
3814  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3815  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3816 {
3817     BOOL ret;
3818     struct AsnDecodeSequenceItem items[] = {
3819      { 0, offsetof(CERT_ISSUER_SERIAL_NUMBER, Issuer), CRYPT_AsnDecodeDerBlob,
3820        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CERT_ISSUER_SERIAL_NUMBER,
3821        Issuer.pbData) },
3822      { ASN_INTEGER, offsetof(CERT_ISSUER_SERIAL_NUMBER, SerialNumber),
3823        CRYPT_AsnDecodeIntegerInternal, sizeof(CRYPT_INTEGER_BLOB), FALSE,
3824        TRUE, offsetof(CERT_ISSUER_SERIAL_NUMBER, SerialNumber.pbData), 0 },
3825     };
3826     CERT_ISSUER_SERIAL_NUMBER *issuerSerial =
3827      (CERT_ISSUER_SERIAL_NUMBER *)pvStructInfo;
3828
3829     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3830      pDecodePara, pvStructInfo, *pcbStructInfo);
3831
3832     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
3833      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded,
3834      dwFlags, pDecodePara, pvStructInfo, pcbStructInfo,
3835      issuerSerial ? issuerSerial->Issuer.pbData : NULL);
3836     if (ret && issuerSerial && !issuerSerial->SerialNumber.cbData)
3837     {
3838         SetLastError(CRYPT_E_ASN1_CORRUPT);
3839         ret = FALSE;
3840     }
3841     TRACE("returning %d\n", ret);
3842     return ret;
3843 }
3844
3845 static BOOL WINAPI CRYPT_AsnDecodePKCSSignerInfoInternal(
3846  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
3847  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
3848  void *pvStructInfo, DWORD *pcbStructInfo)
3849 {
3850     CMSG_SIGNER_INFO *info = (CMSG_SIGNER_INFO *)pvStructInfo;
3851     struct AsnDecodeSequenceItem items[] = {
3852      { ASN_INTEGER, offsetof(CMSG_SIGNER_INFO, dwVersion),
3853        CRYPT_AsnDecodeInt, sizeof(DWORD), FALSE, FALSE, 0, 0 },
3854      { ASN_SEQUENCEOF, offsetof(CMSG_SIGNER_INFO, Issuer),
3855        CRYPT_AsnDecodeIssuerSerialNumber, sizeof(CERT_ISSUER_SERIAL_NUMBER),
3856        FALSE, TRUE, offsetof(CMSG_SIGNER_INFO, Issuer.pbData), 0 },
3857      { ASN_SEQUENCEOF, offsetof(CMSG_SIGNER_INFO, HashAlgorithm),
3858        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
3859        FALSE, TRUE, offsetof(CMSG_SIGNER_INFO, HashAlgorithm.pszObjId), 0 },
3860      { ASN_CONSTRUCTOR | ASN_CONTEXT | 0,
3861        offsetof(CMSG_SIGNER_INFO, AuthAttrs),
3862        CRYPT_AsnDecodePKCSAttributesInternal, sizeof(CRYPT_ATTRIBUTES),
3863        TRUE, TRUE, offsetof(CMSG_SIGNER_INFO, AuthAttrs.rgAttr), 0 },
3864      { ASN_SEQUENCEOF, offsetof(CMSG_SIGNER_INFO, HashEncryptionAlgorithm),
3865        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
3866        FALSE, TRUE, offsetof(CMSG_SIGNER_INFO,
3867        HashEncryptionAlgorithm.pszObjId), 0 },
3868      { ASN_OCTETSTRING, offsetof(CMSG_SIGNER_INFO, EncryptedHash),
3869        CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_DER_BLOB),
3870        FALSE, TRUE, offsetof(CMSG_SIGNER_INFO, EncryptedHash.pbData), 0 },
3871      { ASN_CONSTRUCTOR | ASN_CONTEXT | 1,
3872        offsetof(CMSG_SIGNER_INFO, UnauthAttrs),
3873        CRYPT_AsnDecodePKCSAttributesInternal, sizeof(CRYPT_ATTRIBUTES),
3874        TRUE, TRUE, offsetof(CMSG_SIGNER_INFO, UnauthAttrs.rgAttr), 0 },
3875     };
3876     BOOL ret;
3877
3878     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3879      pDecodePara, pvStructInfo, *pcbStructInfo);
3880
3881     ret = CRYPT_AsnDecodeSequence(dwCertEncodingType, items,
3882      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded,
3883      dwFlags, pDecodePara, pvStructInfo, pcbStructInfo,
3884      info ? info->Issuer.pbData : NULL);
3885     return ret;
3886 }
3887
3888 static BOOL WINAPI CRYPT_AsnDecodePKCSSignerInfo(DWORD dwCertEncodingType,
3889  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3890  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3891 {
3892     BOOL ret = FALSE;
3893
3894     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3895      pDecodePara, pvStructInfo, *pcbStructInfo);
3896
3897     __TRY
3898     {
3899         ret = CRYPT_AsnDecodePKCSSignerInfoInternal(dwCertEncodingType,
3900          lpszStructType, pbEncoded, cbEncoded,
3901          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, NULL, pcbStructInfo);
3902         if (ret && pvStructInfo)
3903         {
3904             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
3905              pcbStructInfo, *pcbStructInfo);
3906             if (ret)
3907             {
3908                 CMSG_SIGNER_INFO *info;
3909
3910                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3911                     pvStructInfo = *(BYTE **)pvStructInfo;
3912                 info = (CMSG_SIGNER_INFO *)pvStructInfo;
3913                 info->Issuer.pbData = ((BYTE *)info +
3914                  sizeof(CMSG_SIGNER_INFO));
3915                 ret = CRYPT_AsnDecodePKCSSignerInfoInternal(dwCertEncodingType,
3916                  lpszStructType, pbEncoded, cbEncoded,
3917                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pvStructInfo,
3918                  pcbStructInfo);
3919             }
3920         }
3921     }
3922     __EXCEPT_PAGE_FAULT
3923     {
3924         SetLastError(STATUS_ACCESS_VIOLATION);
3925     }
3926     __ENDTRY
3927     TRACE("returning %d\n", ret);
3928     return ret;
3929 }
3930
3931 static BOOL WINAPI CRYPT_DecodeSignerArray(DWORD dwCertEncodingType,
3932  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3933  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3934 {
3935     BOOL ret;
3936     struct AsnArrayDescriptor arrayDesc = { ASN_CONSTRUCTOR | ASN_SETOF,
3937      CRYPT_AsnDecodePKCSSignerInfoInternal, sizeof(CMSG_SIGNER_INFO), TRUE,
3938      offsetof(CMSG_SIGNER_INFO, Issuer.pbData) };
3939     struct GenericArray *array = (struct GenericArray *)pvStructInfo;
3940
3941     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3942      pDecodePara, pvStructInfo, *pcbStructInfo);
3943
3944     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
3945      pDecodePara, pvStructInfo, pcbStructInfo, array ? array->rgItems : NULL);
3946     return ret;
3947 }
3948
3949 BOOL CRYPT_AsnDecodePKCSSignedInfo(const BYTE *pbEncoded, DWORD cbEncoded,
3950  DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
3951  CRYPT_SIGNED_INFO *signedInfo, DWORD *pcbSignedInfo)
3952 {
3953     BOOL ret = FALSE;
3954     struct AsnDecodeSequenceItem items[] = {
3955      { ASN_INTEGER, offsetof(CRYPT_SIGNED_INFO, version), CRYPT_AsnDecodeInt,
3956        sizeof(DWORD), FALSE, FALSE, 0, 0 },
3957      /* Placeholder for the hash algorithms - redundant with those in the
3958       * signers, so just ignore them.
3959       */
3960      { ASN_CONSTRUCTOR | ASN_SETOF, 0, NULL, 0, TRUE, FALSE, 0, 0 },
3961      { ASN_SEQUENCE, offsetof(CRYPT_SIGNED_INFO, content),
3962        CRYPT_AsnDecodePKCSContentInfoInternal, sizeof(CRYPT_CONTENT_INFO),
3963        FALSE, TRUE, offsetof(CRYPT_SIGNED_INFO, content.pszObjId), 0 },
3964      { ASN_CONSTRUCTOR | ASN_CONTEXT | 0,
3965        offsetof(CRYPT_SIGNED_INFO, cCertEncoded),
3966        CRYPT_DecodeDERArray, sizeof(struct GenericArray), TRUE, TRUE,
3967        offsetof(CRYPT_SIGNED_INFO, rgCertEncoded), 0 },
3968      { ASN_CONSTRUCTOR | ASN_CONTEXT | 1,
3969        offsetof(CRYPT_SIGNED_INFO, cCrlEncoded), CRYPT_DecodeDERArray,
3970        sizeof(struct GenericArray), TRUE, TRUE,
3971        offsetof(CRYPT_SIGNED_INFO, rgCrlEncoded), 0 },
3972      { ASN_CONSTRUCTOR | ASN_SETOF, offsetof(CRYPT_SIGNED_INFO, cSignerInfo),
3973        CRYPT_DecodeSignerArray, sizeof(struct GenericArray), TRUE, TRUE,
3974        offsetof(CRYPT_SIGNED_INFO, rgSignerInfo), 0 },
3975     };
3976
3977     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3978      pDecodePara, signedInfo, *pcbSignedInfo);
3979
3980     ret = CRYPT_AsnDecodeSequence(X509_ASN_ENCODING, items,
3981      sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
3982      pDecodePara, signedInfo, pcbSignedInfo, NULL);
3983     TRACE("returning %d\n", ret);
3984     return ret;
3985 }
3986
3987 static CryptDecodeObjectExFunc CRYPT_GetBuiltinDecoder(DWORD dwCertEncodingType,
3988  LPCSTR lpszStructType)
3989 {
3990     CryptDecodeObjectExFunc decodeFunc = NULL;
3991
3992     if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING
3993      && (dwCertEncodingType & CMSG_ENCODING_TYPE_MASK) != PKCS_7_ASN_ENCODING)
3994     {
3995         SetLastError(ERROR_FILE_NOT_FOUND);
3996         return NULL;
3997     }
3998     if (!HIWORD(lpszStructType))
3999     {
4000         switch (LOWORD(lpszStructType))
4001         {
4002         case (WORD)X509_CERT:
4003             decodeFunc = CRYPT_AsnDecodeCertSignedContent;
4004             break;
4005         case (WORD)X509_CERT_TO_BE_SIGNED:
4006             decodeFunc = CRYPT_AsnDecodeCert;
4007             break;
4008         case (WORD)X509_CERT_CRL_TO_BE_SIGNED:
4009             decodeFunc = CRYPT_AsnDecodeCRL;
4010             break;
4011         case (WORD)X509_EXTENSIONS:
4012             decodeFunc = CRYPT_AsnDecodeExtensions;
4013             break;
4014         case (WORD)X509_NAME_VALUE:
4015             decodeFunc = CRYPT_AsnDecodeNameValue;
4016             break;
4017         case (WORD)X509_NAME:
4018             decodeFunc = CRYPT_AsnDecodeName;
4019             break;
4020         case (WORD)X509_PUBLIC_KEY_INFO:
4021             decodeFunc = CRYPT_AsnDecodePubKeyInfo;
4022             break;
4023         case (WORD)X509_AUTHORITY_KEY_ID:
4024             decodeFunc = CRYPT_AsnDecodeAuthorityKeyId;
4025             break;
4026         case (WORD)X509_ALTERNATE_NAME:
4027             decodeFunc = CRYPT_AsnDecodeAltName;
4028             break;
4029         case (WORD)X509_BASIC_CONSTRAINTS:
4030             decodeFunc = CRYPT_AsnDecodeBasicConstraints;
4031             break;
4032         case (WORD)X509_BASIC_CONSTRAINTS2:
4033             decodeFunc = CRYPT_AsnDecodeBasicConstraints2;
4034             break;
4035         case (WORD)RSA_CSP_PUBLICKEYBLOB:
4036             decodeFunc = CRYPT_AsnDecodeRsaPubKey;
4037             break;
4038         case (WORD)X509_UNICODE_NAME:
4039             decodeFunc = CRYPT_AsnDecodeUnicodeName;
4040             break;
4041         case (WORD)PKCS_ATTRIBUTE:
4042             decodeFunc = CRYPT_AsnDecodePKCSAttribute;
4043             break;
4044         case (WORD)X509_UNICODE_NAME_VALUE:
4045             decodeFunc = CRYPT_AsnDecodeUnicodeNameValue;
4046             break;
4047         case (WORD)X509_OCTET_STRING:
4048             decodeFunc = CRYPT_AsnDecodeOctets;
4049             break;
4050         case (WORD)X509_BITS:
4051         case (WORD)X509_KEY_USAGE:
4052             decodeFunc = CRYPT_AsnDecodeBits;
4053             break;
4054         case (WORD)X509_INTEGER:
4055             decodeFunc = CRYPT_AsnDecodeInt;
4056             break;
4057         case (WORD)X509_MULTI_BYTE_INTEGER:
4058             decodeFunc = CRYPT_AsnDecodeInteger;
4059             break;
4060         case (WORD)X509_MULTI_BYTE_UINT:
4061             decodeFunc = CRYPT_AsnDecodeUnsignedInteger;
4062             break;
4063         case (WORD)X509_ENUMERATED:
4064             decodeFunc = CRYPT_AsnDecodeEnumerated;
4065             break;
4066         case (WORD)X509_CHOICE_OF_TIME:
4067             decodeFunc = CRYPT_AsnDecodeChoiceOfTime;
4068             break;
4069         case (WORD)X509_AUTHORITY_KEY_ID2:
4070             decodeFunc = CRYPT_AsnDecodeAuthorityKeyId2;
4071             break;
4072         case (WORD)PKCS_CONTENT_INFO:
4073             decodeFunc = CRYPT_AsnDecodePKCSContentInfo;
4074             break;
4075         case (WORD)X509_SEQUENCE_OF_ANY:
4076             decodeFunc = CRYPT_AsnDecodeSequenceOfAny;
4077             break;
4078         case (WORD)PKCS_UTC_TIME:
4079             decodeFunc = CRYPT_AsnDecodeUtcTime;
4080             break;
4081         case (WORD)X509_CRL_DIST_POINTS:
4082             decodeFunc = CRYPT_AsnDecodeCRLDistPoints;
4083             break;
4084         case (WORD)X509_ENHANCED_KEY_USAGE:
4085             decodeFunc = CRYPT_AsnDecodeEnhancedKeyUsage;
4086             break;
4087         case (WORD)PKCS_ATTRIBUTES:
4088             decodeFunc = CRYPT_AsnDecodePKCSAttributes;
4089             break;
4090         case (WORD)X509_ISSUING_DIST_POINT:
4091             decodeFunc = CRYPT_AsnDecodeIssuingDistPoint;
4092             break;
4093         case (WORD)PKCS7_SIGNER_INFO:
4094             decodeFunc = CRYPT_AsnDecodePKCSSignerInfo;
4095             break;
4096         }
4097     }
4098     else if (!strcmp(lpszStructType, szOID_CERT_EXTENSIONS))
4099         decodeFunc = CRYPT_AsnDecodeExtensions;
4100     else if (!strcmp(lpszStructType, szOID_RSA_signingTime))
4101         decodeFunc = CRYPT_AsnDecodeUtcTime;
4102     else if (!strcmp(lpszStructType, szOID_AUTHORITY_KEY_IDENTIFIER))
4103         decodeFunc = CRYPT_AsnDecodeAuthorityKeyId;
4104     else if (!strcmp(lpszStructType, szOID_AUTHORITY_KEY_IDENTIFIER2))
4105         decodeFunc = CRYPT_AsnDecodeAuthorityKeyId2;
4106     else if (!strcmp(lpszStructType, szOID_CRL_REASON_CODE))
4107         decodeFunc = CRYPT_AsnDecodeEnumerated;
4108     else if (!strcmp(lpszStructType, szOID_KEY_USAGE))
4109         decodeFunc = CRYPT_AsnDecodeBits;
4110     else if (!strcmp(lpszStructType, szOID_SUBJECT_KEY_IDENTIFIER))
4111         decodeFunc = CRYPT_AsnDecodeOctets;
4112     else if (!strcmp(lpszStructType, szOID_BASIC_CONSTRAINTS))
4113         decodeFunc = CRYPT_AsnDecodeBasicConstraints;
4114     else if (!strcmp(lpszStructType, szOID_BASIC_CONSTRAINTS2))
4115         decodeFunc = CRYPT_AsnDecodeBasicConstraints2;
4116     else if (!strcmp(lpszStructType, szOID_ISSUER_ALT_NAME))
4117         decodeFunc = CRYPT_AsnDecodeAltName;
4118     else if (!strcmp(lpszStructType, szOID_ISSUER_ALT_NAME2))
4119         decodeFunc = CRYPT_AsnDecodeAltName;
4120     else if (!strcmp(lpszStructType, szOID_NEXT_UPDATE_LOCATION))
4121         decodeFunc = CRYPT_AsnDecodeAltName;
4122     else if (!strcmp(lpszStructType, szOID_SUBJECT_ALT_NAME))
4123         decodeFunc = CRYPT_AsnDecodeAltName;
4124     else if (!strcmp(lpszStructType, szOID_SUBJECT_ALT_NAME2))
4125         decodeFunc = CRYPT_AsnDecodeAltName;
4126     else if (!strcmp(lpszStructType, szOID_CRL_DIST_POINTS))
4127         decodeFunc = CRYPT_AsnDecodeCRLDistPoints;
4128     else if (!strcmp(lpszStructType, szOID_ENHANCED_KEY_USAGE))
4129         decodeFunc = CRYPT_AsnDecodeEnhancedKeyUsage;
4130     else if (!strcmp(lpszStructType, szOID_ISSUING_DIST_POINT))
4131         decodeFunc = CRYPT_AsnDecodeIssuingDistPoint;
4132     return decodeFunc;
4133 }
4134
4135 static CryptDecodeObjectFunc CRYPT_LoadDecoderFunc(DWORD dwCertEncodingType,
4136  LPCSTR lpszStructType, HCRYPTOIDFUNCADDR *hFunc)
4137 {
4138     static HCRYPTOIDFUNCSET set = NULL;
4139     CryptDecodeObjectFunc decodeFunc = NULL;
4140
4141     if (!set)
4142         set = CryptInitOIDFunctionSet(CRYPT_OID_DECODE_OBJECT_FUNC, 0);
4143     CryptGetOIDFunctionAddress(set, dwCertEncodingType, lpszStructType, 0,
4144      (void **)&decodeFunc, hFunc);
4145     return decodeFunc;
4146 }
4147
4148 static CryptDecodeObjectExFunc CRYPT_LoadDecoderExFunc(DWORD dwCertEncodingType,
4149  LPCSTR lpszStructType, HCRYPTOIDFUNCADDR *hFunc)
4150 {
4151     static HCRYPTOIDFUNCSET set = NULL;
4152     CryptDecodeObjectExFunc decodeFunc = NULL;
4153
4154     if (!set)
4155         set = CryptInitOIDFunctionSet(CRYPT_OID_DECODE_OBJECT_EX_FUNC, 0);
4156     CryptGetOIDFunctionAddress(set, dwCertEncodingType, lpszStructType, 0,
4157      (void **)&decodeFunc, hFunc);
4158     return decodeFunc;
4159 }
4160
4161 BOOL WINAPI CryptDecodeObject(DWORD dwCertEncodingType, LPCSTR lpszStructType,
4162  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo,
4163  DWORD *pcbStructInfo)
4164 {
4165     BOOL ret = FALSE;
4166     CryptDecodeObjectFunc pCryptDecodeObject = NULL;
4167     CryptDecodeObjectExFunc pCryptDecodeObjectEx = NULL;
4168     HCRYPTOIDFUNCADDR hFunc = NULL;
4169
4170     TRACE_(crypt)("(0x%08x, %s, %p, %d, 0x%08x, %p, %p)\n", dwCertEncodingType,
4171      debugstr_a(lpszStructType), pbEncoded, cbEncoded, dwFlags,
4172      pvStructInfo, pcbStructInfo);
4173
4174     if (!pvStructInfo && !pcbStructInfo)
4175     {
4176         SetLastError(ERROR_INVALID_PARAMETER);
4177         return FALSE;
4178     }
4179     if (!cbEncoded)
4180     {
4181         SetLastError(CRYPT_E_ASN1_EOD);
4182         return FALSE;
4183     }
4184     if (cbEncoded > MAX_ENCODED_LEN)
4185     {
4186         SetLastError(CRYPT_E_ASN1_LARGE);
4187         return FALSE;
4188     }
4189
4190     if (!(pCryptDecodeObjectEx = CRYPT_GetBuiltinDecoder(dwCertEncodingType,
4191      lpszStructType)))
4192     {
4193         TRACE_(crypt)("OID %s not found or unimplemented, looking for DLL\n",
4194          debugstr_a(lpszStructType));
4195         pCryptDecodeObject = CRYPT_LoadDecoderFunc(dwCertEncodingType,
4196          lpszStructType, &hFunc);
4197         if (!pCryptDecodeObject)
4198             pCryptDecodeObjectEx = CRYPT_LoadDecoderExFunc(dwCertEncodingType,
4199              lpszStructType, &hFunc);
4200     }
4201     if (pCryptDecodeObject)
4202         ret = pCryptDecodeObject(dwCertEncodingType, lpszStructType,
4203          pbEncoded, cbEncoded, dwFlags, pvStructInfo, pcbStructInfo);
4204     else if (pCryptDecodeObjectEx)
4205         ret = pCryptDecodeObjectEx(dwCertEncodingType, lpszStructType,
4206          pbEncoded, cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL,
4207          pvStructInfo, pcbStructInfo);
4208     if (hFunc)
4209         CryptFreeOIDFunctionAddress(hFunc, 0);
4210     TRACE_(crypt)("returning %d\n", ret);
4211     return ret;
4212 }
4213
4214 BOOL WINAPI CryptDecodeObjectEx(DWORD dwCertEncodingType, LPCSTR lpszStructType,
4215  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
4216  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
4217 {
4218     BOOL ret = FALSE;
4219     CryptDecodeObjectExFunc decodeFunc;
4220     HCRYPTOIDFUNCADDR hFunc = NULL;
4221
4222     TRACE_(crypt)("(0x%08x, %s, %p, %d, 0x%08x, %p, %p, %p)\n",
4223      dwCertEncodingType, debugstr_a(lpszStructType), pbEncoded,
4224      cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo);
4225
4226     if (!pvStructInfo && !pcbStructInfo)
4227     {
4228         SetLastError(ERROR_INVALID_PARAMETER);
4229         return FALSE;
4230     }
4231     if (!cbEncoded)
4232     {
4233         SetLastError(CRYPT_E_ASN1_EOD);
4234         return FALSE;
4235     }
4236     if (cbEncoded > MAX_ENCODED_LEN)
4237     {
4238         SetLastError(CRYPT_E_ASN1_LARGE);
4239         return FALSE;
4240     }
4241
4242     SetLastError(NOERROR);
4243     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG && pvStructInfo)
4244         *(BYTE **)pvStructInfo = NULL;
4245     decodeFunc = CRYPT_GetBuiltinDecoder(dwCertEncodingType, lpszStructType);
4246     if (!decodeFunc)
4247     {
4248         TRACE_(crypt)("OID %s not found or unimplemented, looking for DLL\n",
4249          debugstr_a(lpszStructType));
4250         decodeFunc = CRYPT_LoadDecoderExFunc(dwCertEncodingType, lpszStructType,
4251          &hFunc);
4252     }
4253     if (decodeFunc)
4254         ret = decodeFunc(dwCertEncodingType, lpszStructType, pbEncoded,
4255          cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo);
4256     else
4257     {
4258         CryptDecodeObjectFunc pCryptDecodeObject =
4259          CRYPT_LoadDecoderFunc(dwCertEncodingType, lpszStructType, &hFunc);
4260
4261         /* Try CryptDecodeObject function.  Don't call CryptDecodeObject
4262          * directly, as that could cause an infinite loop.
4263          */
4264         if (pCryptDecodeObject)
4265         {
4266             if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
4267             {
4268                 ret = pCryptDecodeObject(dwCertEncodingType, lpszStructType,
4269                  pbEncoded, cbEncoded, dwFlags, NULL, pcbStructInfo);
4270                 if (ret && (ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
4271                  pvStructInfo, pcbStructInfo, *pcbStructInfo)))
4272                     ret = pCryptDecodeObject(dwCertEncodingType,
4273                      lpszStructType, pbEncoded, cbEncoded, dwFlags,
4274                      *(BYTE **)pvStructInfo, pcbStructInfo);
4275             }
4276             else
4277                 ret = pCryptDecodeObject(dwCertEncodingType, lpszStructType,
4278                  pbEncoded, cbEncoded, dwFlags, pvStructInfo, pcbStructInfo);
4279         }
4280     }
4281     if (hFunc)
4282         CryptFreeOIDFunctionAddress(hFunc, 0);
4283     TRACE_(crypt)("returning %d\n", ret);
4284     return ret;
4285 }