~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/crypt32/decode.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  1 /*
  2  * Copyright 2005-2008 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 isn't
 21  * implemented, 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 "Constants for CryptEncodeObject and CryptDecodeObject"
 31  */
 32 
 33 #include "config.h"
 34 #include "wine/port.h"
 35 
 36 #include <assert.h>
 37 #include <stdarg.h>
 38 #include <stdio.h>
 39 #include <stdlib.h>
 40 
 41 #define NONAMELESSUNION
 42 
 43 #include "windef.h"
 44 #include "winbase.h"
 45 #include "wincrypt.h"
 46 #include "winnls.h"
 47 #include "snmp.h"
 48 #include "wine/debug.h"
 49 #include "wine/exception.h"
 50 #include "crypt32_private.h"
 51 
 52 /* This is a bit arbitrary, but to set some limit: */
 53 #define MAX_ENCODED_LEN 0x02000000
 54 
 55 #define ASN_FLAGS_MASK 0xe0
 56 #define ASN_TYPE_MASK  0x1f
 57 
 58 WINE_DEFAULT_DEBUG_CHANNEL(cryptasn);
 59 WINE_DECLARE_DEBUG_CHANNEL(crypt);
 60 
 61 struct GenericArray
 62 {
 63     DWORD cItems;
 64     BYTE *rgItems;
 65 };
 66 
 67 typedef BOOL (WINAPI *CryptDecodeObjectFunc)(DWORD, LPCSTR, const BYTE *,
 68  DWORD, DWORD, void *, DWORD *);
 69 typedef BOOL (WINAPI *CryptDecodeObjectExFunc)(DWORD, LPCSTR, const BYTE *,
 70  DWORD, DWORD, PCRYPT_DECODE_PARA, void *, DWORD *);
 71 
 72 /* Internal decoders don't do memory allocation or exception handling, and
 73  * they report how many bytes they decoded.
 74  */
 75 typedef BOOL (*InternalDecodeFunc)(const BYTE *pbEncoded, DWORD cbEncoded,
 76  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded);
 77 
 78 static BOOL CRYPT_AsnDecodeChoiceOfTimeInternal(const BYTE *pbEncoded,
 79  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
 80  DWORD *pcbDecoded);
 81 static BOOL CRYPT_AsnDecodePubKeyInfoInternal(const BYTE *pbEncoded,
 82  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
 83  DWORD *pcbDecoded);
 84 /* Like CRYPT_AsnDecodeExtensions, except assumes rgExtension is set ahead of
 85  * time, doesn't do memory allocation, and doesn't do exception handling.
 86  */
 87 static BOOL CRYPT_AsnDecodeExtensionsInternal(const BYTE *pbEncoded,
 88  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
 89  DWORD *pcbDecoded);
 90 /* Assumes algo->Parameters.pbData is set ahead of time. */
 91 static BOOL CRYPT_AsnDecodeAlgorithmId(const BYTE *pbEncoded, DWORD cbEncoded,
 92  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded);
 93 static BOOL CRYPT_AsnDecodeBool(const BYTE *pbEncoded, DWORD cbEncoded,
 94  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded);
 95 /* Assumes the CRYPT_DATA_BLOB's pbData member has been initialized */
 96 static BOOL CRYPT_AsnDecodeOctetsInternal(const BYTE *pbEncoded,
 97  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
 98  DWORD *pcbDecoded);
 99 /* Doesn't check the tag, assumes the caller does so */
100 static BOOL CRYPT_AsnDecodeBitsInternal(const BYTE *pbEncoded, DWORD cbEncoded,
101  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded);
102 static BOOL CRYPT_AsnDecodeIntInternal(const BYTE *pbEncoded, DWORD cbEncoded,
103  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded);
104 /* Like CRYPT_AsnDecodeInteger, but assumes the CRYPT_INTEGER_BLOB's pbData
105  * member has been initialized, doesn't do exception handling, and doesn't do
106  * memory allocation.  Also doesn't check tag, assumes the caller has checked
107  * it.
108  */
109 static BOOL CRYPT_AsnDecodeIntegerInternal(const BYTE *pbEncoded,
110  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
111  DWORD *pcbDecoded);
112 /* Like CRYPT_AsnDecodeInteger, but unsigned.  */
113 static BOOL CRYPT_AsnDecodeUnsignedIntegerInternal(const BYTE *pbEncoded,
114  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
115  DWORD *pcbDecoded);
116 static BOOL CRYPT_AsnDecodePKCSAttributesInternal(const BYTE *pbEncoded,
117  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
118  DWORD *pcbDecoded);
119 
120 /* Gets the number of length bytes from the given (leading) length byte */
121 #define GET_LEN_BYTES(b) ((b) <= 0x80 ? 1 : 1 + ((b) & 0x7f))
122 
123 /* Helper function to get the encoded length of the data starting at pbEncoded,
124  * where pbEncoded[0] is the tag.  If the data are too short to contain a
125  * length or if the length is too large for cbEncoded, sets an appropriate
126  * error code and returns FALSE.  If the encoded length is unknown due to
127  * indefinite length encoding, *len is set to CMSG_INDEFINITE_LENGTH.
128  */
129 static BOOL CRYPT_GetLengthIndefinite(const BYTE *pbEncoded, DWORD cbEncoded,
130  DWORD *len)
131 {
132     BOOL ret;
133 
134     if (cbEncoded <= 1)
135     {
136         SetLastError(CRYPT_E_ASN1_CORRUPT);
137         ret = FALSE;
138     }
139     else if (pbEncoded[1] <= 0x7f)
140     {
141         if (pbEncoded[1] + 1 > cbEncoded)
142         {
143             SetLastError(CRYPT_E_ASN1_EOD);
144             ret = FALSE;
145         }
146         else
147         {
148             *len = pbEncoded[1];
149             ret = TRUE;
150         }
151     }
152     else if (pbEncoded[1] == 0x80)
153     {
154         *len = CMSG_INDEFINITE_LENGTH;
155         ret = TRUE;
156     }
157     else
158     {
159         BYTE lenLen = GET_LEN_BYTES(pbEncoded[1]);
160 
161         if (lenLen > sizeof(DWORD) + 1)
162         {
163             SetLastError(CRYPT_E_ASN1_LARGE);
164             ret = FALSE;
165         }
166         else if (lenLen + 2 > cbEncoded)
167         {
168             SetLastError(CRYPT_E_ASN1_CORRUPT);
169             ret = FALSE;
170         }
171         else
172         {
173             DWORD out = 0;
174 
175             pbEncoded += 2;
176             while (--lenLen)
177             {
178                 out <<= 8;
179                 out |= *pbEncoded++;
180             }
181             if (out + lenLen + 1 > cbEncoded)
182             {
183                 SetLastError(CRYPT_E_ASN1_EOD);
184                 ret = FALSE;
185             }
186             else
187             {
188                 *len = out;
189                 ret = TRUE;
190             }
191         }
192     }
193     return ret;
194 }
195 
196 /* Like CRYPT_GetLengthIndefinite, but disallows indefinite-length encoding. */
197 static BOOL CRYPT_GetLen(const BYTE *pbEncoded, DWORD cbEncoded, DWORD *len)
198 {
199     BOOL ret;
200 
201     if ((ret = CRYPT_GetLengthIndefinite(pbEncoded, cbEncoded, len)) &&
202      *len == CMSG_INDEFINITE_LENGTH)
203     {
204         SetLastError(CRYPT_E_ASN1_CORRUPT);
205         ret = FALSE;
206     }
207     return ret;
208 }
209 
210 /* Helper function to check *pcbStructInfo, set it to the required size, and
211  * optionally to allocate memory.  Assumes pvStructInfo is not NULL.
212  * If CRYPT_DECODE_ALLOC_FLAG is set in dwFlags, *pvStructInfo will be set to a
213  * pointer to the newly allocated memory.
214  */
215 static BOOL CRYPT_DecodeEnsureSpace(DWORD dwFlags,
216  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo,
217  DWORD bytesNeeded)
218 {
219     BOOL ret = TRUE;
220 
221     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
222     {
223         if (pDecodePara && pDecodePara->pfnAlloc)
224             *(BYTE **)pvStructInfo = pDecodePara->pfnAlloc(bytesNeeded);
225         else
226             *(BYTE **)pvStructInfo = LocalAlloc(0, bytesNeeded);
227         if (!*(BYTE **)pvStructInfo)
228             ret = FALSE;
229         else
230             *pcbStructInfo = bytesNeeded;
231     }
232     else if (*pcbStructInfo < bytesNeeded)
233     {
234         *pcbStructInfo = bytesNeeded;
235         SetLastError(ERROR_MORE_DATA);
236         ret = FALSE;
237     }
238     else
239         *pcbStructInfo = bytesNeeded;
240     return ret;
241 }
242 
243 static void CRYPT_FreeSpace(PCRYPT_DECODE_PARA pDecodePara, LPVOID pv)
244 {
245     if (pDecodePara && pDecodePara->pfnFree)
246         pDecodePara->pfnFree(pv);
247     else
248         LocalFree(pv);
249 }
250 
251 /* Helper function to check *pcbStructInfo and set it to the required size.
252  * Assumes pvStructInfo is not NULL.
253  */
254 static BOOL CRYPT_DecodeCheckSpace(DWORD *pcbStructInfo, DWORD bytesNeeded)
255 {
256     BOOL ret;
257 
258     if (*pcbStructInfo < bytesNeeded)
259     {
260         *pcbStructInfo = bytesNeeded;
261         SetLastError(ERROR_MORE_DATA);
262         ret = FALSE;
263     }
264     else
265     {
266         *pcbStructInfo = bytesNeeded;
267         ret = TRUE;
268     }
269     return ret;
270 }
271 
272 /* tag:
273  *     The expected tag of the item.  If tag is 0, decodeFunc is called
274  *     regardless of the tag value seen.
275  * offset:
276  *     A sequence is decoded into a struct.  The offset member is the
277  *     offset of this item within that struct.
278  * decodeFunc:
279  *     The decoder function to use.  If this is NULL, then the member isn't
280  *     decoded, but minSize space is reserved for it.
281  * minSize:
282  *     The minimum amount of space occupied after decoding.  You must set this.
283  * optional:
284  *     If true, and the tag doesn't match the expected tag for this item,
285  *     or the decodeFunc fails with CRYPT_E_ASN1_BADTAG, then minSize space is
286  *     filled with 0 for this member.
287  * hasPointer, pointerOffset:
288  *     If the item has dynamic data, set hasPointer to TRUE, pointerOffset to
289  *     the offset within the struct of the data pointer (or to the
290  *     first data pointer, if more than one exist).
291  * size:
292  *     Used by CRYPT_AsnDecodeSequence, not for your use.
293  */
294 struct AsnDecodeSequenceItem
295 {
296     BYTE               tag;
297     DWORD              offset;
298     InternalDecodeFunc decodeFunc;
299     DWORD              minSize;
300     BOOL               optional;
301     BOOL               hasPointer;
302     DWORD              pointerOffset;
303     DWORD              size;
304 };
305 
306 /* Decodes the items in a sequence, where the items are described in items,
307  * the encoded data are in pbEncoded with length cbEncoded.  Decodes into
308  * pvStructInfo.  nextData is a pointer to the memory location at which the
309  * first decoded item with a dynamic pointer should point.
310  * Upon decoding, *cbDecoded is the total number of bytes decoded.
311  * Each item decoder is never called with CRYPT_DECODE_ALLOC_FLAG set.
312  */
313 static BOOL CRYPT_AsnDecodeSequenceItems(struct AsnDecodeSequenceItem items[],
314  DWORD cItem, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
315  void *pvStructInfo, BYTE *nextData, DWORD *cbDecoded)
316 {
317     BOOL ret;
318     DWORD i, decoded = 0;
319     const BYTE *ptr = pbEncoded;
320 
321     TRACE("%p, %d, %p, %d, %08x, %p, %p, %p\n", items, cItem, pbEncoded,
322      cbEncoded, dwFlags, pvStructInfo, nextData, cbDecoded);
323 
324     for (i = 0, ret = TRUE; ret && i < cItem; i++)
325     {
326         if (cbEncoded - (ptr - pbEncoded) != 0)
327         {
328             DWORD itemLen;
329 
330             if ((ret = CRYPT_GetLengthIndefinite(ptr,
331              cbEncoded - (ptr - pbEncoded), &itemLen)))
332             {
333                 BYTE itemLenBytes = GET_LEN_BYTES(ptr[1]);
334 
335                 if (ptr[0] == items[i].tag || !items[i].tag)
336                 {
337                     DWORD itemEncodedLen;
338 
339                     if (itemLen == CMSG_INDEFINITE_LENGTH)
340                         itemEncodedLen = cbEncoded - (ptr - pbEncoded);
341                     else
342                         itemEncodedLen = 1 + itemLenBytes + itemLen;
343                     if (nextData && pvStructInfo && items[i].hasPointer)
344                     {
345                         TRACE("Setting next pointer to %p\n",
346                          nextData);
347                         *(BYTE **)((BYTE *)pvStructInfo +
348                          items[i].pointerOffset) = nextData;
349                     }
350                     if (items[i].decodeFunc)
351                     {
352                         DWORD itemDecoded;
353 
354                         if (pvStructInfo)
355                             TRACE("decoding item %d\n", i);
356                         else
357                             TRACE("sizing item %d\n", i);
358                         ret = items[i].decodeFunc(ptr, itemEncodedLen,
359                          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG,
360                          pvStructInfo ?  (BYTE *)pvStructInfo + items[i].offset
361                          : NULL, &items[i].size, &itemDecoded);
362                         if (ret)
363                         {
364                             /* Account for alignment padding */
365                             items[i].size = ALIGN_DWORD_PTR(items[i].size);
366                             TRACE("item %d size: %d\n", i, items[i].size);
367                             if (nextData && items[i].hasPointer &&
368                              items[i].size > items[i].minSize)
369                                 nextData += items[i].size - items[i].minSize;
370                             if (itemDecoded > itemEncodedLen)
371                             {
372                                 WARN("decoded length %d exceeds encoded %d\n",
373                                  itemDecoded, itemEncodedLen);
374                                 SetLastError(CRYPT_E_ASN1_CORRUPT);
375                                 ret = FALSE;
376                             }
377                             else
378                             {
379                                 if (itemLen == CMSG_INDEFINITE_LENGTH)
380                                 {
381                                     if (itemDecoded > itemEncodedLen - 2 ||
382                                      *(ptr + itemDecoded) != 0 ||
383                                      *(ptr + itemDecoded + 1) != 0)
384                                     {
385                                         TRACE("expected 0 TLV\n");
386                                         SetLastError(CRYPT_E_ASN1_CORRUPT);
387                                         ret = FALSE;
388                                     }
389                                     else
390                                         itemDecoded += 2;
391                                 }
392                                 if (ret)
393                                 {
394                                     ptr += itemDecoded;
395                                     decoded += itemDecoded;
396                                     TRACE("item %d: decoded %d bytes\n", i,
397                                      itemDecoded);
398                                 }
399                             }
400                         }
401                         else if (items[i].optional &&
402                          GetLastError() == CRYPT_E_ASN1_BADTAG)
403                         {
404                             TRACE("skipping optional item %d\n", i);
405                             items[i].size = items[i].minSize;
406                             SetLastError(NOERROR);
407                             ret = TRUE;
408                         }
409                         else
410                             TRACE("item %d failed: %08x\n", i,
411                              GetLastError());
412                     }
413                     else if (itemLen == CMSG_INDEFINITE_LENGTH)
414                     {
415                         ERR("can't use indefinite length encoding without a decoder\n");
416                         SetLastError(CRYPT_E_ASN1_CORRUPT);
417                         ret = FALSE;
418                     }
419                     else
420                     {
421                         TRACE("item %d: decoded %d bytes\n", i, itemEncodedLen);
422                         ptr += itemEncodedLen;
423                         decoded += itemEncodedLen;
424                         items[i].size = items[i].minSize;
425                     }
426                 }
427                 else if (items[i].optional)
428                 {
429                     TRACE("skipping optional item %d\n", i);
430                     items[i].size = items[i].minSize;
431                 }
432                 else
433                 {
434                     TRACE("item %d: tag %02x doesn't match expected %02x\n",
435                      i, ptr[0], items[i].tag);
436                     SetLastError(CRYPT_E_ASN1_BADTAG);
437                     ret = FALSE;
438                 }
439             }
440         }
441         else if (items[i].optional)
442         {
443             TRACE("missing optional item %d, skipping\n", i);
444             items[i].size = items[i].minSize;
445         }
446         else
447         {
448             TRACE("not enough bytes for item %d, failing\n", i);
449             SetLastError(CRYPT_E_ASN1_CORRUPT);
450             ret = FALSE;
451         }
452     }
453     if (cbDecoded)
454         *cbDecoded = decoded;
455     TRACE("returning %d\n", ret);
456     return ret;
457 }
458 
459 /* This decodes an arbitrary sequence into a contiguous block of memory
460  * (basically, a struct.)  Each element being decoded is described by a struct
461  * AsnDecodeSequenceItem, see above.
462  * startingPointer is an optional pointer to the first place where dynamic
463  * data will be stored.  If you know the starting offset, you may pass it
464  * here.  Otherwise, pass NULL, and one will be inferred from the items.
465  */
466 static BOOL CRYPT_AsnDecodeSequence(struct AsnDecodeSequenceItem items[],
467  DWORD cItem, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
468  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo,
469  DWORD *pcbDecoded, void *startingPointer)
470 {
471     BOOL ret;
472 
473     TRACE("%p, %d, %p, %d, %08x, %p, %p, %d, %p\n", items, cItem, pbEncoded,
474      cbEncoded, dwFlags, pDecodePara, pvStructInfo, *pcbStructInfo,
475      startingPointer);
476 
477     if (!cbEncoded)
478     {
479         SetLastError(CRYPT_E_ASN1_EOD);
480         return FALSE;
481     }
482     if (pbEncoded[0] == ASN_SEQUENCE)
483     {
484         DWORD dataLen;
485 
486         if ((ret = CRYPT_GetLengthIndefinite(pbEncoded, cbEncoded, &dataLen)))
487         {
488             DWORD lenBytes = GET_LEN_BYTES(pbEncoded[1]), cbDecoded;
489             const BYTE *ptr = pbEncoded + 1 + lenBytes;
490             BOOL indefinite = FALSE;
491 
492             cbEncoded -= 1 + lenBytes;
493             if (dataLen == CMSG_INDEFINITE_LENGTH)
494             {
495                 dataLen = cbEncoded;
496                 indefinite = TRUE;
497             }
498             else if (cbEncoded < dataLen)
499             {
500                 TRACE("dataLen %d exceeds cbEncoded %d, failing\n", dataLen,
501                  cbEncoded);
502                 SetLastError(CRYPT_E_ASN1_CORRUPT);
503                 ret = FALSE;
504             }
505             if (ret)
506             {
507                 ret = CRYPT_AsnDecodeSequenceItems(items, cItem,
508                  ptr, dataLen, dwFlags, NULL, NULL, &cbDecoded);
509                 if (ret && dataLen == CMSG_INDEFINITE_LENGTH)
510                 {
511                     if (cbDecoded > cbEncoded - 2)
512                     {
513                         /* Not enough space for 0 TLV */
514                         SetLastError(CRYPT_E_ASN1_CORRUPT);
515                         ret = FALSE;
516                     }
517                     else if (*(ptr + cbDecoded) != 0 ||
518                      *(ptr + cbDecoded + 1) != 0)
519                     {
520                         TRACE("expected 0 TLV\n");
521                         SetLastError(CRYPT_E_ASN1_CORRUPT);
522                         ret = FALSE;
523                     }
524                     else
525                         cbDecoded += 2;
526                 }
527             }
528             if (ret && !indefinite && cbDecoded != dataLen)
529             {
530                 TRACE("expected %d decoded, got %d, failing\n", dataLen,
531                  cbDecoded);
532                 SetLastError(CRYPT_E_ASN1_CORRUPT);
533                 ret = FALSE;
534             }
535             if (ret)
536             {
537                 DWORD i, bytesNeeded = 0, structSize = 0;
538 
539                 for (i = 0; i < cItem; i++)
540                 {
541                     bytesNeeded += items[i].size;
542                     structSize += items[i].minSize;
543                 }
544                 if (pcbDecoded)
545                     *pcbDecoded = 1 + lenBytes + cbDecoded;
546                 if (!pvStructInfo)
547                     *pcbStructInfo = bytesNeeded;
548                 else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags,
549                  pDecodePara, pvStructInfo, pcbStructInfo, bytesNeeded)))
550                 {
551                     BYTE *nextData;
552 
553                     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
554                         pvStructInfo = *(BYTE **)pvStructInfo;
555                     if (startingPointer)
556                         nextData = (BYTE *)startingPointer;
557                     else
558                         nextData = (BYTE *)pvStructInfo + structSize;
559                     memset(pvStructInfo, 0, structSize);
560                     ret = CRYPT_AsnDecodeSequenceItems(items, cItem,
561                      ptr, dataLen, dwFlags, pvStructInfo, nextData,
562                      &cbDecoded);
563                     if (!ret && (dwFlags & CRYPT_DECODE_ALLOC_FLAG))
564                         CRYPT_FreeSpace(pDecodePara, pvStructInfo);
565                 }
566             }
567         }
568     }
569     else
570     {
571         SetLastError(CRYPT_E_ASN1_BADTAG);
572         ret = FALSE;
573     }
574     TRACE("returning %d (%08x)\n", ret, GetLastError());
575     return ret;
576 }
577 
578 /* tag:
579  *     The expected tag of the entire encoded array (usually a variant
580  *     of ASN_SETOF or ASN_SEQUENCEOF.)  If tag is 0, decodeFunc is called
581  *     regardless of the tag seen.
582  * decodeFunc:
583  *     used to decode each item in the array
584  * itemSize:
585  *      is the minimum size of each decoded item
586  * hasPointer:
587  *      indicates whether each item has a dynamic pointer
588  * pointerOffset:
589  *     indicates the offset within itemSize at which the pointer exists
590  */
591 struct AsnArrayDescriptor
592 {
593     BYTE               tag;
594     InternalDecodeFunc decodeFunc;
595     DWORD              itemSize;
596     BOOL               hasPointer;
597     DWORD              pointerOffset;
598 };
599 
600 struct AsnArrayItemSize
601 {
602     DWORD encodedLen;
603     DWORD size;
604 };
605 
606 /* Decodes an array of like types into a struct GenericArray.
607  * The layout and decoding of the array are described by a struct
608  * AsnArrayDescriptor.
609  */
610 static BOOL CRYPT_AsnDecodeArray(const struct AsnArrayDescriptor *arrayDesc,
611  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
612  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo,
613  DWORD *pcbDecoded, void *startingPointer)
614 {
615     BOOL ret = TRUE;
616 
617     TRACE("%p, %p, %d, %08x, %p, %p, %d, %p\n", arrayDesc, pbEncoded,
618      cbEncoded, dwFlags, pDecodePara, pvStructInfo, *pcbStructInfo,
619      startingPointer);
620 
621     if (!arrayDesc->tag || pbEncoded[0] == arrayDesc->tag)
622     {
623         DWORD dataLen;
624 
625         if ((ret = CRYPT_GetLengthIndefinite(pbEncoded, cbEncoded, &dataLen)))
626         {
627             DWORD bytesNeeded, cItems = 0, decoded;
628             BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
629             /* There can be arbitrarily many items, but there is often only one.
630              */
631             struct AsnArrayItemSize itemSize = { 0 }, *itemSizes = &itemSize;
632 
633             decoded = 1 + lenBytes;
634             bytesNeeded = sizeof(struct GenericArray);
635             if (dataLen)
636             {
637                 const BYTE *ptr;
638                 BOOL doneDecoding = FALSE;
639 
640                 for (ptr = pbEncoded + 1 + lenBytes; ret && !doneDecoding; )
641                 {
642                     if (dataLen == CMSG_INDEFINITE_LENGTH)
643                     {
644                         if (ptr[0] == 0)
645                         {
646                             doneDecoding = TRUE;
647                             if (ptr[1] != 0)
648                             {
649                                 SetLastError(CRYPT_E_ASN1_CORRUPT);
650                                 ret = FALSE;
651                             }
652                             else
653                                 decoded += 2;
654                         }
655                     }
656                     else if (ptr - pbEncoded - 1 - lenBytes >= dataLen)
657                         doneDecoding = TRUE;
658                     if (!doneDecoding)
659                     {
660                         DWORD itemEncoded, itemDataLen, itemDecoded, size = 0;
661 
662                         /* Each item decoded may not tolerate extraneous bytes,
663                          * so get the length of the next element if known.
664                          */
665                         if ((ret = CRYPT_GetLengthIndefinite(ptr,
666                          cbEncoded - (ptr - pbEncoded), &itemDataLen)))
667                         {
668                             if (itemDataLen == CMSG_INDEFINITE_LENGTH)
669                                 itemEncoded = cbEncoded - (ptr - pbEncoded);
670                             else
671                                 itemEncoded = 1 + GET_LEN_BYTES(ptr[1]) +
672                                  itemDataLen;
673                         }
674                         if (ret)
675                             ret = arrayDesc->decodeFunc(ptr, itemEncoded,
676                              dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &size,
677                              &itemDecoded);
678                         if (ret)
679                         {
680                             cItems++;
681                             if (itemSizes != &itemSize)
682                                 itemSizes = CryptMemRealloc(itemSizes,
683                                  cItems * sizeof(struct AsnArrayItemSize));
684                             else if (cItems > 1)
685                             {
686                                 itemSizes =
687                                  CryptMemAlloc(
688                                  cItems * sizeof(struct AsnArrayItemSize));
689                                 if (itemSizes)
690                                     memcpy(itemSizes, &itemSize,
691                                      sizeof(itemSize));
692                             }
693                             if (itemSizes)
694                             {
695                                 decoded += itemDecoded;
696                                 itemSizes[cItems - 1].encodedLen = itemEncoded;
697                                 itemSizes[cItems - 1].size = size;
698                                 bytesNeeded += size;
699                                 ptr += itemEncoded;
700                             }
701                             else
702                                 ret = FALSE;
703                         }
704                     }
705                 }
706             }
707             if (ret)
708             {
709                 if (pcbDecoded)
710                     *pcbDecoded = decoded;
711                 if (!pvStructInfo)
712                     *pcbStructInfo = bytesNeeded;
713                 else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags,
714                  pDecodePara, pvStructInfo, pcbStructInfo, bytesNeeded)))
715                 {
716                     DWORD i;
717                     BYTE *nextData;
718                     const BYTE *ptr;
719                     struct GenericArray *array;
720 
721                     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
722                         pvStructInfo = *(BYTE **)pvStructInfo;
723                     array = (struct GenericArray *)pvStructInfo;
724                     array->cItems = cItems;
725                     if (startingPointer)
726                         array->rgItems = startingPointer;
727                     else
728                         array->rgItems = (BYTE *)array +
729                          sizeof(struct GenericArray);
730                     nextData = array->rgItems +
731                      array->cItems * arrayDesc->itemSize;
732                     for (i = 0, ptr = pbEncoded + 1 + lenBytes; ret &&
733                      i < cItems && ptr - pbEncoded - 1 - lenBytes <
734                      dataLen; i++)
735                     {
736                         DWORD itemDecoded;
737 
738                         if (arrayDesc->hasPointer)
739                             *(BYTE **)(array->rgItems + i * arrayDesc->itemSize
740                              + arrayDesc->pointerOffset) = nextData;
741                         ret = arrayDesc->decodeFunc(ptr,
742                          itemSizes[i].encodedLen,
743                          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG,
744                          array->rgItems + i * arrayDesc->itemSize,
745                          &itemSizes[i].size, &itemDecoded);
746                         if (ret)
747                         {
748                             nextData += itemSizes[i].size - arrayDesc->itemSize;
749                             ptr += itemDecoded;
750                         }
751                     }
752                     if (!ret && (dwFlags & CRYPT_DECODE_ALLOC_FLAG))
753                         CRYPT_FreeSpace(pDecodePara, pvStructInfo);
754                 }
755             }
756             if (itemSizes != &itemSize)
757                 CryptMemFree(itemSizes);
758         }
759     }
760     else
761     {
762         SetLastError(CRYPT_E_ASN1_BADTAG);
763         ret = FALSE;
764     }
765     return ret;
766 }
767 
768 /* Decodes a DER-encoded BLOB into a CRYPT_DER_BLOB struct pointed to by
769  * pvStructInfo.  The BLOB must be non-empty, otherwise the last error is set
770  * to CRYPT_E_ASN1_CORRUPT.
771  * Warning: assumes the CRYPT_DER_BLOB pointed to by pvStructInfo has pbData
772  * set!
773  */
774 static BOOL CRYPT_AsnDecodeDerBlob(const BYTE *pbEncoded, DWORD cbEncoded,
775  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
776 {
777     BOOL ret;
778     DWORD dataLen;
779 
780     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
781     {
782         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
783         DWORD bytesNeeded = sizeof(CRYPT_DER_BLOB);
784        
785         if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
786             bytesNeeded += 1 + lenBytes + dataLen;
787 
788         if (pcbDecoded)
789             *pcbDecoded = 1 + lenBytes + dataLen;
790         if (!pvStructInfo)
791             *pcbStructInfo = bytesNeeded;
792         else if ((ret = CRYPT_DecodeCheckSpace(pcbStructInfo, bytesNeeded)))
793         {
794             CRYPT_DER_BLOB *blob;
795 
796             if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
797                 pvStructInfo = *(BYTE **)pvStructInfo;
798             blob = (CRYPT_DER_BLOB *)pvStructInfo;
799             blob->cbData = 1 + lenBytes + dataLen;
800             if (blob->cbData)
801             {
802                 if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
803                     blob->pbData = (BYTE *)pbEncoded;
804                 else
805                 {
806                     assert(blob->pbData);
807                     memcpy(blob->pbData, pbEncoded, blob->cbData);
808                 }
809             }
810             else
811             {
812                 SetLastError(CRYPT_E_ASN1_CORRUPT);
813                 ret = FALSE;
814             }
815         }
816     }
817     return ret;
818 }
819 
820 /* Like CRYPT_AsnDecodeBitsInternal, but swaps the bytes */
821 static BOOL CRYPT_AsnDecodeBitsSwapBytes(const BYTE *pbEncoded,
822  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
823  DWORD *pcbDecoded)
824 {
825     BOOL ret;
826 
827     TRACE("(%p, %d, 0x%08x, %p, %d, %p)\n", pbEncoded, cbEncoded, dwFlags,
828      pvStructInfo, *pcbStructInfo, pcbDecoded);
829 
830     /* Can't use the CRYPT_DECODE_NOCOPY_FLAG, because we modify the bytes in-
831      * place.
832      */
833     ret = CRYPT_AsnDecodeBitsInternal(pbEncoded, cbEncoded,
834      dwFlags & ~CRYPT_DECODE_NOCOPY_FLAG, pvStructInfo, pcbStructInfo,
835      pcbDecoded);
836     if (ret && pvStructInfo)
837     {
838         CRYPT_BIT_BLOB *blob = (CRYPT_BIT_BLOB *)pvStructInfo;
839 
840         if (blob->cbData)
841         {
842             DWORD i;
843             BYTE temp;
844 
845             for (i = 0; i < blob->cbData / 2; i++)
846             {
847                 temp = blob->pbData[i];
848                 blob->pbData[i] = blob->pbData[blob->cbData - i - 1];
849                 blob->pbData[blob->cbData - i - 1] = temp;
850             }
851         }
852     }
853     TRACE("returning %d (%08x)\n", ret, GetLastError());
854     return ret;
855 }
856 
857 static BOOL WINAPI CRYPT_AsnDecodeCertSignedContent(DWORD dwCertEncodingType,
858  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
859  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
860 {
861     BOOL ret = TRUE;
862 
863     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
864      pDecodePara, pvStructInfo, *pcbStructInfo);
865 
866     __TRY
867     {
868         struct AsnDecodeSequenceItem items[] = {
869          { 0, offsetof(CERT_SIGNED_CONTENT_INFO, ToBeSigned),
870            CRYPT_AsnDecodeDerBlob, sizeof(CRYPT_DER_BLOB), FALSE, TRUE,
871            offsetof(CERT_SIGNED_CONTENT_INFO, ToBeSigned.pbData), 0 },
872          { ASN_SEQUENCEOF, offsetof(CERT_SIGNED_CONTENT_INFO,
873            SignatureAlgorithm), CRYPT_AsnDecodeAlgorithmId,
874            sizeof(CRYPT_ALGORITHM_IDENTIFIER), FALSE, TRUE,
875            offsetof(CERT_SIGNED_CONTENT_INFO, SignatureAlgorithm.pszObjId), 0 },
876          { ASN_BITSTRING, offsetof(CERT_SIGNED_CONTENT_INFO, Signature),
877            CRYPT_AsnDecodeBitsSwapBytes, sizeof(CRYPT_BIT_BLOB), FALSE, TRUE,
878            offsetof(CERT_SIGNED_CONTENT_INFO, Signature.pbData), 0 },
879         };
880 
881         if (dwFlags & CRYPT_DECODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG)
882             items[2].decodeFunc = CRYPT_AsnDecodeBitsInternal;
883         ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
884          pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
885          pcbStructInfo, NULL, NULL);
886     }
887     __EXCEPT_PAGE_FAULT
888     {
889         SetLastError(STATUS_ACCESS_VIOLATION);
890         ret = FALSE;
891     }
892     __ENDTRY
893 
894     TRACE("Returning %d (%08x)\n", ret, GetLastError());
895     return ret;
896 }
897 
898 static BOOL CRYPT_AsnDecodeCertVersion(const BYTE *pbEncoded, DWORD cbEncoded,
899  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
900 {
901     BOOL ret;
902     DWORD dataLen;
903 
904     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
905     {
906         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
907 
908         ret = CRYPT_AsnDecodeIntInternal(pbEncoded + 1 + lenBytes, dataLen,
909          dwFlags, pvStructInfo, pcbStructInfo, NULL);
910         if (pcbDecoded)
911             *pcbDecoded = 1 + lenBytes + dataLen;
912     }
913     return ret;
914 }
915 
916 static BOOL CRYPT_AsnDecodeValidity(const BYTE *pbEncoded, DWORD cbEncoded,
917  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
918 {
919     BOOL ret;
920 
921     struct AsnDecodeSequenceItem items[] = {
922      { 0, offsetof(CERT_PRIVATE_KEY_VALIDITY, NotBefore),
923        CRYPT_AsnDecodeChoiceOfTimeInternal, sizeof(FILETIME), FALSE, FALSE, 0 },
924      { 0, offsetof(CERT_PRIVATE_KEY_VALIDITY, NotAfter),
925        CRYPT_AsnDecodeChoiceOfTimeInternal, sizeof(FILETIME), FALSE, FALSE, 0 },
926     };
927 
928     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
929      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
930      pcbDecoded, NULL);
931     return ret;
932 }
933 
934 static BOOL CRYPT_AsnDecodeCertExtensions(const BYTE *pbEncoded,
935  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
936  DWORD *pcbDecoded)
937 {
938     BOOL ret;
939     DWORD dataLen;
940 
941     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
942     {
943         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
944 
945         ret = CRYPT_AsnDecodeExtensionsInternal(pbEncoded + 1 + lenBytes,
946          dataLen, dwFlags, pvStructInfo, pcbStructInfo, NULL);
947         if (ret && pcbDecoded)
948             *pcbDecoded = 1 + lenBytes + dataLen;
949     }
950     return ret;
951 }
952 
953 static BOOL WINAPI CRYPT_AsnDecodeCertInfo(DWORD dwCertEncodingType,
954  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
955  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
956 {
957     BOOL ret = TRUE;
958     struct AsnDecodeSequenceItem items[] = {
959      { ASN_CONTEXT | ASN_CONSTRUCTOR, offsetof(CERT_INFO, dwVersion),
960        CRYPT_AsnDecodeCertVersion, sizeof(DWORD), TRUE, FALSE, 0, 0 },
961      { ASN_INTEGER, offsetof(CERT_INFO, SerialNumber),
962        CRYPT_AsnDecodeIntegerInternal, sizeof(CRYPT_INTEGER_BLOB), FALSE,
963        TRUE, offsetof(CERT_INFO, SerialNumber.pbData), 0 },
964      { ASN_SEQUENCEOF, offsetof(CERT_INFO, SignatureAlgorithm),
965        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
966        FALSE, TRUE, offsetof(CERT_INFO, SignatureAlgorithm.pszObjId), 0 },
967      { 0, offsetof(CERT_INFO, Issuer), CRYPT_AsnDecodeDerBlob,
968        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CERT_INFO,
969        Issuer.pbData) },
970      { ASN_SEQUENCEOF, offsetof(CERT_INFO, NotBefore),
971        CRYPT_AsnDecodeValidity, sizeof(CERT_PRIVATE_KEY_VALIDITY), FALSE,
972        FALSE, 0 },
973      { 0, offsetof(CERT_INFO, Subject), CRYPT_AsnDecodeDerBlob,
974        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CERT_INFO,
975        Subject.pbData) },
976      { ASN_SEQUENCEOF, offsetof(CERT_INFO, SubjectPublicKeyInfo),
977        CRYPT_AsnDecodePubKeyInfoInternal, sizeof(CERT_PUBLIC_KEY_INFO),
978        FALSE, TRUE, offsetof(CERT_INFO,
979        SubjectPublicKeyInfo.Algorithm.Parameters.pbData), 0 },
980      { ASN_BITSTRING, offsetof(CERT_INFO, IssuerUniqueId),
981        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), TRUE, TRUE,
982        offsetof(CERT_INFO, IssuerUniqueId.pbData), 0 },
983      { ASN_BITSTRING, offsetof(CERT_INFO, SubjectUniqueId),
984        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), TRUE, TRUE,
985        offsetof(CERT_INFO, SubjectUniqueId.pbData), 0 },
986      { ASN_CONTEXT | ASN_CONSTRUCTOR | 3, offsetof(CERT_INFO, cExtension),
987        CRYPT_AsnDecodeCertExtensions, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
988        offsetof(CERT_INFO, rgExtension), 0 },
989     };
990 
991     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
992      pDecodePara, pvStructInfo, *pcbStructInfo);
993 
994     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
995      pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo,
996      NULL, NULL);
997     if (ret && pvStructInfo)
998     {
999         CERT_INFO *info;
1000 
1001         if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1002             info = *(CERT_INFO **)pvStructInfo;
1003         else
1004             info = (CERT_INFO *)pvStructInfo;
1005         if (!info->SerialNumber.cbData || !info->Issuer.cbData ||
1006          !info->Subject.cbData)
1007         {
1008             SetLastError(CRYPT_E_ASN1_CORRUPT);
1009             /* Don't need to deallocate, because it should have failed on the
1010              * first pass (and no memory was allocated.)
1011              */
1012             ret = FALSE;
1013         }
1014     }
1015 
1016     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1017     return ret;
1018 }
1019 
1020 static BOOL WINAPI CRYPT_AsnDecodeCert(DWORD dwCertEncodingType,
1021  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1022  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1023 {
1024     BOOL ret = FALSE;
1025 
1026     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1027      pDecodePara, pvStructInfo, *pcbStructInfo);
1028 
1029     __TRY
1030     {
1031         DWORD size = 0;
1032 
1033         /* Unless told not to, first try to decode it as a signed cert. */
1034         if (!(dwFlags & CRYPT_DECODE_TO_BE_SIGNED_FLAG))
1035         {
1036             PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
1037 
1038             ret = CRYPT_AsnDecodeCertSignedContent(dwCertEncodingType,
1039              X509_CERT, pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
1040              (BYTE *)&signedCert, &size);
1041             if (ret)
1042             {
1043                 size = 0;
1044                 ret = CRYPT_AsnDecodeCertInfo(dwCertEncodingType,
1045                  X509_CERT_TO_BE_SIGNED, signedCert->ToBeSigned.pbData,
1046                  signedCert->ToBeSigned.cbData, dwFlags, pDecodePara,
1047                  pvStructInfo, pcbStructInfo);
1048                 LocalFree(signedCert);
1049             }
1050         }
1051         /* Failing that, try it as an unsigned cert */
1052         if (!ret)
1053         {
1054             size = 0;
1055             ret = CRYPT_AsnDecodeCertInfo(dwCertEncodingType,
1056              X509_CERT_TO_BE_SIGNED, pbEncoded, cbEncoded, dwFlags,
1057              pDecodePara, pvStructInfo, pcbStructInfo);
1058         }
1059     }
1060     __EXCEPT_PAGE_FAULT
1061     {
1062         SetLastError(STATUS_ACCESS_VIOLATION);
1063     }
1064     __ENDTRY
1065 
1066     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1067     return ret;
1068 }
1069 
1070 static BOOL CRYPT_AsnDecodeCRLEntry(const BYTE *pbEncoded, DWORD cbEncoded,
1071  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1072 {
1073     BOOL ret;
1074     struct AsnDecodeSequenceItem items[] = {
1075      { ASN_INTEGER, offsetof(CRL_ENTRY, SerialNumber),
1076        CRYPT_AsnDecodeIntegerInternal, sizeof(CRYPT_INTEGER_BLOB), FALSE, TRUE,
1077        offsetof(CRL_ENTRY, SerialNumber.pbData), 0 },
1078      { 0, offsetof(CRL_ENTRY, RevocationDate),
1079        CRYPT_AsnDecodeChoiceOfTimeInternal, sizeof(FILETIME), FALSE, FALSE, 0 },
1080      { ASN_SEQUENCEOF, offsetof(CRL_ENTRY, cExtension),
1081        CRYPT_AsnDecodeExtensionsInternal, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
1082        offsetof(CRL_ENTRY, rgExtension), 0 },
1083     };
1084     PCRL_ENTRY entry = (PCRL_ENTRY)pvStructInfo;
1085 
1086     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags, entry,
1087      *pcbStructInfo);
1088 
1089     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
1090      pbEncoded, cbEncoded, dwFlags, NULL, entry, pcbStructInfo, pcbDecoded,
1091      entry ? entry->SerialNumber.pbData : NULL);
1092     if (ret && entry && !entry->SerialNumber.cbData)
1093     {
1094         WARN("empty CRL entry serial number\n");
1095         SetLastError(CRYPT_E_ASN1_CORRUPT);
1096         ret = FALSE;
1097     }
1098     return ret;
1099 }
1100 
1101 /* Warning: assumes pvStructInfo is a struct GenericArray whose rgItems has
1102  * been set prior to calling.
1103  */
1104 static BOOL CRYPT_AsnDecodeCRLEntries(const BYTE *pbEncoded, DWORD cbEncoded,
1105  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1106 {
1107     BOOL ret;
1108     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1109      CRYPT_AsnDecodeCRLEntry, sizeof(CRL_ENTRY), TRUE,
1110      offsetof(CRL_ENTRY, SerialNumber.pbData) };
1111     struct GenericArray *entries = (struct GenericArray *)pvStructInfo;
1112 
1113     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
1114      pvStructInfo, *pcbStructInfo, pcbDecoded);
1115 
1116     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1117      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
1118      entries ? entries->rgItems : NULL);
1119     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1120     return ret;
1121 }
1122 
1123 static BOOL WINAPI CRYPT_AsnDecodeCRLInfo(DWORD dwCertEncodingType,
1124  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1125  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1126 {
1127     struct AsnDecodeSequenceItem items[] = {
1128      { ASN_INTEGER, offsetof(CRL_INFO, dwVersion),
1129        CRYPT_AsnDecodeIntInternal, sizeof(DWORD), TRUE, FALSE, 0, 0 },
1130      { ASN_SEQUENCEOF, offsetof(CRL_INFO, SignatureAlgorithm),
1131        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
1132        FALSE, TRUE, offsetof(CRL_INFO, SignatureAlgorithm.pszObjId), 0 },
1133      { 0, offsetof(CRL_INFO, Issuer), CRYPT_AsnDecodeDerBlob,
1134        sizeof(CRYPT_DER_BLOB), FALSE, TRUE, offsetof(CRL_INFO,
1135        Issuer.pbData) },
1136      { 0, offsetof(CRL_INFO, ThisUpdate), CRYPT_AsnDecodeChoiceOfTimeInternal,
1137        sizeof(FILETIME), FALSE, FALSE, 0 },
1138      { 0, offsetof(CRL_INFO, NextUpdate), CRYPT_AsnDecodeChoiceOfTimeInternal,
1139        sizeof(FILETIME), TRUE, FALSE, 0 },
1140      { ASN_SEQUENCEOF, offsetof(CRL_INFO, cCRLEntry),
1141        CRYPT_AsnDecodeCRLEntries, sizeof(struct GenericArray), TRUE, TRUE,
1142        offsetof(CRL_INFO, rgCRLEntry), 0 },
1143      { ASN_CONTEXT | ASN_CONSTRUCTOR | 0, offsetof(CRL_INFO, cExtension),
1144        CRYPT_AsnDecodeCertExtensions, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
1145        offsetof(CRL_INFO, rgExtension), 0 },
1146     };
1147     BOOL ret = TRUE;
1148 
1149     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1150      pDecodePara, pvStructInfo, *pcbStructInfo);
1151 
1152     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
1153      pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo,
1154      NULL, NULL);
1155 
1156     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1157     return ret;
1158 }
1159 
1160 static BOOL WINAPI CRYPT_AsnDecodeCRL(DWORD dwCertEncodingType,
1161  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1162  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1163 {
1164     BOOL ret = FALSE;
1165 
1166     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1167      pDecodePara, pvStructInfo, *pcbStructInfo);
1168 
1169     __TRY
1170     {
1171         DWORD size = 0;
1172 
1173         /* Unless told not to, first try to decode it as a signed crl. */
1174         if (!(dwFlags & CRYPT_DECODE_TO_BE_SIGNED_FLAG))
1175         {
1176             PCERT_SIGNED_CONTENT_INFO signedCrl = NULL;
1177 
1178             ret = CRYPT_AsnDecodeCertSignedContent(dwCertEncodingType,
1179              X509_CERT, pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
1180              (BYTE *)&signedCrl, &size);
1181             if (ret)
1182             {
1183                 size = 0;
1184                 ret = CRYPT_AsnDecodeCRLInfo(dwCertEncodingType,
1185                  X509_CERT_CRL_TO_BE_SIGNED, signedCrl->ToBeSigned.pbData,
1186                  signedCrl->ToBeSigned.cbData, dwFlags, pDecodePara,
1187                  pvStructInfo, pcbStructInfo);
1188                 LocalFree(signedCrl);
1189             }
1190         }
1191         /* Failing that, try it as an unsigned crl */
1192         if (!ret)
1193         {
1194             size = 0;
1195             ret = CRYPT_AsnDecodeCRLInfo(dwCertEncodingType,
1196              X509_CERT_CRL_TO_BE_SIGNED, pbEncoded, cbEncoded,
1197              dwFlags, pDecodePara, pvStructInfo, pcbStructInfo);
1198         }
1199     }
1200     __EXCEPT_PAGE_FAULT
1201     {
1202         SetLastError(STATUS_ACCESS_VIOLATION);
1203     }
1204     __ENDTRY
1205 
1206     TRACE("Returning %d (%08x)\n", ret, GetLastError());
1207     return ret;
1208 }
1209 
1210 static BOOL CRYPT_AsnDecodeOidIgnoreTag(const BYTE *pbEncoded, DWORD cbEncoded,
1211  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1212 {
1213     BOOL ret = TRUE;
1214     DWORD dataLen;
1215 
1216     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1217      pvStructInfo, *pcbStructInfo);
1218 
1219     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
1220     {
1221         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1222         DWORD bytesNeeded = sizeof(LPSTR);
1223 
1224         if (dataLen)
1225         {
1226             /* The largest possible string for the first two components
1227              * is 2.175 (= 2 * 40 + 175 = 255), so this is big enough.
1228              */
1229             char firstTwo[6];
1230             const BYTE *ptr;
1231 
1232             snprintf(firstTwo, sizeof(firstTwo), "%d.%d",
1233              pbEncoded[1 + lenBytes] / 40,
1234              pbEncoded[1 + lenBytes] - (pbEncoded[1 + lenBytes] / 40)
1235              * 40);
1236             bytesNeeded += strlen(firstTwo) + 1;
1237             for (ptr = pbEncoded + 2 + lenBytes; ret &&
1238              ptr - pbEncoded - 1 - lenBytes < dataLen; )
1239             {
1240                 /* large enough for ".4000000" */
1241                 char str[9];
1242                 int val = 0;
1243 
1244                 while (ptr - pbEncoded - 1 - lenBytes < dataLen &&
1245                  (*ptr & 0x80))
1246                 {
1247                     val <<= 7;
1248                     val |= *ptr & 0x7f;
1249                     ptr++;
1250                 }
1251                 if (ptr - pbEncoded - 1 - lenBytes >= dataLen ||
1252                  (*ptr & 0x80))
1253                 {
1254                     SetLastError(CRYPT_E_ASN1_CORRUPT);
1255                     ret = FALSE;
1256                 }
1257                 else
1258                 {
1259                     val <<= 7;
1260                     val |= *ptr++;
1261                     snprintf(str, sizeof(str), ".%d", val);
1262                     bytesNeeded += strlen(str);
1263                 }
1264             }
1265         }
1266         if (pcbDecoded)
1267             *pcbDecoded = 1 + lenBytes + dataLen;
1268         if (!pvStructInfo)
1269             *pcbStructInfo = bytesNeeded;
1270         else if (*pcbStructInfo < bytesNeeded)
1271         {
1272             *pcbStructInfo = bytesNeeded;
1273             SetLastError(ERROR_MORE_DATA);
1274             ret = FALSE;
1275         }
1276         else
1277         {
1278             if (dataLen)
1279             {
1280                 const BYTE *ptr;
1281                 LPSTR pszObjId = *(LPSTR *)pvStructInfo;
1282 
1283                 *pszObjId = 0;
1284                 sprintf(pszObjId, "%d.%d", pbEncoded[1 + lenBytes] / 40,
1285                  pbEncoded[1 + lenBytes] - (pbEncoded[1 + lenBytes] /
1286                  40) * 40);
1287                 pszObjId += strlen(pszObjId);
1288                 for (ptr = pbEncoded + 2 + lenBytes; ret &&
1289                  ptr - pbEncoded - 1 - lenBytes < dataLen; )
1290                 {
1291                     int val = 0;
1292 
1293                     while (ptr - pbEncoded - 1 - lenBytes < dataLen &&
1294                      (*ptr & 0x80))
1295                     {
1296                         val <<= 7;
1297                         val |= *ptr & 0x7f;
1298                         ptr++;
1299                     }
1300                     val <<= 7;
1301                     val |= *ptr++;
1302                     sprintf(pszObjId, ".%d", val);
1303                     pszObjId += strlen(pszObjId);
1304                 }
1305             }
1306             else
1307                 *(LPSTR *)pvStructInfo = NULL;
1308             *pcbStructInfo = bytesNeeded;
1309         }
1310     }
1311     return ret;
1312 }
1313 
1314 static BOOL CRYPT_AsnDecodeOidInternal(const BYTE *pbEncoded, DWORD cbEncoded,
1315  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1316 {
1317     BOOL ret;
1318 
1319     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1320      pvStructInfo, *pcbStructInfo);
1321 
1322     if (pbEncoded[0] == ASN_OBJECTIDENTIFIER)
1323         ret = CRYPT_AsnDecodeOidIgnoreTag(pbEncoded, cbEncoded, dwFlags,
1324          pvStructInfo, pcbStructInfo, pcbDecoded);
1325     else
1326     {
1327         SetLastError(CRYPT_E_ASN1_BADTAG);
1328         ret = FALSE;
1329     }
1330     return ret;
1331 }
1332 
1333 /* Warning:  assumes pvStructInfo is a CERT_EXTENSION whose pszObjId is set
1334  * ahead of time!
1335  */
1336 static BOOL CRYPT_AsnDecodeExtension(const BYTE *pbEncoded, DWORD cbEncoded,
1337  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1338 {
1339     struct AsnDecodeSequenceItem items[] = {
1340      { ASN_OBJECTIDENTIFIER, offsetof(CERT_EXTENSION, pszObjId),
1341        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1342        offsetof(CERT_EXTENSION, pszObjId), 0 },
1343      { ASN_BOOL, offsetof(CERT_EXTENSION, fCritical), CRYPT_AsnDecodeBool,
1344        sizeof(BOOL), TRUE, FALSE, 0, 0 },
1345      { ASN_OCTETSTRING, offsetof(CERT_EXTENSION, Value),
1346        CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_OBJID_BLOB), FALSE, TRUE,
1347        offsetof(CERT_EXTENSION, Value.pbData) },
1348     };
1349     BOOL ret = TRUE;
1350     PCERT_EXTENSION ext = (PCERT_EXTENSION)pvStructInfo;
1351 
1352     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags, ext,
1353      *pcbStructInfo);
1354 
1355     if (ext)
1356         TRACE("ext->pszObjId is %p\n", ext->pszObjId);
1357     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
1358      pbEncoded, cbEncoded, dwFlags, NULL, ext, pcbStructInfo,
1359      pcbDecoded, ext ? ext->pszObjId : NULL);
1360     if (ext)
1361         TRACE("ext->pszObjId is %p (%s)\n", ext->pszObjId,
1362          debugstr_a(ext->pszObjId));
1363     TRACE("returning %d (%08x)\n", ret, GetLastError());
1364     return ret;
1365 }
1366 
1367 static BOOL CRYPT_AsnDecodeExtensionsInternal(const BYTE *pbEncoded,
1368  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
1369  DWORD *pcbDecoded)
1370 {
1371     BOOL ret = TRUE;
1372     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1373      CRYPT_AsnDecodeExtension, sizeof(CERT_EXTENSION), TRUE,
1374      offsetof(CERT_EXTENSION, pszObjId) };
1375     PCERT_EXTENSIONS exts = (PCERT_EXTENSIONS)pvStructInfo;
1376 
1377     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
1378      pvStructInfo, *pcbStructInfo, pcbDecoded);
1379 
1380     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1381      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
1382      exts ? exts->rgExtension : NULL);
1383     return ret;
1384 }
1385 
1386 static BOOL WINAPI CRYPT_AsnDecodeExtensions(DWORD dwCertEncodingType,
1387  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1388  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1389 {
1390     BOOL ret = TRUE;
1391 
1392     __TRY
1393     {
1394         ret = CRYPT_AsnDecodeExtensionsInternal(pbEncoded, cbEncoded,
1395          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pcbStructInfo, NULL);
1396         if (ret && pvStructInfo)
1397         {
1398             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1399              pcbStructInfo, *pcbStructInfo);
1400             if (ret)
1401             {
1402                 CERT_EXTENSIONS *exts;
1403 
1404                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1405                     pvStructInfo = *(BYTE **)pvStructInfo;
1406                 exts = (CERT_EXTENSIONS *)pvStructInfo;
1407                 exts->rgExtension = (CERT_EXTENSION *)((BYTE *)exts +
1408                  sizeof(CERT_EXTENSIONS));
1409                 ret = CRYPT_AsnDecodeExtensionsInternal(pbEncoded, cbEncoded,
1410                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
1411                  pcbStructInfo, NULL);
1412             }
1413         }
1414     }
1415     __EXCEPT_PAGE_FAULT
1416     {
1417         SetLastError(STATUS_ACCESS_VIOLATION);
1418         ret = FALSE;
1419     }
1420     __ENDTRY
1421     return ret;
1422 }
1423 
1424 /* Warning: this assumes the address of value->Value.pbData is already set, in
1425  * order to avoid overwriting memory.  (In some cases, it may change it, if it
1426  * doesn't copy anything to memory.)  Be sure to set it correctly!
1427  */
1428 static BOOL CRYPT_AsnDecodeNameValueInternal(const BYTE *pbEncoded,
1429  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
1430  DWORD *pcbDecoded)
1431 {
1432     BOOL ret = TRUE;
1433     DWORD dataLen;
1434     CERT_NAME_VALUE *value = (CERT_NAME_VALUE *)pvStructInfo;
1435 
1436     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
1437     {
1438         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1439         DWORD bytesNeeded = sizeof(CERT_NAME_VALUE), valueType;
1440 
1441         switch (pbEncoded[0])
1442         {
1443         case ASN_OCTETSTRING:
1444             valueType = CERT_RDN_OCTET_STRING;
1445             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1446                 bytesNeeded += dataLen;
1447             break;
1448         case ASN_NUMERICSTRING:
1449             valueType = CERT_RDN_NUMERIC_STRING;
1450             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1451                 bytesNeeded += dataLen;
1452             break;
1453         case ASN_PRINTABLESTRING:
1454             valueType = CERT_RDN_PRINTABLE_STRING;
1455             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1456                 bytesNeeded += dataLen;
1457             break;
1458         case ASN_IA5STRING:
1459             valueType = CERT_RDN_IA5_STRING;
1460             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1461                 bytesNeeded += dataLen;
1462             break;
1463         case ASN_T61STRING:
1464             valueType = CERT_RDN_T61_STRING;
1465             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1466                 bytesNeeded += dataLen;
1467             break;
1468         case ASN_VIDEOTEXSTRING:
1469             valueType = CERT_RDN_VIDEOTEX_STRING;
1470             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1471                 bytesNeeded += dataLen;
1472             break;
1473         case ASN_GRAPHICSTRING:
1474             valueType = CERT_RDN_GRAPHIC_STRING;
1475             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1476                 bytesNeeded += dataLen;
1477             break;
1478         case ASN_VISIBLESTRING:
1479             valueType = CERT_RDN_VISIBLE_STRING;
1480             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1481                 bytesNeeded += dataLen;
1482             break;
1483         case ASN_GENERALSTRING:
1484             valueType = CERT_RDN_GENERAL_STRING;
1485             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1486                 bytesNeeded += dataLen;
1487             break;
1488         case ASN_UNIVERSALSTRING:
1489             FIXME("ASN_UNIVERSALSTRING: unimplemented\n");
1490             SetLastError(CRYPT_E_ASN1_BADTAG);
1491             return FALSE;
1492         case ASN_BMPSTRING:
1493             valueType = CERT_RDN_BMP_STRING;
1494             bytesNeeded += dataLen;
1495             break;
1496         case ASN_UTF8STRING:
1497             valueType = CERT_RDN_UTF8_STRING;
1498             bytesNeeded += MultiByteToWideChar(CP_UTF8, 0,
1499              (LPCSTR)pbEncoded + 1 + lenBytes, dataLen, NULL, 0) * 2;
1500             break;
1501         default:
1502             SetLastError(CRYPT_E_ASN1_BADTAG);
1503             return FALSE;
1504         }
1505 
1506         if (pcbDecoded)
1507             *pcbDecoded = 1 + lenBytes + dataLen;
1508         if (!value)
1509             *pcbStructInfo = bytesNeeded;
1510         else if (*pcbStructInfo < bytesNeeded)
1511         {
1512             *pcbStructInfo = bytesNeeded;
1513             SetLastError(ERROR_MORE_DATA);
1514             ret = FALSE;
1515         }
1516         else
1517         {
1518             *pcbStructInfo = bytesNeeded;
1519             value->dwValueType = valueType;
1520             if (dataLen)
1521             {
1522                 DWORD i;
1523 
1524                 assert(value->Value.pbData);
1525                 switch (pbEncoded[0])
1526                 {
1527                 case ASN_OCTETSTRING:
1528                 case ASN_NUMERICSTRING:
1529                 case ASN_PRINTABLESTRING:
1530                 case ASN_IA5STRING:
1531                 case ASN_T61STRING:
1532                 case ASN_VIDEOTEXSTRING:
1533                 case ASN_GRAPHICSTRING:
1534                 case ASN_VISIBLESTRING:
1535                 case ASN_GENERALSTRING:
1536                     value->Value.cbData = dataLen;
1537                     if (dataLen)
1538                     {
1539                         if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1540                             memcpy(value->Value.pbData,
1541                              pbEncoded + 1 + lenBytes, dataLen);
1542                         else
1543                             value->Value.pbData = (LPBYTE)pbEncoded + 1 +
1544                              lenBytes;
1545                     }
1546                     break;
1547                 case ASN_BMPSTRING:
1548                 {
1549                     LPWSTR str = (LPWSTR)value->Value.pbData;
1550 
1551                     value->Value.cbData = dataLen;
1552                     for (i = 0; i < dataLen / 2; i++)
1553                         str[i] = (pbEncoded[1 + lenBytes + 2 * i] << 8) |
1554                          pbEncoded[1 + lenBytes + 2 * i + 1];
1555                     break;
1556                 }
1557                 case ASN_UTF8STRING:
1558                 {
1559                     LPWSTR str = (LPWSTR)value->Value.pbData;
1560 
1561                     value->Value.cbData = MultiByteToWideChar(CP_UTF8, 0,
1562                      (LPCSTR)pbEncoded + 1 + lenBytes, dataLen, 
1563                      str, bytesNeeded - sizeof(CERT_NAME_VALUE)) * 2;
1564                     break;
1565                 }
1566                 }
1567             }
1568             else
1569             {
1570                 value->Value.cbData = 0;
1571                 value->Value.pbData = NULL;
1572             }
1573         }
1574     }
1575     return ret;
1576 }
1577 
1578 static BOOL WINAPI CRYPT_AsnDecodeNameValue(DWORD dwCertEncodingType,
1579  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1580  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1581 {
1582     BOOL ret = TRUE;
1583 
1584     __TRY
1585     {
1586         ret = CRYPT_AsnDecodeNameValueInternal(pbEncoded, cbEncoded,
1587          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pcbStructInfo, NULL);
1588         if (ret && pvStructInfo)
1589         {
1590             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1591              pcbStructInfo, *pcbStructInfo);
1592             if (ret)
1593             {
1594                 CERT_NAME_VALUE *value;
1595 
1596                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1597                     pvStructInfo = *(BYTE **)pvStructInfo;
1598                 value = (CERT_NAME_VALUE *)pvStructInfo;
1599                 value->Value.pbData = ((BYTE *)value + sizeof(CERT_NAME_VALUE));
1600                 ret = CRYPT_AsnDecodeNameValueInternal( pbEncoded, cbEncoded,
1601                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
1602                  pcbStructInfo, NULL);
1603             }
1604         }
1605     }
1606     __EXCEPT_PAGE_FAULT
1607     {
1608         SetLastError(STATUS_ACCESS_VIOLATION);
1609         ret = FALSE;
1610     }
1611     __ENDTRY
1612     return ret;
1613 }
1614 
1615 static BOOL CRYPT_AsnDecodeUnicodeNameValueInternal(const BYTE *pbEncoded,
1616  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
1617  DWORD *pcbDecoded)
1618 {
1619     BOOL ret = TRUE;
1620     DWORD dataLen;
1621     CERT_NAME_VALUE *value = (CERT_NAME_VALUE *)pvStructInfo;
1622 
1623     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
1624     {
1625         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1626         DWORD bytesNeeded = sizeof(CERT_NAME_VALUE), valueType;
1627 
1628         switch (pbEncoded[0])
1629         {
1630         case ASN_NUMERICSTRING:
1631             valueType = CERT_RDN_NUMERIC_STRING;
1632             if (dataLen)
1633                 bytesNeeded += (dataLen + 1) * 2;
1634             break;
1635         case ASN_PRINTABLESTRING:
1636             valueType = CERT_RDN_PRINTABLE_STRING;
1637             if (dataLen)
1638                 bytesNeeded += (dataLen + 1) * 2;
1639             break;
1640         case ASN_IA5STRING:
1641             valueType = CERT_RDN_IA5_STRING;
1642             if (dataLen)
1643                 bytesNeeded += (dataLen + 1) * 2;
1644             break;
1645         case ASN_T61STRING:
1646             valueType = CERT_RDN_T61_STRING;
1647             if (dataLen)
1648                 bytesNeeded += (dataLen + 1) * 2;
1649             break;
1650         case ASN_VIDEOTEXSTRING:
1651             valueType = CERT_RDN_VIDEOTEX_STRING;
1652             if (dataLen)
1653                 bytesNeeded += (dataLen + 1) * 2;
1654             break;
1655         case ASN_GRAPHICSTRING:
1656             valueType = CERT_RDN_GRAPHIC_STRING;
1657             if (dataLen)
1658                 bytesNeeded += (dataLen + 1) * 2;
1659             break;
1660         case ASN_VISIBLESTRING:
1661             valueType = CERT_RDN_VISIBLE_STRING;
1662             if (dataLen)
1663                 bytesNeeded += (dataLen + 1) * 2;
1664             break;
1665         case ASN_GENERALSTRING:
1666             valueType = CERT_RDN_GENERAL_STRING;
1667             if (dataLen)
1668                 bytesNeeded += (dataLen + 1) * 2;
1669             break;
1670         case ASN_UNIVERSALSTRING:
1671             valueType = CERT_RDN_UNIVERSAL_STRING;
1672             if (dataLen)
1673                 bytesNeeded += dataLen / 2 + sizeof(WCHAR);
1674             break;
1675         case ASN_BMPSTRING:
1676             valueType = CERT_RDN_BMP_STRING;
1677             if (dataLen)
1678                 bytesNeeded += dataLen + sizeof(WCHAR);
1679             break;
1680         case ASN_UTF8STRING:
1681             valueType = CERT_RDN_UTF8_STRING;
1682             if (dataLen)
1683                 bytesNeeded += (MultiByteToWideChar(CP_UTF8, 0,
1684                  (LPCSTR)pbEncoded + 1 + lenBytes, dataLen, NULL, 0) + 1) * 2;
1685             break;
1686         default:
1687             SetLastError(CRYPT_E_ASN1_BADTAG);
1688             return FALSE;
1689         }
1690 
1691         if (pcbDecoded)
1692             *pcbDecoded = 1 + lenBytes + dataLen;
1693         if (!value)
1694             *pcbStructInfo = bytesNeeded;
1695         else if (*pcbStructInfo < bytesNeeded)
1696         {
1697             *pcbStructInfo = bytesNeeded;
1698             SetLastError(ERROR_MORE_DATA);
1699             ret = FALSE;
1700         }
1701         else
1702         {
1703             *pcbStructInfo = bytesNeeded;
1704             value->dwValueType = valueType;
1705             if (dataLen)
1706             {
1707                 DWORD i;
1708                 LPWSTR str = (LPWSTR)value->Value.pbData;
1709 
1710                 assert(value->Value.pbData);
1711                 switch (pbEncoded[0])
1712                 {
1713                 case ASN_NUMERICSTRING:
1714                 case ASN_PRINTABLESTRING:
1715                 case ASN_IA5STRING:
1716                 case ASN_T61STRING:
1717                 case ASN_VIDEOTEXSTRING:
1718                 case ASN_GRAPHICSTRING:
1719                 case ASN_VISIBLESTRING:
1720                 case ASN_GENERALSTRING:
1721                     value->Value.cbData = dataLen * 2;
1722                     for (i = 0; i < dataLen; i++)
1723                         str[i] = pbEncoded[1 + lenBytes + i];
1724                     str[i] = 0;
1725                     break;
1726                 case ASN_UNIVERSALSTRING:
1727                     value->Value.cbData = dataLen / 2;
1728                     for (i = 0; i < dataLen / 4; i++)
1729                         str[i] = (pbEncoded[1 + lenBytes + 2 * i + 2] << 8)
1730                          | pbEncoded[1 + lenBytes + 2 * i + 3];
1731                     str[i] = 0;
1732                     break;
1733                 case ASN_BMPSTRING:
1734                     value->Value.cbData = dataLen;
1735                     for (i = 0; i < dataLen / 2; i++)
1736                         str[i] = (pbEncoded[1 + lenBytes + 2 * i] << 8) |
1737                          pbEncoded[1 + lenBytes + 2 * i + 1];
1738                     str[i] = 0;
1739                     break;
1740                 case ASN_UTF8STRING:
1741                     value->Value.cbData = MultiByteToWideChar(CP_UTF8, 0,
1742                      (LPCSTR)pbEncoded + 1 + lenBytes, dataLen,
1743                      str, bytesNeeded - sizeof(CERT_NAME_VALUE)) * 2;
1744                     value->Value.pbData[value->Value.cbData / sizeof(WCHAR)]
1745                      = 0;
1746                     value->Value.cbData += sizeof(WCHAR);
1747                     break;
1748                 }
1749             }
1750             else
1751             {
1752                 value->Value.cbData = 0;
1753                 value->Value.pbData = NULL;
1754             }
1755         }
1756     }
1757     return ret;
1758 }
1759 
1760 static BOOL WINAPI CRYPT_AsnDecodeUnicodeNameValue(DWORD dwCertEncodingType,
1761  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1762  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1763 {
1764     BOOL ret = TRUE;
1765 
1766     __TRY
1767     {
1768         ret = CRYPT_AsnDecodeUnicodeNameValueInternal(pbEncoded, cbEncoded,
1769          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pcbStructInfo, NULL);
1770         if (ret && pvStructInfo)
1771         {
1772             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1773              pcbStructInfo, *pcbStructInfo);
1774             if (ret)
1775             {
1776                 CERT_NAME_VALUE *value;
1777 
1778                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1779                     pvStructInfo = *(BYTE **)pvStructInfo;
1780                 value = (CERT_NAME_VALUE *)pvStructInfo;
1781                 value->Value.pbData = ((BYTE *)value + sizeof(CERT_NAME_VALUE));
1782                 ret = CRYPT_AsnDecodeUnicodeNameValueInternal(pbEncoded,
1783                  cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
1784                  pcbStructInfo, NULL);
1785             }
1786         }
1787     }
1788     __EXCEPT_PAGE_FAULT
1789     {
1790         SetLastError(STATUS_ACCESS_VIOLATION);
1791         ret = FALSE;
1792     }
1793     __ENDTRY
1794     return ret;
1795 }
1796 
1797 static BOOL CRYPT_AsnDecodeRdnAttr(const BYTE *pbEncoded, DWORD cbEncoded,
1798  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1799 {
1800     BOOL ret;
1801     struct AsnDecodeSequenceItem items[] = {
1802      { ASN_OBJECTIDENTIFIER, offsetof(CERT_RDN_ATTR, pszObjId),
1803        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1804        offsetof(CERT_RDN_ATTR, pszObjId), 0 },
1805      { 0, offsetof(CERT_RDN_ATTR, dwValueType),
1806        CRYPT_AsnDecodeNameValueInternal, sizeof(CERT_NAME_VALUE),
1807        FALSE, TRUE, offsetof(CERT_RDN_ATTR, Value.pbData), 0 },
1808     };
1809     CERT_RDN_ATTR *attr = (CERT_RDN_ATTR *)pvStructInfo;
1810 
1811     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1812      pvStructInfo, *pcbStructInfo);
1813 
1814     if (attr)
1815         TRACE("attr->pszObjId is %p\n", attr->pszObjId);
1816     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
1817      pbEncoded, cbEncoded, dwFlags, NULL, attr, pcbStructInfo, pcbDecoded,
1818      attr ? attr->pszObjId : NULL);
1819     if (attr)
1820     {
1821         TRACE("attr->pszObjId is %p (%s)\n", attr->pszObjId,
1822          debugstr_a(attr->pszObjId));
1823         TRACE("attr->dwValueType is %d\n", attr->dwValueType);
1824     }
1825     TRACE("returning %d (%08x)\n", ret, GetLastError());
1826     return ret;
1827 }
1828 
1829 static BOOL CRYPT_AsnDecodeRdn(const BYTE *pbEncoded, DWORD cbEncoded,
1830  DWORD dwFlags,  void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1831 {
1832     BOOL ret = TRUE;
1833     struct AsnArrayDescriptor arrayDesc = { ASN_CONSTRUCTOR | ASN_SETOF,
1834      CRYPT_AsnDecodeRdnAttr, sizeof(CERT_RDN_ATTR), TRUE,
1835      offsetof(CERT_RDN_ATTR, pszObjId) };
1836     PCERT_RDN rdn = (PCERT_RDN)pvStructInfo;
1837 
1838     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1839      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
1840      rdn ? rdn->rgRDNAttr : NULL);
1841     return ret;
1842 }
1843 
1844 static BOOL WINAPI CRYPT_AsnDecodeName(DWORD dwCertEncodingType,
1845  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1846  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1847 {
1848     BOOL ret = TRUE;
1849 
1850     __TRY
1851     {
1852         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1853          CRYPT_AsnDecodeRdn, sizeof(CERT_RDN), TRUE,
1854          offsetof(CERT_RDN, rgRDNAttr) };
1855 
1856         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1857          pDecodePara, pvStructInfo, pcbStructInfo, NULL, NULL);
1858     }
1859     __EXCEPT_PAGE_FAULT
1860     {
1861         SetLastError(STATUS_ACCESS_VIOLATION);
1862         ret = FALSE;
1863     }
1864     __ENDTRY
1865     return ret;
1866 }
1867 
1868 static BOOL CRYPT_AsnDecodeUnicodeRdnAttr(const BYTE *pbEncoded,
1869  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
1870  DWORD *pcbDecoded)
1871 {
1872     BOOL ret;
1873     struct AsnDecodeSequenceItem items[] = {
1874      { ASN_OBJECTIDENTIFIER, offsetof(CERT_RDN_ATTR, pszObjId),
1875        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
1876        offsetof(CERT_RDN_ATTR, pszObjId), 0 },
1877      { 0, offsetof(CERT_RDN_ATTR, dwValueType),
1878        CRYPT_AsnDecodeUnicodeNameValueInternal, sizeof(CERT_NAME_VALUE),
1879        FALSE, TRUE, offsetof(CERT_RDN_ATTR, Value.pbData), 0 },
1880     };
1881     CERT_RDN_ATTR *attr = (CERT_RDN_ATTR *)pvStructInfo;
1882 
1883     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
1884      pvStructInfo, *pcbStructInfo);
1885 
1886     if (attr)
1887         TRACE("attr->pszObjId is %p\n", attr->pszObjId);
1888     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
1889      pbEncoded, cbEncoded, dwFlags, NULL, attr, pcbStructInfo, pcbDecoded,
1890      attr ? attr->pszObjId : NULL);
1891     if (attr)
1892     {
1893         TRACE("attr->pszObjId is %p (%s)\n", attr->pszObjId,
1894          debugstr_a(attr->pszObjId));
1895         TRACE("attr->dwValueType is %d\n", attr->dwValueType);
1896     }
1897     TRACE("returning %d (%08x)\n", ret, GetLastError());
1898     return ret;
1899 }
1900 
1901 static BOOL CRYPT_AsnDecodeUnicodeRdn(const BYTE *pbEncoded, DWORD cbEncoded,
1902  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
1903 {
1904     BOOL ret = TRUE;
1905     struct AsnArrayDescriptor arrayDesc = { ASN_CONSTRUCTOR | ASN_SETOF,
1906      CRYPT_AsnDecodeUnicodeRdnAttr, sizeof(CERT_RDN_ATTR), TRUE,
1907      offsetof(CERT_RDN_ATTR, pszObjId) };
1908     PCERT_RDN rdn = (PCERT_RDN)pvStructInfo;
1909 
1910     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1911      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
1912      rdn ? rdn->rgRDNAttr : NULL);
1913     return ret;
1914 }
1915 
1916 static BOOL WINAPI CRYPT_AsnDecodeUnicodeName(DWORD dwCertEncodingType,
1917  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1918  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1919 {
1920     BOOL ret = TRUE;
1921 
1922     __TRY
1923     {
1924         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
1925          CRYPT_AsnDecodeUnicodeRdn, sizeof(CERT_RDN), TRUE,
1926          offsetof(CERT_RDN, rgRDNAttr) };
1927 
1928         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
1929          pDecodePara, pvStructInfo, pcbStructInfo, NULL, NULL);
1930     }
1931     __EXCEPT_PAGE_FAULT
1932     {
1933         SetLastError(STATUS_ACCESS_VIOLATION);
1934         ret = FALSE;
1935     }
1936     __ENDTRY
1937     return ret;
1938 }
1939 
1940 static BOOL CRYPT_FindEncodedLen(const BYTE *pbEncoded, DWORD cbEncoded,
1941  DWORD *pcbDecoded)
1942 {
1943     BOOL ret = TRUE, done = FALSE;
1944     DWORD indefiniteNestingLevels = 0, decoded = 0;
1945 
1946     TRACE("(%p, %d)\n", pbEncoded, cbEncoded);
1947 
1948     do {
1949         DWORD dataLen;
1950 
1951         if (!cbEncoded)
1952             done = TRUE;
1953         else if ((ret = CRYPT_GetLengthIndefinite(pbEncoded, cbEncoded,
1954          &dataLen)))
1955         {
1956             BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1957 
1958             if (dataLen == CMSG_INDEFINITE_LENGTH)
1959             {
1960                 indefiniteNestingLevels++;
1961                 pbEncoded += 1 + lenBytes;
1962                 cbEncoded -= 1 + lenBytes;
1963                 decoded += 1 + lenBytes;
1964                 TRACE("indefiniteNestingLevels = %d\n",
1965                  indefiniteNestingLevels);
1966             }
1967             else
1968             {
1969                 if (pbEncoded[0] == 0 && pbEncoded[1] == 0 &&
1970                  indefiniteNestingLevels)
1971                 {
1972                     indefiniteNestingLevels--;
1973                     TRACE("indefiniteNestingLevels = %d\n",
1974                      indefiniteNestingLevels);
1975                 }
1976                 pbEncoded += 1 + lenBytes + dataLen;
1977                 cbEncoded -= 1 + lenBytes + dataLen;
1978                 decoded += 1 + lenBytes + dataLen;
1979                 if (!indefiniteNestingLevels)
1980                     done = TRUE;
1981             }
1982         }
1983     } while (ret && !done);
1984     /* If we haven't found all 0 TLVs, we haven't found the end */
1985     if (ret && indefiniteNestingLevels)
1986     {
1987         SetLastError(CRYPT_E_ASN1_EOD);
1988         ret = FALSE;
1989     }
1990     if (ret)
1991         *pcbDecoded = decoded;
1992     TRACE("returning %d (%d)\n", ret, ret ? *pcbDecoded : 0);
1993     return ret;
1994 }
1995 
1996 static BOOL CRYPT_AsnDecodeCopyBytes(const BYTE *pbEncoded,
1997  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
1998  DWORD *pcbDecoded)
1999 {
2000     BOOL ret = TRUE;
2001     DWORD bytesNeeded = sizeof(CRYPT_OBJID_BLOB), encodedLen = 0;
2002 
2003     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2004      pvStructInfo, *pcbStructInfo);
2005 
2006     if ((ret = CRYPT_FindEncodedLen(pbEncoded, cbEncoded, &encodedLen)))
2007     {
2008         if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
2009             bytesNeeded += encodedLen;
2010         if (!pvStructInfo)
2011             *pcbStructInfo = bytesNeeded;
2012         else if (*pcbStructInfo < bytesNeeded)
2013         {
2014             SetLastError(ERROR_MORE_DATA);
2015             *pcbStructInfo = bytesNeeded;
2016             ret = FALSE;
2017         }
2018         else
2019         {
2020             PCRYPT_OBJID_BLOB blob = (PCRYPT_OBJID_BLOB)pvStructInfo;
2021 
2022             *pcbStructInfo = bytesNeeded;
2023             blob->cbData = encodedLen;
2024             if (encodedLen)
2025             {
2026                 if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
2027                     blob->pbData = (LPBYTE)pbEncoded;
2028                 else
2029                 {
2030                     assert(blob->pbData);
2031                     memcpy(blob->pbData, pbEncoded, blob->cbData);
2032                 }
2033             }
2034             else
2035                 blob->pbData = NULL;
2036         }
2037         if (pcbDecoded)
2038             *pcbDecoded = encodedLen;
2039     }
2040     return ret;
2041 }
2042 
2043 static BOOL CRYPT_DecodeDERArray(const BYTE *pbEncoded, DWORD cbEncoded,
2044  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2045 {
2046     BOOL ret;
2047     struct AsnArrayDescriptor arrayDesc = { 0, CRYPT_AsnDecodeCopyBytes,
2048      sizeof(CRYPT_DER_BLOB), TRUE, offsetof(CRYPT_DER_BLOB, pbData) };
2049     struct GenericArray *array = (struct GenericArray *)pvStructInfo;
2050 
2051     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
2052      pvStructInfo, *pcbStructInfo, pcbDecoded);
2053 
2054     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2055      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
2056      array ? array->rgItems : NULL);
2057     return ret;
2058 }
2059 
2060 static BOOL CRYPT_AsnDecodeCTLUsage(const BYTE *pbEncoded, DWORD cbEncoded,
2061  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2062 {
2063     BOOL ret;
2064     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
2065      CRYPT_AsnDecodeOidInternal, sizeof(LPSTR), TRUE, 0 };
2066     CTL_USAGE *usage = (CTL_USAGE *)pvStructInfo;
2067 
2068     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2069      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
2070      usage ? usage->rgpszUsageIdentifier : NULL);
2071     return ret;
2072 }
2073 
2074 static BOOL CRYPT_AsnDecodeCTLEntry(const BYTE *pbEncoded, DWORD cbEncoded,
2075  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2076 {
2077     struct AsnDecodeSequenceItem items[] = {
2078      { ASN_OCTETSTRING, offsetof(CTL_ENTRY, SubjectIdentifier),
2079        CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_DATA_BLOB), FALSE, TRUE,
2080        offsetof(CTL_ENTRY, SubjectIdentifier.pbData), 0 },
2081      { ASN_CONSTRUCTOR | ASN_SETOF, offsetof(CTL_ENTRY, cAttribute),
2082        CRYPT_AsnDecodePKCSAttributesInternal, sizeof(CRYPT_ATTRIBUTES), FALSE,
2083        TRUE, offsetof(CTL_ENTRY, rgAttribute), 0 },
2084     };
2085     BOOL ret = TRUE;
2086     CTL_ENTRY *entry = (CTL_ENTRY *)pvStructInfo;
2087 
2088     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags, entry,
2089      *pcbStructInfo);
2090 
2091     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2092      pbEncoded, cbEncoded, dwFlags, NULL, entry, pcbStructInfo,
2093      pcbDecoded, entry ? entry->SubjectIdentifier.pbData : NULL);
2094     return ret;
2095 }
2096 
2097 static BOOL CRYPT_AsnDecodeCTLEntries(const BYTE *pbEncoded, DWORD cbEncoded,
2098  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2099 {
2100     BOOL ret;
2101     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
2102      CRYPT_AsnDecodeCTLEntry, sizeof(CTL_ENTRY), TRUE,
2103      offsetof(CTL_ENTRY, SubjectIdentifier.pbData) };
2104     struct GenericArray *entries = (struct GenericArray *)pvStructInfo;
2105 
2106     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
2107      pvStructInfo, *pcbStructInfo, pcbDecoded);
2108 
2109     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2110      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
2111      entries ? entries->rgItems : NULL);
2112     return ret;
2113 }
2114 
2115 static BOOL WINAPI CRYPT_AsnDecodeCTL(DWORD dwCertEncodingType,
2116  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2117  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2118 {
2119     BOOL ret = FALSE;
2120 
2121     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2122      pDecodePara, pvStructInfo, *pcbStructInfo);
2123 
2124     __TRY
2125     {
2126         struct AsnDecodeSequenceItem items[] = {
2127          { ASN_INTEGER, offsetof(CTL_INFO, dwVersion),
2128            CRYPT_AsnDecodeIntInternal, sizeof(DWORD), TRUE, FALSE, 0, 0 },
2129          { ASN_SEQUENCEOF, offsetof(CTL_INFO, SubjectUsage),
2130            CRYPT_AsnDecodeCTLUsage, sizeof(CTL_USAGE), FALSE, TRUE,
2131            offsetof(CTL_INFO, SubjectUsage.rgpszUsageIdentifier), 0 },
2132          { ASN_OCTETSTRING, offsetof(CTL_INFO, ListIdentifier),
2133            CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_DATA_BLOB), TRUE,
2134            TRUE, offsetof(CTL_INFO, ListIdentifier.pbData), 0 },
2135          { ASN_INTEGER, offsetof(CTL_INFO, SequenceNumber),
2136            CRYPT_AsnDecodeIntegerInternal, sizeof(CRYPT_INTEGER_BLOB),
2137            TRUE, TRUE, offsetof(CTL_INFO, SequenceNumber.pbData), 0 },
2138          { 0, offsetof(CTL_INFO, ThisUpdate),
2139            CRYPT_AsnDecodeChoiceOfTimeInternal, sizeof(FILETIME), FALSE, FALSE,
2140            0 },
2141          { 0, offsetof(CTL_INFO, NextUpdate),
2142            CRYPT_AsnDecodeChoiceOfTimeInternal, sizeof(FILETIME), TRUE, FALSE,
2143            0 },
2144          { ASN_SEQUENCEOF, offsetof(CTL_INFO, SubjectAlgorithm),
2145            CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
2146            FALSE, TRUE, offsetof(CTL_INFO, SubjectAlgorithm.pszObjId), 0 },
2147          { ASN_SEQUENCEOF, offsetof(CTL_INFO, cCTLEntry),
2148            CRYPT_AsnDecodeCTLEntries, sizeof(struct GenericArray),
2149            TRUE, TRUE, offsetof(CTL_INFO, rgCTLEntry), 0 },
2150          { ASN_CONTEXT | ASN_CONSTRUCTOR | 0, offsetof(CTL_INFO, cExtension),
2151            CRYPT_AsnDecodeCertExtensions, sizeof(CERT_EXTENSIONS), TRUE, TRUE,
2152            offsetof(CTL_INFO, rgExtension), 0 },
2153         };
2154 
2155         TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2156          pDecodePara, pvStructInfo, *pcbStructInfo);
2157 
2158         ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2159          pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
2160          pcbStructInfo, NULL, NULL);
2161     }
2162     __EXCEPT_PAGE_FAULT
2163     {
2164         SetLastError(STATUS_ACCESS_VIOLATION);
2165     }
2166     __ENDTRY
2167     return ret;
2168 }
2169 
2170 static BOOL CRYPT_AsnDecodeSMIMECapability(const BYTE *pbEncoded,
2171  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2172  DWORD *pcbDecoded)
2173 {
2174     BOOL ret;
2175     struct AsnDecodeSequenceItem items[] = {
2176      { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_SMIME_CAPABILITY, pszObjId),
2177        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
2178        offsetof(CRYPT_SMIME_CAPABILITY, pszObjId), 0 },
2179      { 0, offsetof(CRYPT_SMIME_CAPABILITY, Parameters),
2180        CRYPT_AsnDecodeCopyBytes, sizeof(CRYPT_OBJID_BLOB), TRUE, TRUE,
2181        offsetof(CRYPT_SMIME_CAPABILITY, Parameters.pbData), 0 },
2182     };
2183     PCRYPT_SMIME_CAPABILITY capability = (PCRYPT_SMIME_CAPABILITY)pvStructInfo;
2184 
2185     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2186      pvStructInfo, *pcbStructInfo);
2187 
2188     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2189      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
2190      pcbDecoded, capability ? capability->pszObjId : NULL);
2191     TRACE("returning %d\n", ret);
2192     return ret;
2193 }
2194 
2195 static BOOL CRYPT_AsnDecodeSMIMECapabilitiesInternal(const BYTE *pbEncoded,
2196  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2197  DWORD *pcbDecoded)
2198 {
2199     struct AsnArrayDescriptor arrayDesc = { 0,
2200      CRYPT_AsnDecodeSMIMECapability, sizeof(CRYPT_SMIME_CAPABILITY), TRUE,
2201      offsetof(CRYPT_SMIME_CAPABILITY, pszObjId) };
2202     PCRYPT_SMIME_CAPABILITIES capabilities =
2203      (PCRYPT_SMIME_CAPABILITIES)pvStructInfo;
2204     BOOL ret;
2205 
2206     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2207      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
2208      capabilities ? capabilities->rgCapability : NULL);
2209     return ret;
2210 }
2211 
2212 static BOOL WINAPI CRYPT_AsnDecodeSMIMECapabilities(DWORD dwCertEncodingType,
2213  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2214  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2215 {
2216     BOOL ret = FALSE;
2217 
2218     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2219      pDecodePara, pvStructInfo, *pcbStructInfo);
2220 
2221     __TRY
2222     {
2223         DWORD bytesNeeded;
2224 
2225         if (!cbEncoded)
2226             SetLastError(CRYPT_E_ASN1_EOD);
2227         else if (pbEncoded[0] != ASN_SEQUENCEOF)
2228             SetLastError(CRYPT_E_ASN1_CORRUPT);
2229         else if ((ret = CRYPT_AsnDecodeSMIMECapabilitiesInternal(pbEncoded,
2230          cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &bytesNeeded,
2231          NULL)))
2232         {
2233             if (!pvStructInfo)
2234                 *pcbStructInfo = bytesNeeded;
2235             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2236              pvStructInfo, pcbStructInfo, bytesNeeded)))
2237             {
2238                 PCRYPT_SMIME_CAPABILITIES capabilities;
2239 
2240                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2241                     pvStructInfo = *(BYTE **)pvStructInfo;
2242                 capabilities = (PCRYPT_SMIME_CAPABILITIES)pvStructInfo;
2243                 capabilities->rgCapability =
2244                  (PCRYPT_SMIME_CAPABILITY)((BYTE *)pvStructInfo +
2245                  sizeof(CRYPT_SMIME_CAPABILITIES));
2246                 ret = CRYPT_AsnDecodeSMIMECapabilitiesInternal(pbEncoded,
2247                  cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
2248                  &bytesNeeded, NULL);
2249             }
2250         }
2251     }
2252     __EXCEPT_PAGE_FAULT
2253     {
2254         SetLastError(STATUS_ACCESS_VIOLATION);
2255     }
2256     __ENDTRY
2257     TRACE("returning %d\n", ret);
2258     return ret;
2259 }
2260 
2261 static BOOL CRYPT_AsnDecodeIA5String(const BYTE *pbEncoded,
2262  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2263  DWORD *pcbDecoded)
2264 {
2265     BOOL ret = TRUE;
2266     DWORD dataLen;
2267     LPSTR *pStr = pvStructInfo;
2268 
2269     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2270     {
2271         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2272         DWORD bytesNeeded = sizeof(LPSTR) + sizeof(char);
2273 
2274         if (pbEncoded[0] != ASN_IA5STRING)
2275         {
2276             SetLastError(CRYPT_E_ASN1_CORRUPT);
2277             ret = FALSE;
2278         }
2279         else
2280         {
2281             bytesNeeded += dataLen;
2282             if (pcbDecoded)
2283                 *pcbDecoded = 1 + lenBytes + dataLen;
2284             if (!pvStructInfo)
2285                 *pcbStructInfo = bytesNeeded;
2286             else if (*pcbStructInfo < bytesNeeded)
2287             {
2288                 *pcbStructInfo = bytesNeeded;
2289                 SetLastError(ERROR_MORE_DATA);
2290                 ret = FALSE;
2291             }
2292             else
2293             {
2294                 *pcbStructInfo = bytesNeeded;
2295                 if (dataLen)
2296                 {
2297                     LPSTR str = *pStr;
2298 
2299                     assert(str);
2300                     memcpy(str, pbEncoded + 1 + lenBytes, dataLen);
2301                     str[dataLen] = 0;
2302                 }
2303                 else
2304                     *pStr = NULL;
2305             }
2306         }
2307     }
2308     return ret;
2309 }
2310 
2311 static BOOL CRYPT_AsnDecodeIntArray(const BYTE *pbEncoded,
2312  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2313  DWORD *pcbDecoded)
2314 {
2315     struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
2316      CRYPT_AsnDecodeIntInternal, sizeof(int), FALSE, 0 };
2317     struct GenericArray *array = pvStructInfo;
2318     BOOL ret;
2319 
2320     TRACE("(%p, %d, %08x, %p, %d)\n", pbEncoded, cbEncoded, dwFlags,
2321      pvStructInfo, pvStructInfo ? *pcbDecoded : 0);
2322 
2323     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2324      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
2325      array ? array->rgItems : NULL);
2326     TRACE("returning %d\n", ret);
2327     return ret;
2328 }
2329 
2330 static BOOL CRYPT_AsnDecodeNoticeReference(const BYTE *pbEncoded,
2331  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2332  DWORD *pcbDecoded)
2333 {
2334     BOOL ret;
2335     struct AsnDecodeSequenceItem items[] = {
2336      { ASN_IA5STRING, offsetof(CERT_POLICY_QUALIFIER_NOTICE_REFERENCE,
2337        pszOrganization), CRYPT_AsnDecodeIA5String, sizeof(LPSTR), FALSE, TRUE,
2338        offsetof(CERT_POLICY_QUALIFIER_NOTICE_REFERENCE, pszOrganization), 0 },
2339      { ASN_SEQUENCEOF, offsetof(CERT_POLICY_QUALIFIER_NOTICE_REFERENCE,
2340        cNoticeNumbers), CRYPT_AsnDecodeIntArray, sizeof(struct GenericArray),
2341        FALSE, TRUE, offsetof(CERT_POLICY_QUALIFIER_NOTICE_REFERENCE,
2342        rgNoticeNumbers), 0 },
2343     };
2344     DWORD bytesNeeded;
2345 
2346     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2347      pvStructInfo, pvStructInfo ? *pcbStructInfo : 0);
2348 
2349     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2350      pbEncoded, cbEncoded, dwFlags, NULL, NULL, &bytesNeeded, pcbDecoded,
2351      NULL);
2352     if (ret)
2353     {
2354         /* The caller is expecting a pointer to a
2355          * CERT_POLICY_QUALIFIER_NOTICE_REFERENCE to be decoded, whereas
2356          * CRYPT_AsnDecodeSequence is decoding a
2357          * CERT_POLICY_QUALIFIER_NOTICE_REFERENCE.  Increment the bytes
2358          * needed, and decode again if the requisite space is available.
2359          */
2360         bytesNeeded += sizeof(PCERT_POLICY_QUALIFIER_NOTICE_REFERENCE);
2361         if (!pvStructInfo)
2362             *pcbStructInfo = bytesNeeded;
2363         else if (*pcbStructInfo < bytesNeeded)
2364         {
2365             *pcbStructInfo = bytesNeeded;
2366             SetLastError(ERROR_MORE_DATA);
2367             ret = FALSE;
2368         }
2369         else
2370         {
2371             PCERT_POLICY_QUALIFIER_NOTICE_REFERENCE noticeRef;
2372 
2373             *pcbStructInfo = bytesNeeded;
2374             /* The pointer (pvStructInfo) passed in points to the first dynamic
2375              * pointer, so use it as the pointer to the
2376              * CERT_POLICY_QUALIFIER_NOTICE_REFERENCE, and create the
2377              * appropriate offset for the first dynamic pointer within the
2378              * notice reference by pointing to the first memory location past
2379              * the CERT_POLICY_QUALIFIER_NOTICE_REFERENCE.
2380              */
2381             noticeRef =
2382              *(PCERT_POLICY_QUALIFIER_NOTICE_REFERENCE *)pvStructInfo;
2383             noticeRef->pszOrganization = (LPSTR)((LPBYTE)noticeRef +
2384              sizeof(CERT_POLICY_QUALIFIER_NOTICE_REFERENCE));
2385             ret = CRYPT_AsnDecodeSequence(items,
2386              sizeof(items) / sizeof(items[0]), pbEncoded, cbEncoded, dwFlags,
2387              NULL, noticeRef, &bytesNeeded, pcbDecoded,
2388              noticeRef->pszOrganization);
2389         }
2390     }
2391     TRACE("returning %d\n", ret);
2392     return ret;
2393 }
2394 
2395 static BOOL CRYPT_AsnDecodeBMPString(const BYTE *pbEncoded,
2396  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2397  DWORD *pcbDecoded)
2398 {
2399     BOOL ret = TRUE;
2400     DWORD dataLen;
2401     LPWSTR *pStr = pvStructInfo;
2402 
2403     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2404     {
2405         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2406         DWORD bytesNeeded = sizeof(LPWSTR) + sizeof(WCHAR);
2407 
2408         if (pbEncoded[0] != ASN_BMPSTRING)
2409         {
2410             SetLastError(CRYPT_E_ASN1_CORRUPT);
2411             ret = FALSE;
2412         }
2413         else
2414         {
2415             bytesNeeded += dataLen;
2416             if (pcbDecoded)
2417                 *pcbDecoded = 1 + lenBytes + dataLen;
2418             if (!pvStructInfo)
2419                 *pcbStructInfo = bytesNeeded;
2420             else if (*pcbStructInfo < bytesNeeded)
2421             {
2422                 *pcbStructInfo = bytesNeeded;
2423                 SetLastError(ERROR_MORE_DATA);
2424                 ret = FALSE;
2425             }
2426             else
2427             {
2428                 *pcbStructInfo = bytesNeeded;
2429                 if (dataLen)
2430                 {
2431                     DWORD i;
2432                     LPWSTR str = *pStr;
2433 
2434                     assert(str);
2435                     for (i = 0; i < dataLen / 2; i++)
2436                         str[i] = (pbEncoded[1 + lenBytes + 2 * i] << 8) |
2437                          pbEncoded[1 + lenBytes + 2 * i + 1];
2438                     str[i] = 0;
2439                 }
2440                 else
2441                     *pStr = NULL;
2442             }
2443         }
2444     }
2445     return ret;
2446 }
2447 
2448 static BOOL CRYPT_AsnDecodePolicyQualifierUserNoticeInternal(
2449  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo,
2450  DWORD *pcbStructInfo, DWORD *pcbDecoded)
2451 {
2452     BOOL ret;
2453     struct AsnDecodeSequenceItem items[] = {
2454      { ASN_SEQUENCE, offsetof(CERT_POLICY_QUALIFIER_USER_NOTICE,
2455        pNoticeReference), CRYPT_AsnDecodeNoticeReference,
2456        sizeof(PCERT_POLICY_QUALIFIER_NOTICE_REFERENCE), TRUE, TRUE,
2457        offsetof(CERT_POLICY_QUALIFIER_USER_NOTICE, pNoticeReference), 0 },
2458      { ASN_BMPSTRING, offsetof(CERT_POLICY_QUALIFIER_USER_NOTICE,
2459        pszDisplayText), CRYPT_AsnDecodeBMPString, sizeof(LPWSTR), TRUE, TRUE,
2460        offsetof(CERT_POLICY_QUALIFIER_USER_NOTICE, pszDisplayText), 0 },
2461     };
2462     PCERT_POLICY_QUALIFIER_USER_NOTICE notice = pvStructInfo;
2463 
2464     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2465      pvStructInfo, *pcbStructInfo);
2466 
2467     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2468      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
2469      pcbDecoded, notice ? notice->pNoticeReference : NULL);
2470     TRACE("returning %d\n", ret);
2471     return ret;
2472 }
2473 
2474 static BOOL WINAPI CRYPT_AsnDecodePolicyQualifierUserNotice(
2475  DWORD dwCertEncodingType, LPCSTR lpszStructType, const BYTE *pbEncoded,
2476  DWORD cbEncoded, DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
2477  void *pvStructInfo, DWORD *pcbStructInfo)
2478 {
2479     BOOL ret = FALSE;
2480 
2481     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2482      pDecodePara, pvStructInfo, *pcbStructInfo);
2483 
2484     __TRY
2485     {
2486         DWORD bytesNeeded;
2487 
2488         ret = CRYPT_AsnDecodePolicyQualifierUserNoticeInternal(pbEncoded,
2489          cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &bytesNeeded,
2490          NULL);
2491         if (ret)
2492         {
2493             if (!pvStructInfo)
2494                 *pcbStructInfo = bytesNeeded;
2495             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2496              pvStructInfo, pcbStructInfo, bytesNeeded)))
2497             {
2498                 PCERT_POLICY_QUALIFIER_USER_NOTICE notice;
2499 
2500                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2501                     pvStructInfo = *(BYTE **)pvStructInfo;
2502                 notice = pvStructInfo;
2503                 notice->pNoticeReference =
2504                  (PCERT_POLICY_QUALIFIER_NOTICE_REFERENCE)
2505                  ((BYTE *)pvStructInfo +
2506                  sizeof(CERT_POLICY_QUALIFIER_USER_NOTICE));
2507                 ret = CRYPT_AsnDecodePolicyQualifierUserNoticeInternal(
2508                  pbEncoded, cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG,
2509                  pvStructInfo, &bytesNeeded, NULL);
2510             }
2511         }
2512     }
2513     __EXCEPT_PAGE_FAULT
2514     {
2515         SetLastError(STATUS_ACCESS_VIOLATION);
2516     }
2517     __ENDTRY
2518     TRACE("returning %d\n", ret);
2519     return ret;
2520 }
2521 
2522 static BOOL CRYPT_AsnDecodePKCSAttributeInternal(const BYTE *pbEncoded,
2523  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2524  DWORD *pcbDecoded)
2525 {
2526     BOOL ret;
2527     struct AsnDecodeSequenceItem items[] = {
2528      { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_ATTRIBUTE, pszObjId),
2529        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
2530        offsetof(CRYPT_ATTRIBUTE, pszObjId), 0 },
2531      { ASN_CONSTRUCTOR | ASN_SETOF, offsetof(CRYPT_ATTRIBUTE, cValue),
2532        CRYPT_DecodeDERArray, sizeof(struct GenericArray), FALSE, TRUE,
2533        offsetof(CRYPT_ATTRIBUTE, rgValue), 0 },
2534     };
2535     PCRYPT_ATTRIBUTE attr = (PCRYPT_ATTRIBUTE)pvStructInfo;
2536 
2537     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2538      pvStructInfo, *pcbStructInfo);
2539 
2540     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2541      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
2542      pcbDecoded, attr ? attr->pszObjId : NULL);
2543     TRACE("returning %d\n", ret);
2544     return ret;
2545 }
2546 
2547 static BOOL WINAPI CRYPT_AsnDecodePKCSAttribute(DWORD dwCertEncodingType,
2548  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2549  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2550 {
2551     BOOL ret = FALSE;
2552 
2553     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2554      pDecodePara, pvStructInfo, *pcbStructInfo);
2555 
2556     __TRY
2557     {
2558         DWORD bytesNeeded;
2559 
2560         ret = CRYPT_AsnDecodePKCSAttributeInternal(pbEncoded, cbEncoded,
2561          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &bytesNeeded, NULL);
2562         if (ret)
2563         {
2564             if (!pvStructInfo)
2565                 *pcbStructInfo = bytesNeeded;
2566             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2567              pvStructInfo, pcbStructInfo, bytesNeeded)))
2568             {
2569                 PCRYPT_ATTRIBUTE attr;
2570 
2571                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2572                     pvStructInfo = *(BYTE **)pvStructInfo;
2573                 attr = (PCRYPT_ATTRIBUTE)pvStructInfo;
2574                 attr->pszObjId = (LPSTR)((BYTE *)pvStructInfo +
2575                  sizeof(CRYPT_ATTRIBUTE));
2576                 ret = CRYPT_AsnDecodePKCSAttributeInternal(pbEncoded, cbEncoded,
2577                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo, &bytesNeeded,
2578                  NULL);
2579             }
2580         }
2581     }
2582     __EXCEPT_PAGE_FAULT
2583     {
2584         SetLastError(STATUS_ACCESS_VIOLATION);
2585     }
2586     __ENDTRY
2587     TRACE("returning %d\n", ret);
2588     return ret;
2589 }
2590 
2591 static BOOL CRYPT_AsnDecodePKCSAttributesInternal(const BYTE *pbEncoded,
2592  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2593  DWORD *pcbDecoded)
2594 {
2595     struct AsnArrayDescriptor arrayDesc = { 0,
2596      CRYPT_AsnDecodePKCSAttributeInternal, sizeof(CRYPT_ATTRIBUTE), TRUE,
2597      offsetof(CRYPT_ATTRIBUTE, pszObjId) };
2598     PCRYPT_ATTRIBUTES attrs = (PCRYPT_ATTRIBUTES)pvStructInfo;
2599     BOOL ret;
2600 
2601     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2602      NULL, pvStructInfo, pcbStructInfo, pcbDecoded, attrs ? attrs->rgAttr :
2603      NULL);
2604     return ret;
2605 }
2606 
2607 static BOOL WINAPI CRYPT_AsnDecodePKCSAttributes(DWORD dwCertEncodingType,
2608  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2609  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2610 {
2611     BOOL ret = FALSE;
2612 
2613     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2614      pDecodePara, pvStructInfo, *pcbStructInfo);
2615 
2616     __TRY
2617     {
2618         DWORD bytesNeeded;
2619 
2620         if (!cbEncoded)
2621             SetLastError(CRYPT_E_ASN1_EOD);
2622         else if (pbEncoded[0] != (ASN_CONSTRUCTOR | ASN_SETOF))
2623             SetLastError(CRYPT_E_ASN1_CORRUPT);
2624         else if ((ret = CRYPT_AsnDecodePKCSAttributesInternal(pbEncoded,
2625          cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &bytesNeeded,
2626          NULL)))
2627         {
2628             if (!pvStructInfo)
2629                 *pcbStructInfo = bytesNeeded;
2630             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2631              pvStructInfo, pcbStructInfo, bytesNeeded)))
2632             {
2633                 PCRYPT_ATTRIBUTES attrs;
2634 
2635                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2636                     pvStructInfo = *(BYTE **)pvStructInfo;
2637                 attrs = (PCRYPT_ATTRIBUTES)pvStructInfo;
2638                 attrs->rgAttr = (PCRYPT_ATTRIBUTE)((BYTE *)pvStructInfo +
2639                  sizeof(CRYPT_ATTRIBUTES));
2640                 ret = CRYPT_AsnDecodePKCSAttributesInternal(pbEncoded,
2641                  cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
2642                  &bytesNeeded, NULL);
2643             }
2644         }
2645     }
2646     __EXCEPT_PAGE_FAULT
2647     {
2648         SetLastError(STATUS_ACCESS_VIOLATION);
2649     }
2650     __ENDTRY
2651     TRACE("returning %d\n", ret);
2652     return ret;
2653 }
2654 
2655 static BOOL CRYPT_AsnDecodeAlgorithmId(const BYTE *pbEncoded, DWORD cbEncoded,
2656  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2657 {
2658     CRYPT_ALGORITHM_IDENTIFIER *algo =
2659      (CRYPT_ALGORITHM_IDENTIFIER *)pvStructInfo;
2660     BOOL ret = TRUE;
2661     struct AsnDecodeSequenceItem items[] = {
2662      { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_ALGORITHM_IDENTIFIER, pszObjId),
2663        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
2664        offsetof(CRYPT_ALGORITHM_IDENTIFIER, pszObjId), 0 },
2665      { 0, offsetof(CRYPT_ALGORITHM_IDENTIFIER, Parameters),
2666        CRYPT_AsnDecodeCopyBytes, sizeof(CRYPT_OBJID_BLOB), TRUE, TRUE, 
2667        offsetof(CRYPT_ALGORITHM_IDENTIFIER, Parameters.pbData), 0 },
2668     };
2669 
2670     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
2671      pvStructInfo, *pcbStructInfo, pcbDecoded);
2672 
2673     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2674      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
2675      pcbDecoded, algo ? algo->pszObjId : NULL);
2676     if (ret && pvStructInfo)
2677     {
2678         TRACE("pszObjId is %p (%s)\n", algo->pszObjId,
2679          debugstr_a(algo->pszObjId));
2680     }
2681     return ret;
2682 }
2683 
2684 static BOOL CRYPT_AsnDecodePubKeyInfoInternal(const BYTE *pbEncoded,
2685  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2686  DWORD *pcbDecoded)
2687 {
2688     BOOL ret = TRUE;
2689     struct AsnDecodeSequenceItem items[] = {
2690      { ASN_SEQUENCEOF, offsetof(CERT_PUBLIC_KEY_INFO, Algorithm),
2691        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
2692        FALSE, TRUE, offsetof(CERT_PUBLIC_KEY_INFO,
2693        Algorithm.pszObjId) },
2694      { ASN_BITSTRING, offsetof(CERT_PUBLIC_KEY_INFO, PublicKey),
2695        CRYPT_AsnDecodeBitsInternal, sizeof(CRYPT_BIT_BLOB), FALSE, TRUE,
2696        offsetof(CERT_PUBLIC_KEY_INFO, PublicKey.pbData) },
2697     };
2698     PCERT_PUBLIC_KEY_INFO info = (PCERT_PUBLIC_KEY_INFO)pvStructInfo;
2699 
2700     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2701      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
2702      pcbDecoded, info ? info->Algorithm.Parameters.pbData : NULL);
2703     return ret;
2704 }
2705 
2706 static BOOL WINAPI CRYPT_AsnDecodePubKeyInfo(DWORD dwCertEncodingType,
2707  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2708  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2709 {
2710     BOOL ret = TRUE;
2711 
2712     __TRY
2713     {
2714         DWORD bytesNeeded;
2715 
2716         if ((ret = CRYPT_AsnDecodePubKeyInfoInternal(pbEncoded, cbEncoded,
2717          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &bytesNeeded, NULL)))
2718         {
2719             if (!pvStructInfo)
2720                 *pcbStructInfo = bytesNeeded;
2721             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
2722              pvStructInfo, pcbStructInfo, bytesNeeded)))
2723             {
2724                 PCERT_PUBLIC_KEY_INFO info;
2725 
2726                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2727                     pvStructInfo = *(BYTE **)pvStructInfo;
2728                 info = (PCERT_PUBLIC_KEY_INFO)pvStructInfo;
2729                 info->Algorithm.Parameters.pbData = (BYTE *)pvStructInfo +
2730                  sizeof(CERT_PUBLIC_KEY_INFO);
2731                 ret = CRYPT_AsnDecodePubKeyInfoInternal(pbEncoded, cbEncoded,
2732                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
2733                  &bytesNeeded, NULL);
2734             }
2735         }
2736     }
2737     __EXCEPT_PAGE_FAULT
2738     {
2739         SetLastError(STATUS_ACCESS_VIOLATION);
2740         ret = FALSE;
2741     }
2742     __ENDTRY
2743     return ret;
2744 }
2745 
2746 static BOOL CRYPT_AsnDecodeBool(const BYTE *pbEncoded, DWORD cbEncoded,
2747  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2748 {
2749     BOOL ret;
2750 
2751     if (cbEncoded < 3)
2752     {
2753         SetLastError(CRYPT_E_ASN1_CORRUPT);
2754         return FALSE;
2755     }
2756     if (GET_LEN_BYTES(pbEncoded[1]) > 1)
2757     {
2758         SetLastError(CRYPT_E_ASN1_CORRUPT);
2759         return FALSE;
2760     }
2761     if (pbEncoded[1] > 1)
2762     {
2763         SetLastError(CRYPT_E_ASN1_CORRUPT);
2764         return FALSE;
2765     }
2766     if (pcbDecoded)
2767         *pcbDecoded = 3;
2768     if (!pvStructInfo)
2769     {
2770         *pcbStructInfo = sizeof(BOOL);
2771         ret = TRUE;
2772     }
2773     else if (*pcbStructInfo < sizeof(BOOL))
2774     {
2775         *pcbStructInfo = sizeof(BOOL);
2776         SetLastError(ERROR_MORE_DATA);
2777         ret = FALSE;
2778     }
2779     else
2780     {
2781         *pcbStructInfo = sizeof(BOOL);
2782         *(BOOL *)pvStructInfo = pbEncoded[2] ? TRUE : FALSE;
2783         ret = TRUE;
2784     }
2785     TRACE("returning %d (%08x)\n", ret, GetLastError());
2786     return ret;
2787 }
2788 
2789 static BOOL CRYPT_AsnDecodeAltNameEntry(const BYTE *pbEncoded, DWORD cbEncoded,
2790  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
2791 {
2792     PCERT_ALT_NAME_ENTRY entry = (PCERT_ALT_NAME_ENTRY)pvStructInfo;
2793     DWORD dataLen, lenBytes, bytesNeeded = sizeof(CERT_ALT_NAME_ENTRY);
2794     BOOL ret;
2795 
2796     TRACE("%p, %d, %08x, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
2797      pvStructInfo, *pcbStructInfo);
2798 
2799     if (cbEncoded < 2)
2800     {
2801         SetLastError(CRYPT_E_ASN1_CORRUPT);
2802         return FALSE;
2803     }
2804     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2805     if (1 + lenBytes > cbEncoded)
2806     {
2807         SetLastError(CRYPT_E_ASN1_CORRUPT);
2808         return FALSE;
2809     }
2810     if ((ret = CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen)))
2811     {
2812         switch (pbEncoded[0] & ASN_TYPE_MASK)
2813         {
2814         case 1: /* rfc822Name */
2815         case 2: /* dNSName */
2816         case 6: /* uniformResourceIdentifier */
2817             bytesNeeded += (dataLen + 1) * sizeof(WCHAR);
2818             break;
2819         case 4: /* directoryName */
2820         case 7: /* iPAddress */
2821             bytesNeeded += dataLen;
2822             break;
2823         case 8: /* registeredID */
2824             ret = CRYPT_AsnDecodeOidIgnoreTag(pbEncoded, cbEncoded, 0, NULL,
2825              &dataLen, NULL);
2826             if (ret)
2827             {
2828                 /* FIXME: ugly, shouldn't need to know internals of OID decode
2829                  * function to use it.
2830                  */
2831                 bytesNeeded += dataLen - sizeof(LPSTR);
2832             }
2833             break;
2834         case 0: /* otherName */
2835             FIXME("%d: stub\n", pbEncoded[0] & ASN_TYPE_MASK);
2836             SetLastError(CRYPT_E_ASN1_BADTAG);
2837             ret = FALSE;
2838             break;
2839         case 3: /* x400Address, unimplemented */
2840         case 5: /* ediPartyName, unimplemented */
2841             TRACE("type %d unimplemented\n", pbEncoded[0] & ASN_TYPE_MASK);
2842             SetLastError(CRYPT_E_ASN1_BADTAG);
2843             ret = FALSE;
2844             break;
2845         default:
2846             TRACE("type %d bad\n", pbEncoded[0] & ASN_TYPE_MASK);
2847             SetLastError(CRYPT_E_ASN1_CORRUPT);
2848             ret = FALSE;
2849         }
2850         if (ret)
2851         {
2852             if (pcbDecoded)
2853                 *pcbDecoded = 1 + lenBytes + dataLen;
2854             if (!entry)
2855                 *pcbStructInfo = bytesNeeded;
2856             else if (*pcbStructInfo < bytesNeeded)
2857             {
2858                 *pcbStructInfo = bytesNeeded;
2859                 SetLastError(ERROR_MORE_DATA);
2860                 ret = FALSE;
2861             }
2862             else
2863             {
2864                 *pcbStructInfo = bytesNeeded;
2865                 /* MS used values one greater than the asn1 ones.. sigh */
2866                 entry->dwAltNameChoice = (pbEncoded[0] & ASN_TYPE_MASK) + 1;
2867                 switch (pbEncoded[0] & ASN_TYPE_MASK)
2868                 {
2869                 case 1: /* rfc822Name */
2870                 case 2: /* dNSName */
2871                 case 6: /* uniformResourceIdentifier */
2872                 {
2873                     DWORD i;
2874 
2875                     for (i = 0; i < dataLen; i++)
2876                         entry->u.pwszURL[i] =
2877                          (WCHAR)pbEncoded[1 + lenBytes + i];
2878                     entry->u.pwszURL[i] = 0;
2879                     TRACE("URL is %p (%s)\n", entry->u.pwszURL,
2880                      debugstr_w(entry->u.pwszURL));
2881                     break;
2882                 }
2883                 case 4: /* directoryName */
2884                     /* The data are memory-equivalent with the IPAddress case,
2885                      * fall-through
2886                      */
2887                 case 7: /* iPAddress */
2888                     /* The next data pointer is in the pwszURL spot, that is,
2889                      * the first 4 bytes.  Need to move it to the next spot.
2890                      */
2891                     entry->u.IPAddress.pbData = (LPBYTE)entry->u.pwszURL;
2892                     entry->u.IPAddress.cbData = dataLen;
2893                     memcpy(entry->u.IPAddress.pbData, pbEncoded + 1 + lenBytes,
2894                      dataLen);
2895                     break;
2896                 case 8: /* registeredID */
2897                     ret = CRYPT_AsnDecodeOidIgnoreTag(pbEncoded, cbEncoded, 0,
2898                      &entry->u.pszRegisteredID, &dataLen, NULL);
2899                     break;
2900                 }
2901             }
2902         }
2903     }
2904     return ret;
2905 }
2906 
2907 static BOOL CRYPT_AsnDecodeAltNameInternal(const BYTE *pbEncoded,
2908  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2909  DWORD *pcbDecoded)
2910 {
2911     BOOL ret = TRUE;
2912     struct AsnArrayDescriptor arrayDesc = { 0,
2913      CRYPT_AsnDecodeAltNameEntry, sizeof(CERT_ALT_NAME_ENTRY), TRUE,
2914      offsetof(CERT_ALT_NAME_ENTRY, u.pwszURL) };
2915     PCERT_ALT_NAME_INFO info = (PCERT_ALT_NAME_INFO)pvStructInfo;
2916 
2917     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
2918      pvStructInfo, *pcbStructInfo, pcbDecoded);
2919 
2920     if (info)
2921         TRACE("info->rgAltEntry is %p\n", info->rgAltEntry);
2922     ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
2923      NULL, pvStructInfo, pcbStructInfo, pcbDecoded,
2924      info ? info->rgAltEntry : NULL);
2925     return ret;
2926 }
2927 
2928 /* Like CRYPT_AsnDecodeIntegerInternal, but swaps the bytes */
2929 static BOOL CRYPT_AsnDecodeIntegerSwapBytes(const BYTE *pbEncoded,
2930  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
2931  DWORD *pcbDecoded)
2932 {
2933     BOOL ret;
2934 
2935     TRACE("(%p, %d, 0x%08x, %p, %d, %p)\n", pbEncoded, cbEncoded, dwFlags,
2936      pvStructInfo, *pcbStructInfo, pcbDecoded);
2937 
2938     /* Can't use the CRYPT_DECODE_NOCOPY_FLAG, because we modify the bytes in-
2939      * place.
2940      */
2941     ret = CRYPT_AsnDecodeIntegerInternal(pbEncoded, cbEncoded,
2942      dwFlags & ~CRYPT_DECODE_NOCOPY_FLAG, pvStructInfo, pcbStructInfo,
2943      pcbDecoded);
2944     if (ret && pvStructInfo)
2945     {
2946         CRYPT_DATA_BLOB *blob = (CRYPT_DATA_BLOB *)pvStructInfo;
2947 
2948         if (blob->cbData)
2949         {
2950             DWORD i;
2951             BYTE temp;
2952 
2953             for (i = 0; i < blob->cbData / 2; i++)
2954             {
2955                 temp = blob->pbData[i];
2956                 blob->pbData[i] = blob->pbData[blob->cbData - i - 1];
2957                 blob->pbData[blob->cbData - i - 1] = temp;
2958             }
2959         }
2960     }
2961     TRACE("returning %d (%08x)\n", ret, GetLastError());
2962     return ret;
2963 }
2964 
2965 static BOOL WINAPI CRYPT_AsnDecodeAuthorityKeyId(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 
2971     __TRY
2972     {
2973         struct AsnDecodeSequenceItem items[] = {
2974          { ASN_CONTEXT | 0, offsetof(CERT_AUTHORITY_KEY_ID_INFO, KeyId),
2975            CRYPT_AsnDecodeIntegerSwapBytes, sizeof(CRYPT_DATA_BLOB),
2976            TRUE, TRUE, offsetof(CERT_AUTHORITY_KEY_ID_INFO, KeyId.pbData), 0 },
2977          { ASN_CONTEXT | ASN_CONSTRUCTOR| 1,
2978            offsetof(CERT_AUTHORITY_KEY_ID_INFO, CertIssuer),
2979            CRYPT_AsnDecodeOctetsInternal, sizeof(CERT_NAME_BLOB), TRUE, TRUE,
2980            offsetof(CERT_AUTHORITY_KEY_ID_INFO, CertIssuer.pbData), 0 },
2981          { ASN_CONTEXT | 2, offsetof(CERT_AUTHORITY_KEY_ID_INFO,
2982            CertSerialNumber), CRYPT_AsnDecodeIntegerInternal,
2983            sizeof(CRYPT_INTEGER_BLOB), TRUE, TRUE,
2984            offsetof(CERT_AUTHORITY_KEY_ID_INFO, CertSerialNumber.pbData), 0 },
2985         };
2986 
2987         ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
2988          pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
2989          pcbStructInfo, NULL, NULL);
2990     }
2991     __EXCEPT_PAGE_FAULT
2992     {
2993         SetLastError(STATUS_ACCESS_VIOLATION);
2994         ret = FALSE;
2995     }
2996     __ENDTRY
2997     return ret;
2998 }
2999 
3000 static BOOL WINAPI CRYPT_AsnDecodeAuthorityKeyId2(DWORD dwCertEncodingType,
3001  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3002  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3003 {
3004     BOOL ret;
3005 
3006     __TRY
3007     {
3008         struct AsnDecodeSequenceItem items[] = {
3009          { ASN_CONTEXT | 0, offsetof(CERT_AUTHORITY_KEY_ID2_INFO, KeyId),
3010            CRYPT_AsnDecodeIntegerSwapBytes, sizeof(CRYPT_DATA_BLOB),
3011            TRUE, TRUE, offsetof(CERT_AUTHORITY_KEY_ID2_INFO, KeyId.pbData), 0 },
3012          { ASN_CONTEXT | ASN_CONSTRUCTOR| 1,
3013            offsetof(CERT_AUTHORITY_KEY_ID2_INFO, AuthorityCertIssuer),
3014            CRYPT_AsnDecodeAltNameInternal, sizeof(CERT_ALT_NAME_INFO), TRUE,
3015            TRUE, offsetof(CERT_AUTHORITY_KEY_ID2_INFO,
3016            AuthorityCertIssuer.rgAltEntry), 0 },
3017          { ASN_CONTEXT | 2, offsetof(CERT_AUTHORITY_KEY_ID2_INFO,
3018            AuthorityCertSerialNumber), CRYPT_AsnDecodeIntegerInternal,
3019            sizeof(CRYPT_INTEGER_BLOB), TRUE, TRUE,
3020            offsetof(CERT_AUTHORITY_KEY_ID2_INFO,
3021            AuthorityCertSerialNumber.pbData), 0 },
3022         };
3023 
3024         ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
3025          pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
3026          pcbStructInfo, NULL, NULL);
3027     }
3028     __EXCEPT_PAGE_FAULT
3029     {
3030         SetLastError(STATUS_ACCESS_VIOLATION);
3031         ret = FALSE;
3032     }
3033     __ENDTRY
3034     return ret;
3035 }
3036 
3037 static BOOL CRYPT_AsnDecodeAccessDescription(const BYTE *pbEncoded,
3038  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
3039  DWORD *pcbDecoded)
3040 {
3041     struct AsnDecodeSequenceItem items[] = {
3042      { 0, offsetof(CERT_ACCESS_DESCRIPTION, pszAccessMethod),
3043        CRYPT_AsnDecodeOidInternal, sizeof(LPSTR), FALSE, TRUE,
3044        offsetof(CERT_ACCESS_DESCRIPTION, pszAccessMethod), 0 },
3045      { 0, offsetof(CERT_ACCESS_DESCRIPTION, AccessLocation),
3046        CRYPT_AsnDecodeAltNameEntry, sizeof(CERT_ALT_NAME_ENTRY), FALSE,
3047        TRUE, offsetof(CERT_ACCESS_DESCRIPTION, AccessLocation.u.pwszURL), 0 },
3048     };
3049     CERT_ACCESS_DESCRIPTION *descr = (CERT_ACCESS_DESCRIPTION *)pvStructInfo;
3050 
3051     return CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
3052      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
3053      pcbDecoded, descr ? descr->pszAccessMethod : NULL);
3054 }
3055 
3056 static BOOL WINAPI CRYPT_AsnDecodeAuthorityInfoAccess(DWORD dwCertEncodingType,
3057  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3058  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3059 {
3060     BOOL ret;
3061 
3062     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3063      pDecodePara, pvStructInfo, *pcbStructInfo);
3064 
3065     __TRY
3066     {
3067         struct AsnArrayDescriptor arrayDesc = { ASN_SEQUENCEOF,
3068          CRYPT_AsnDecodeAccessDescription, sizeof(CERT_ACCESS_DESCRIPTION),
3069          TRUE, offsetof(CERT_ACCESS_DESCRIPTION, pszAccessMethod) };
3070 
3071         ret = CRYPT_AsnDecodeArray(&arrayDesc, pbEncoded, cbEncoded, dwFlags,
3072          pDecodePara, pvStructInfo, pcbStructInfo, NULL, NULL);
3073     }
3074     __EXCEPT_PAGE_FAULT
3075     {
3076         SetLastError(STATUS_ACCESS_VIOLATION);
3077         ret = FALSE;
3078     }
3079     __ENDTRY
3080     return ret;
3081 }
3082 
3083 static BOOL CRYPT_AsnDecodePKCSContent(const BYTE *pbEncoded, DWORD cbEncoded,
3084  DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo, DWORD *pcbDecoded)
3085 {
3086     BOOL ret;
3087     DWORD dataLen;
3088 
3089     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
3090      pvStructInfo, *pcbStructInfo, pcbDecoded);
3091 
3092     /* The caller has already checked the tag, no need to check it again.
3093      * Check the outer length is valid:
3094      */
3095     if ((ret = CRYPT_GetLengthIndefinite(pbEncoded, cbEncoded, &dataLen)))
3096     {
3097         BYTE lenBytes = GET_LEN_BYTES(pbEncoded[1]);
3098         DWORD innerLen;
3099 
3100         pbEncoded += 1 + lenBytes;
3101         cbEncoded -= 1 + lenBytes;
3102         if (dataLen == CMSG_INDEFINITE_LENGTH)
3103             cbEncoded -= 2; /* space for 0 TLV */
3104         /* Check the inner length is valid: */
3105         if ((ret = CRYPT_GetLengthIndefinite(pbEncoded, cbEncoded, &innerLen)))
3106         {
3107             DWORD decodedLen;
3108 
3109             ret = CRYPT_AsnDecodeCopyBytes(pbEncoded, cbEncoded, dwFlags,
3110              pvStructInfo, pcbStructInfo, &decodedLen);
3111             if (dataLen == CMSG_INDEFINITE_LENGTH)
3112             {
3113                 if (*(pbEncoded + decodedLen) != 0 ||
3114                  *(pbEncoded + decodedLen + 1) != 0)
3115                 {
3116                     TRACE("expected 0 TLV, got {%02x,%02x}\n",
3117                      *(pbEncoded + decodedLen),
3118                      *(pbEncoded + decodedLen + 1));
3119                     SetLastError(CRYPT_E_ASN1_CORRUPT);
3120                     ret = FALSE;
3121                 }
3122                 else
3123                     decodedLen += 2;
3124             }
3125             if (ret && pcbDecoded)
3126             {
3127                 *pcbDecoded = 1 + lenBytes + decodedLen;
3128                 TRACE("decoded %d bytes\n", *pcbDecoded);
3129             }
3130         }
3131     }
3132     return ret;
3133 }
3134 
3135 static BOOL CRYPT_AsnDecodePKCSContentInfoInternal(const BYTE *pbEncoded,
3136  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
3137  DWORD *pcbDecoded)
3138 {
3139     CRYPT_CONTENT_INFO *info = (CRYPT_CONTENT_INFO *)pvStructInfo;
3140     struct AsnDecodeSequenceItem items[] = {
3141      { ASN_OBJECTIDENTIFIER, offsetof(CRYPT_CONTENT_INFO, pszObjId),
3142        CRYPT_AsnDecodeOidIgnoreTag, sizeof(LPSTR), FALSE, TRUE,
3143        offsetof(CRYPT_CONTENT_INFO, pszObjId), 0 },
3144      { ASN_CONTEXT | ASN_CONSTRUCTOR | 0,
3145        offsetof(CRYPT_CONTENT_INFO, Content), CRYPT_AsnDecodePKCSContent,
3146        sizeof(CRYPT_DER_BLOB), TRUE, TRUE,
3147        offsetof(CRYPT_CONTENT_INFO, Content.pbData), 0 },
3148     };
3149     BOOL ret;
3150 
3151     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
3152      pvStructInfo, *pcbStructInfo, pcbDecoded);
3153 
3154     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
3155      pbEncoded, cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo,
3156      pcbDecoded, info ? info->pszObjId : NULL);
3157     return ret;
3158 }
3159 
3160 static BOOL WINAPI CRYPT_AsnDecodePKCSContentInfo(DWORD dwCertEncodingType,
3161  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3162  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3163 {
3164     BOOL ret = FALSE;
3165 
3166     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3167      pDecodePara, pvStructInfo, *pcbStructInfo);
3168 
3169     __TRY
3170     {
3171         ret = CRYPT_AsnDecodePKCSContentInfoInternal(pbEncoded, cbEncoded,
3172          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, pcbStructInfo, NULL);
3173         if (ret && pvStructInfo)
3174         {
3175             ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
3176              pcbStructInfo, *pcbStructInfo);
3177             if (ret)
3178             {
3179                 CRYPT_CONTENT_INFO *info;
3180 
3181                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3182                     pvStructInfo = *(BYTE **)pvStructInfo;
3183                 info = (CRYPT_CONTENT_INFO *)pvStructInfo;
3184                 info->pszObjId = (LPSTR)((BYTE *)info +
3185                  sizeof(CRYPT_CONTENT_INFO));
3186                 ret = CRYPT_AsnDecodePKCSContentInfoInternal(pbEncoded,
3187                  cbEncoded, dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
3188                  pcbStructInfo, NULL);
3189             }
3190         }
3191     }
3192     __EXCEPT_PAGE_FAULT
3193     {
3194         SetLastError(STATUS_ACCESS_VIOLATION);
3195     }
3196     __ENDTRY
3197     return ret;
3198 }
3199 
3200 BOOL CRYPT_AsnDecodePKCSDigestedData(const BYTE *pbEncoded, DWORD cbEncoded,
3201  DWORD dwFlags, PCRYPT_DECODE_PARA pDecodePara,
3202  CRYPT_DIGESTED_DATA *digestedData, DWORD *pcbDigestedData)
3203 {
3204     BOOL ret;
3205     struct AsnDecodeSequenceItem items[] = {
3206      { ASN_INTEGER, offsetof(CRYPT_DIGESTED_DATA, version),
3207        CRYPT_AsnDecodeIntInternal, sizeof(DWORD), FALSE, FALSE, 0, 0 },
3208      { ASN_SEQUENCEOF, offsetof(CRYPT_DIGESTED_DATA, DigestAlgorithm),
3209        CRYPT_AsnDecodeAlgorithmId, sizeof(CRYPT_ALGORITHM_IDENTIFIER),
3210        FALSE, TRUE, offsetof(CRYPT_DIGESTED_DATA, DigestAlgorithm.pszObjId),
3211        0 },
3212      { ASN_SEQUENCEOF, offsetof(CRYPT_DIGESTED_DATA, ContentInfo),
3213        CRYPT_AsnDecodePKCSContentInfoInternal,
3214        sizeof(CRYPT_CONTENT_INFO), FALSE, TRUE, offsetof(CRYPT_DIGESTED_DATA,
3215        ContentInfo.pszObjId), 0 },
3216      { ASN_OCTETSTRING, offsetof(CRYPT_DIGESTED_DATA, hash),
3217        CRYPT_AsnDecodeOctetsInternal, sizeof(CRYPT_HASH_BLOB), FALSE, TRUE,
3218        offsetof(CRYPT_DIGESTED_DATA, hash.pbData), 0 },
3219     };
3220 
3221     ret = CRYPT_AsnDecodeSequence(items, sizeof(items) / sizeof(items[0]),
3222      pbEncoded, cbEncoded, dwFlags, pDecodePara, digestedData, pcbDigestedData,
3223      NULL, NULL);
3224     return ret;
3225 }
3226 
3227 static BOOL WINAPI CRYPT_AsnDecodeAltName(DWORD dwCertEncodingType,
3228  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
3229  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
3230 {
3231     BOOL ret = TRUE;
3232 
3233     TRACE("%p, %d, %08x, %p, %p, %d\n", pbEncoded, cbEncoded, dwFlags,
3234      pDecodePara, pvStructInfo, *pcbStructInfo);
3235 
3236     __TRY
3237     {
3238         DWORD bytesNeeded;
3239 
3240         if ((ret = CRYPT_AsnDecodeAltNameInternal(pbEncoded, cbEncoded,
3241          dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, NULL, &bytesNeeded, NULL)))
3242         {
3243             if (!pvStructInfo)
3244                 *pcbStructInfo = bytesNeeded;
3245             else if ((ret = CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara,
3246              pvStructInfo, pcbStructInfo, bytesNeeded)))
3247             {
3248                 CERT_ALT_NAME_INFO *name;
3249 
3250                 if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
3251                     pvStructInfo = *(BYTE **)pvStructInfo;
3252                 name = (CERT_ALT_NAME_INFO *)pvStructInfo;
3253                 name->rgAltEntry = (PCERT_ALT_NAME_ENTRY)
3254                  ((BYTE *)pvStructInfo + sizeof(CERT_ALT_NAME_INFO));
3255                 ret = CRYPT_AsnDecodeAltNameInternal(pbEncoded, cbEncoded,
3256                  dwFlags & ~CRYPT_DECODE_ALLOC_FLAG, pvStructInfo,
3257                  &bytesNeeded, NULL);
3258             }
3259         }
3260     }
3261     __EXCEPT_PAGE_FAULT
3262     {
3263         SetLastError(STATUS_ACCESS_VIOLATION);
3264         ret = FALSE;
3265     }
3266     __ENDTRY
3267     return ret;
3268 }
3269 
3270 struct PATH_LEN_CONSTRAINT
3271 {
3272     BOOL  fPathLenConstraint;
3273     DWORD dwPathLenConstraint;
3274 };
3275 
3276 static BOOL CRYPT_AsnDecodePathLenConstraint(const BYTE *pbEncoded,
3277  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
3278  DWORD *pcbDecoded)
3279 {
3280     BOOL ret = TRUE;
3281     DWORD bytesNeeded = sizeof(struct PATH_LEN_CONSTRAINT), size;
3282 
3283     TRACE("%p, %d, %08x, %p, %d, %p\n", pbEncoded, cbEncoded, dwFlags,
3284      pvStructInfo, *pcbStructInfo, pcbDecoded);
3285 
3286     if (!pvStructInfo)
3287     {
3288         ret = CRYPT_AsnDecodeIntInternal(pbEncoded, cbEncoded, dwFlags, NULL,
3289          &size, pcbDecoded);
3290         *pcbStructInfo = bytesNeeded;
3291     }
3292     else if (*pcbStructInfo < bytesNeeded)
3293     {
3294         SetLastError(ERROR_MORE_DATA);
3295         *pcbStructInfo = bytesNeeded;
3296         ret = FALSE;
3297     }
3298     else
3299     {
3300         struct PATH_LEN_CONSTRAINT *constraint =
3301          (struct PATH_LEN_CONSTRAINT *)pvStructInfo;
3302 
3303         *pcbStructInfo = bytesNeeded;
3304         size = sizeof(constraint->dwPathLenConstraint);
3305         ret = CRYPT_AsnDecodeIntInternal(pbEncoded, cbEncoded, dwFlags,
3306          &constraint->dwPathLenConstraint, &size, pcbDecoded);
3307         if (ret)
3308             constraint->fPathLenConstraint = TRUE;
3309         TRACE("got an int, dwPathLenConstraint is %d\n",
3310          constraint->dwPathLenConstraint);
3311     }
3312     TRACE("returning %d (%08x)\n", ret, GetLastError());
3313     return ret;
3314 }
3315 
3316 static BOOL CRYPT_AsnDecodeSubtreeConstraints(const BYTE *pbEncoded,
3317  DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo, DWORD *pcbStructInfo,
3318  DWORD *