cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
asn1_rd.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * ASN.1 Read Routines *
4 * Copyright Peter Gutmann 1992-2008 *
5 * *
6 ****************************************************************************/
7 
8 #include <ctype.h>
9 #if defined( INC_ALL )
10  #include "crypt.h"
11  #include "bn.h"
12  #include "asn1.h"
13 #else
14  #include "crypt.h"
15  #include "bn/bn.h"
16  #include "enc_dec/asn1.h"
17 #endif /* Compiler-specific includes */
18 
19 /****************************************************************************
20 * *
21 * Utility Routines *
22 * *
23 ****************************************************************************/
24 
25 /* When specifying a tag we can use either the default tag for the object
26  (indicated with the value DEFAULT_TAG) or a special-case tag. The
27  following macro selects the correct value. Since these are all primitive
28  objects we force the tag type to a primitive tag */
29 
30 #define selectTag( tag, defaultTag ) \
31  ( ( ( tag ) == DEFAULT_TAG ) ? ( defaultTag ) : \
32  ( MAKE_CTAG_PRIMITIVE( tag ) ) )
33 
34 /* Read the length octets for an ASN.1 data type with special-case handling
35  for long and short lengths and indefinite-length encodings. The short-
36  length read is limited to 32K, which is a sane limit for most PKI data
37  and one that doesn't cause type conversion problems on systems where
38  sizeof( int ) != sizeof( long ). If the caller indicates that indefinite
39  lengths are OK for short lengths we return OK_SPECIAL if we encounter one.
40  Long length reads always allow indefinite lengths since these are quite
41  likely for large objects */
42 
43 typedef enum {
44  READLENGTH_NONE, /* No length read behaviour */
45  READLENGTH_SHORT, /* Short length, no indef.allowed */
46  READLENGTH_SHORT_INDEF, /* Short length, indef.to OK_SPECIAL */
47  READLENGTH_LONG_INDEF, /* Long length, indef.to OK_SPECIAL */
48  READLENGTH_LAST /* Last possible read type */
50 
52 static int readLengthValue( INOUT STREAM *stream,
53  OUT_LENGTH_Z long *length,
54  IN_ENUM( READLENGTH ) const READLENGTH_TYPE readType )
55  {
56  BYTE buffer[ 8 + 8 ], *bufPtr = buffer;
57  BOOLEAN shortLen = ( readType == READLENGTH_SHORT || \
58  readType == READLENGTH_SHORT_INDEF );
59  long dataLength;
60  int noLengthOctets, i, status;
61 
62  assert( isWritePtr( stream, sizeof( STREAM ) ) );
63  assert( isWritePtr( length, sizeof( long ) ) );
64 
65  REQUIRES_S( readType > READLENGTH_NONE && readType < READLENGTH_LAST );
66 
67  /* Clear return value */
68  *length = 0;
69 
70  /* Read the first byte of length data. If it's a short length, we're
71  done */
72  status = dataLength = sgetc( stream );
73  if( cryptStatusError( status ) )
74  return( status );
75  if( !( dataLength & 0x80 ) )
76  {
77  *length = dataLength;
78  return( CRYPT_OK );
79  }
80 
81  /* Read the actual length octets */
82  noLengthOctets = dataLength & 0x7F;
83  if( noLengthOctets <= 0 )
84  {
85  /* If indefinite lengths aren't allowed, signal an error */
86  if( readType != READLENGTH_SHORT_INDEF && \
87  readType != READLENGTH_LONG_INDEF )
88  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
89 
90  /* It's an indefinite length encoding, we're done */
91  *length = CRYPT_UNUSED;
92 
93  return( CRYPT_OK );
94  }
95  if( noLengthOctets > 8 )
96  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
97  status = sread( stream, buffer, noLengthOctets );
98  if( cryptStatusError( status ) )
99  return( status );
100 
101  /* Handle leading zero octets. Since BER lengths can be encoded in
102  peculiar ways (at least one text uses a big-endian 32-bit encoding
103  for everything) we allow up to 8 bytes of non-DER length data, but
104  only the last 2 or 4 of these (for short or long lengths
105  respectively) can be nonzero */
106  if( buffer[ 0 ] == 0 )
107  {
108  /* Oddball length encoding with leading zero(es) */
109  for( i = 0; i < noLengthOctets && buffer[ i ] == 0; i++ );
110  noLengthOctets -= i;
111  if( noLengthOctets <= 0 )
112  return( 0 ); /* Very broken encoding of a zero length */
113  bufPtr += i; /* Skip leading zero(es) */
114  }
115 
116  /* Make sure that the length size is reasonable */
117  if( noLengthOctets < 0 || noLengthOctets > ( shortLen ? 2 : 4 ) )
118  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
119 
120  /* Read and check the length value */
121  for( dataLength = 0, i = 0; i < noLengthOctets; i++ )
122  {
123  const long dataLenTmp = dataLength << 8;
124  const int data = byteToInt( bufPtr[ i ] );
125 
126  if( dataLength >= ( MAX_INTLENGTH >> 8 ) || \
127  dataLenTmp >= MAX_INTLENGTH - data )
128  {
129  /* Integer overflow */
130  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
131  }
132  dataLength = dataLenTmp | data;
133  if( dataLength <= 0 || dataLength >= MAX_INTLENGTH )
134  {
135  /* Integer overflow */
136  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
137  }
138  }
139  if( shortLen )
140  {
141  if( dataLength & 0xFFFF8000UL || dataLength > 32767L )
142  {
143  /* Length must be < 32K for short lengths */
144  return( sSetError( stream, CRYPT_ERROR_OVERFLOW ) );
145  }
146  }
147  else
148  {
149  if( ( dataLength & 0x80000000UL ) || dataLength >= MAX_INTLENGTH )
150  {
151  /* Length must be < MAX_INTLENGTH for standard data */
152  return( sSetError( stream, CRYPT_ERROR_OVERFLOW ) );
153  }
154  }
155  if( dataLength <= 0 )
156  {
157  /* Shouldn't happen since the overflow check above catches it, but we
158  check again just to be safe */
159  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
160  }
161  ENSURES_S( dataLength > 0 && dataLength < MAX_INTLENGTH );
162  *length = dataLength;
163 
164  return( CRYPT_OK );
165  }
166 
167 /* Read the header for a (signed) integer value */
168 
170 static int readIntegerHeader( INOUT STREAM *stream,
171  IN_TAG_EXT const int tag )
172  {
173  long length;
174  int noLeadingZeroes, status;
175 
176  assert( isWritePtr( stream, sizeof( STREAM ) ) );
177 
178  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
179  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
180 
181  /* Read the identifier field if necessary and the length */
182  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_INTEGER ) )
183  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
184  status = readLengthValue( stream, &length, READLENGTH_SHORT );
185  if( cryptStatusError( status ) )
186  return( status );
187  if( length <= 0 )
188  return( 0 ); /* Zero-length data */
189 
190  /* ASN.1 encoded values are signed while the internal representation is
191  unsigned so we skip any leading zero bytes needed to encode a value
192  that has the high bit set. If we get a value with the (supposed)
193  sign bit set we treat it as an unsigned value since a number of
194  implementations get this wrong. As with length encodings, we allow
195  up to 8 bytes of non-DER leading zeroes */
196  for( noLeadingZeroes = 0;
197  noLeadingZeroes < length && noLeadingZeroes < 8 && \
198  sPeek( stream ) == 0;
199  noLeadingZeroes++ )
200  {
201  status = sgetc( stream );
202  if( cryptStatusError( status ) )
203  return( status );
204  ENSURES_S( status == 0 );
205  }
206  if( noLeadingZeroes >= 8 )
207  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
208 
209  return( length - noLeadingZeroes );
210  }
211 
212 /* Read a (non-bignum) numeric value, used by several routines */
213 
215 static int readNumeric( INOUT STREAM *stream, OUT_OPT_LENGTH_Z long *value )
216  {
217  BYTE buffer[ 4 + 8 ];
218  long localValue;
219  int length, i, status;
220 
221  assert( isWritePtr( stream, sizeof( STREAM ) ) );
222  assert( value == NULL || isWritePtr( value, sizeof( long ) ) );
223 
224  /* Clear return value */
225  if( value != NULL )
226  *value = 0L;
227 
228  /* Read the length field and make sure that it's a non-bignum value */
229  status = length = readIntegerHeader( stream, NO_TAG );
230  if( cryptStatusError( status ) )
231  return( status );
232  if( length <= 0 )
233  return( 0 ); /* Zero-length data */
234  if( length > 4 )
235  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
236 
237  /* Read the data */
238  status = sread( stream, buffer, length );
239  if( cryptStatusError( status ) || value == NULL )
240  return( status );
241  for( localValue = 0, i = 0; i < length; i++ )
242  {
243  const long localValTmp = localValue << 8;
244  const int data = byteToInt( buffer[ i ] );
245 
246  if( localValue >= ( MAX_INTLENGTH >> 8 ) || \
247  localValTmp >= MAX_INTLENGTH - data )
248  {
249  /* Integer overflow */
250  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
251  }
252  localValue = localValTmp | data;
253  if( localValue < 0 || localValue >= MAX_INTLENGTH )
254  {
255  /* Integer overflow */
256  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
257  }
258  }
259  if( value != NULL )
260  *value = localValue;
261  return( CRYPT_OK );
262  }
263 
264 /* Read a constrained-length data value, used by several routines */
265 
267 static int readConstrainedData( INOUT STREAM *stream,
268  OUT_BUFFER_OPT( bufferMaxLength, \
269  *bufferLength ) BYTE *buffer,
270  IN_LENGTH_SHORT const int bufferMaxLength,
272  IN_LENGTH const int length )
273  {
274  int dataLength = length, remainder = 0, status;
275 
276  assert( isWritePtr( stream, sizeof( STREAM ) ) );
277  assert( buffer == NULL || isWritePtr( buffer, length ) );
278  assert( isWritePtr( bufferLength, sizeof( int ) ) );
279 
280  REQUIRES_S( bufferMaxLength > 0 && \
281  bufferMaxLength < MAX_INTLENGTH_SHORT );
282  REQUIRES_S( length > 0 && length < MAX_INTLENGTH_SHORT );
283 
284  /* Clear return value */
285  *bufferLength = dataLength;
286 
287  /* If we don't care about the return value, skip it and exit */
288  if( buffer == NULL )
289  return( sSkip( stream, dataLength ) );
290 
291  /* Read the object, limiting the size to the maximum buffer size */
292  if( dataLength > bufferMaxLength )
293  {
294  remainder = dataLength - bufferMaxLength;
295  dataLength = bufferMaxLength;
296  *bufferLength = dataLength;
297  }
298  status = sread( stream, buffer, dataLength );
299  if( cryptStatusError( status ) )
300  return( status );
301 
302  /* If there's no data remaining, we're done */
303  if( remainder <= 0 )
304  return( CRYPT_OK );
305 
306  /* Skip any remaining data */
307  return( sSkip( stream, remainder ) );
308  }
309 
310 /****************************************************************************
311 * *
312 * Read Routines for Primitive Objects *
313 * *
314 ****************************************************************************/
315 
316 /* Read a tag and make sure that it's (approximately) valid */
317 
318 CHECK_RETVAL_BOOL \
319 static BOOLEAN checkTag( IN_TAG_ENCODED const int tag )
320  {
321  /* Make sure that it's (approximately) valid: Not an EOC, and within the
322  allowed range */
323  if( tag <= 0 || tag > MAX_TAG )
324  return( FALSE );
325 
326  /* Make sure that it's not an application-specific or private tag */
327  if( ( tag & BER_CLASS_MASK ) == BER_APPLICATION ||
328  ( tag & BER_CLASS_MASK ) == BER_PRIVATE )
329  return( FALSE );
330 
331  /* If its's a context-specific tag make sure that the tag value is
332  within the allowed range */
333  if( ( tag & BER_CLASS_MASK ) == BER_CONTEXT_SPECIFIC && \
334  ( tag & BER_SHORT_ID_MASK ) > MAX_CTAG_VALUE )
335  return( FALSE );
336 
337  return( TRUE );
338  }
339 
341 int readTag( INOUT STREAM *stream )
342  {
343  int tag;
344 
345  /* Read the tag */
346  tag = sgetc( stream );
347  if( cryptStatusError( tag ) )
348  return( tag );
349  if( !checkTag( tag ) )
350  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
351  return( tag );
352  }
353 
355 int peekTag( INOUT STREAM *stream )
356  {
357  int tag;
358 
359  /* Peek at the tag value */
360  tag = sPeek( stream );
361  if( cryptStatusError( tag ) )
362  return( tag );
363  if( !checkTag( tag ) )
364  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
365  return( tag );
366  }
367 
368 /* Check for constructed data end-of-contents octets. Note that this
369  is a standard integer-return function that can return either a boolean
370  TRUE/FALSE or alternatively a stream error code if there's a problem, so
371  it's not a purely boolean function */
372 
374 int checkEOC( INOUT STREAM *stream )
375  {
376  BYTE eocBuffer[ 2 + 8 ];
377  int tag, status;
378 
379  assert( isWritePtr( stream, sizeof( STREAM ) ) );
380 
381  /* Read the tag and check for an EOC octet pair. Note that we can't use
382  peekTag()/readTag() for this because an EOC isn't a valid tag */
383  tag = sPeek( stream );
384  if( cryptStatusError( tag ) )
385  return( tag );
386  if( tag != BER_EOC )
387  return( FALSE );
388  status = sread( stream, eocBuffer, 2 );
389  if( cryptStatusError( status ) )
390  return( status );
391  if( memcmp( eocBuffer, "\x00\x00", 2 ) )
392  {
393  /* After finding an EOC tag we need to have a length of zero */
394  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
395  }
396 
397  return( TRUE );
398  }
399 
400 /* Read a short (<= 256 bytes) raw object without decoding it. This is used
401  to read short data blocks like object identifiers, which are only ever
402  handled in encoded form */
403 
405 int readRawObject( INOUT STREAM *stream,
406  OUT_BUFFER( bufferMaxLength, *bufferLength ) BYTE *buffer,
407  IN_LENGTH_SHORT_MIN( 3 ) const int bufferMaxLength,
409  IN_TAG_ENCODED const int tag )
410  {
411  int length, offset = 0;
412 
413  assert( isWritePtr( stream, sizeof( STREAM ) ) );
414  assert( isWritePtr( buffer, bufferMaxLength ) );
415  assert( isWritePtr( bufferLength, sizeof( int ) ) );
416 
417  REQUIRES_S( bufferMaxLength >= 3 && \
418  bufferMaxLength < MAX_INTLENGTH_SHORT );
419  /* Need to be able to write at least the tag, length, and
420  one byte of content */
421  REQUIRES_S( ( tag == NO_TAG ) || ( tag >= 1 && tag <= MAX_TAG ) );
422  /* Note tag != 0 */
423 
424  /* Clear return values */
425  memset( buffer, 0, min( 16, bufferMaxLength ) );
426  *bufferLength = 0;
427 
428  /* Read the identifier field and length. We need to remember each byte
429  as it's read so we can't just call readLengthValue() for the length,
430  but since we only need to handle lengths that can be encoded in one
431  or two bytes this isn't a problem. Since this function reads a
432  complete encoded object, the tag (if known) must be specified so
433  there's no capability to use DEFAULT_TAG */
434  if( tag != NO_TAG )
435  {
436  const int objectTag = readTag( stream );
437  if( cryptStatusError( objectTag ) )
438  return( objectTag );
439  if( tag != objectTag )
440  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
441  buffer[ offset++ ] = objectTag;
442  }
443  length = sgetc( stream );
444  if( cryptStatusError( length ) )
445  return( length );
446  buffer[ offset++ ] = length;
447  if( length & 0x80 )
448  {
449  /* If the object is indefinite-length or longer than 256 bytes (i.e.
450  the length-of-length is anything other than 1) we don't want to
451  handle it */
452  if( length != 0x81 )
453  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
454  length = sgetc( stream );
455  if( cryptStatusError( length ) )
456  return( length );
457  buffer[ offset++ ] = length;
458  }
459  if( length <= 0 || length > 0xFF )
460  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
461  if( offset + length > bufferMaxLength )
462  {
463  /* We treat this as a stream error even though technically it's an
464  insufficient-buffer-space error because the data object has
465  violated the implicit format constraint of being larger than the
466  maximum size specified by the caller */
467  return( sSetError( stream, CRYPT_ERROR_OVERFLOW ) );
468  }
469 
470  /* Read in the rest of the data */
471  *bufferLength = offset + length;
472  return( sread( stream, buffer + offset, length ) );
473  }
474 
475 /* Read a large integer value */
476 
477 RETVAL STDC_NONNULL_ARG( ( 1, 4 ) ) \
478 int readIntegerTag( INOUT STREAM *stream,
483  IN_TAG_EXT const int tag )
484  {
485  int localIntegerLength, length, status;
486 
487  assert( isWritePtr( stream, sizeof( STREAM ) ) );
488  assert( integer == NULL || isWritePtr( integer, integerMaxLength ) );
489  assert( integerLength == NULL || \
490  isWritePtr( integerLength, sizeof( int ) ) );
491 
492  REQUIRES_S( integerMaxLength > 0 && \
493  integerMaxLength < MAX_INTLENGTH_SHORT );
494  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
495  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
496 
497  /* Clear return values */
498  if( integer != NULL )
499  memset( integer, 0, min( 16, integerMaxLength ) );
500  if( integerLength != NULL )
501  *integerLength = 0;
502 
503  /* Read the integer header info */
504  status = length = readIntegerHeader( stream, tag );
505  if( cryptStatusError( status ) )
506  return( status );
507  if( length <= 0 )
508  return( 0 ); /* Zero-length data */
509 
510  /* Read in the numeric value, limiting the size to the maximum buffer
511  size. This is safe because the only situation where this can occur
512  is when we're reading some blob (whose value we don't care about)
513  dressed up as an integer rather than for any real integer */
514  status = readConstrainedData( stream, integer, integerMaxLength,
515  &localIntegerLength, length );
516  if( cryptStatusOK( status ) && integerLength != NULL )
517  *integerLength = localIntegerLength;
518  return( status );
519  }
520 
521 #ifdef USE_PKC
522 
523 /* Read a bignum integer value */
524 
525 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
526 static int readBignumInteger( INOUT STREAM *stream,
527  INOUT TYPECAST( BIGNUM * ) void *bignum,
528  IN_LENGTH_PKC const int minLength,
529  IN_LENGTH_PKC const int maxLength,
530  IN_OPT TYPECAST( BIGNUM * ) const void *maxRange,
531  IN_TAG_EXT const int tag,
532  IN_ENUM_OPT( KEYSIZE_CHECK ) \
533  const KEYSIZE_CHECK_TYPE checkType )
534  {
535  BYTE buffer[ CRYPT_MAX_PKCSIZE + 8 ];
536  int length, status;
537 
538  assert( isWritePtr( stream, sizeof( STREAM ) ) );
539  assert( isWritePtr( bignum, sizeof( BIGNUM ) ) );
540  assert( maxRange == NULL || isReadPtr( maxRange, sizeof( BIGNUM ) ) );
541 
542  REQUIRES_S( minLength > 0 && minLength <= maxLength && \
543  maxLength <= CRYPT_MAX_PKCSIZE );
544  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
545  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
546  REQUIRES_S( checkType >= KEYSIZE_CHECK_NONE && \
547  checkType < KEYSIZE_CHECK_LAST );
548 
549  /* Read the integer header info */
550  status = length = readIntegerHeader( stream, tag );
551  if( cryptStatusError( status ) )
552  return( status );
553  if( length <= 0 )
554  {
555  /* It's a read of a zero value, make it explicit */
556  BN_zero( bignum );
557 
558  return( CRYPT_OK );
559  }
560 
561  /* Read the value into a fixed buffer */
562  if( length > CRYPT_MAX_PKCSIZE )
563  return( sSetError( stream, CRYPT_ERROR_OVERFLOW ) );
564  status = sread( stream, buffer, length );
565  if( cryptStatusError( status ) )
566  return( status );
567  status = importBignum( bignum, buffer, length, minLength, maxLength,
568  maxRange, checkType );
569  if( cryptStatusError( status ) )
570  status = sSetError( stream, status );
571  zeroise( buffer, CRYPT_MAX_PKCSIZE );
572  return( status );
573  }
574 
575 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
576 int readBignumTag( INOUT STREAM *stream,
577  INOUT TYPECAST( BIGNUM * ) void *bignum,
578  IN_LENGTH_PKC const int minLength,
579  IN_LENGTH_PKC const int maxLength,
580  IN_OPT TYPECAST( BIGNUM * ) const void *maxRange,
581  IN_TAG_EXT const int tag )
582  {
583  return( readBignumInteger( stream, bignum, minLength, maxLength,
584  maxRange, tag, KEYSIZE_CHECK_NONE ) );
585  }
586 
587 /* Special-case bignum read routine that explicitly checks for a too-short
588  key and returns CRYPT_ERROR_NOSECURE rather than the CRYPT_ERROR_BADDATA
589  that'd otherwise be returned */
590 
591 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
592 int readBignumChecked( INOUT STREAM *stream,
593  INOUT TYPECAST( BIGNUM * ) void *bignum,
594  IN_LENGTH_PKC const int minLength,
595  IN_LENGTH_PKC const int maxLength,
596  IN_OPT TYPECAST( BIGNUM * ) const void *maxRange )
597  {
598  return( readBignumInteger( stream, bignum, minLength, maxLength,
599  maxRange, DEFAULT_TAG, KEYSIZE_CHECK_PKC ) );
600  }
601 #endif /* USE_PKC */
602 
603 /* Read a universal type and discard it (used to skip unknown or unwanted
604  types) */
605 
606 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
607 int readUniversalData( INOUT STREAM *stream )
608  {
609  long length;
610  int status;
611 
612  assert( isWritePtr( stream, sizeof( STREAM ) ) );
613 
614  status = readLengthValue( stream, &length, READLENGTH_SHORT );
615  if( cryptStatusError( status ) )
616  return( status );
617  if( length <= 0 )
618  return( CRYPT_OK ); /* Zero-length data */
619  return( sSkip( stream, length ) );
620  }
621 
622 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
623 int readUniversal( INOUT STREAM *stream )
624  {
625  assert( isWritePtr( stream, sizeof( STREAM ) ) );
626 
627  readTag( stream );
628  return( readUniversalData( stream ) );
629  }
630 
631 /* Read a short integer value */
632 
633 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
634 int readShortIntegerTag( INOUT STREAM *stream,
635  OUT_OPT_INT_Z long *value,
636  IN_TAG_EXT const int tag )
637  {
638  assert( isWritePtr( stream, sizeof( STREAM ) ) );
639  assert( value == NULL || isWritePtr( value, sizeof( long ) ) );
640 
641  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
642  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
643 
644  /* Clear return value */
645  if( value != NULL )
646  *value = 0L;
647 
648  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_INTEGER ) )
649  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
650  return( readNumeric( stream, value ) );
651  }
652 
653 /* Read an enumerated value. This is encoded like an ASN.1 integer so we
654  just read it as such */
655 
656 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
657 int readEnumeratedTag( INOUT STREAM *stream,
659  IN_TAG_EXT const int tag )
660  {
661  long value;
662  int status;
663 
664  assert( isWritePtr( stream, sizeof( STREAM ) ) );
665  assert( enumeration == NULL || \
666  isWritePtr( enumeration, sizeof( int ) ) );
667 
668  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
669  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
670 
671  /* Clear return value */
672  if( enumeration != NULL )
673  *enumeration = 0;
674 
675  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_ENUMERATED ) )
676  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
677  status = readNumeric( stream, &value );
678  if( cryptStatusError( status ) )
679  return( status );
680  if( value < 0 || value > 1000 )
681  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
682  if( enumeration != NULL )
683  *enumeration = ( int ) value;
684 
685  return( CRYPT_OK );
686  }
687 
688 /* Read a null value */
689 
690 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
691 int readNullTag( INOUT STREAM *stream, IN_TAG_EXT const int tag )
692  {
693  int value;
694 
695  assert( isWritePtr( stream, sizeof( STREAM ) ) );
696 
697  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
698  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
699 
700  /* Read the identifier if necessary */
701  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_NULL ) )
702  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
703  value = sgetc( stream );
704  if( cryptStatusError( value ) )
705  return( value );
706  if( value != 0 )
707  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
708  return( CRYPT_OK );
709  }
710 
711 /* Read a boolean value */
712 
713 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
714 int readBooleanTag( INOUT STREAM *stream,
715  OUT_OPT_BOOL BOOLEAN *boolean,
716  IN_TAG_EXT const int tag )
717  {
718  BYTE buffer[ 2 + 8 ];
719  int status;
720 
721  assert( isWritePtr( stream, sizeof( STREAM ) ) );
722  assert( boolean == NULL || \
723  isWritePtr( boolean, sizeof( BOOLEAN ) ) );
724 
725  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
726  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
727 
728  /* Clear return value */
729  if( boolean != NULL )
730  *boolean = FALSE;
731 
732  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_BOOLEAN ) )
733  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
734  status = sread( stream, buffer, 2 );
735  if( cryptStatusError( status ) )
736  return( status );
737  if( buffer[ 0 ] != 1 )
738  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
739  if( boolean != NULL )
740  *boolean = ( buffer[ 1 ] != 0 ) ? TRUE : FALSE;
741  return( CRYPT_OK );
742  }
743 
744 /* Read an OID and check it against a permitted value or a selection of
745  permitted values */
746 
747 RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
748 int readOIDEx( INOUT STREAM *stream,
749  IN_ARRAY( noOidSelectionEntries ) const OID_INFO *oidSelection,
750  IN_RANGE( 1, 50 ) const int noOidSelectionEntries,
752  {
753  static const OID_INFO nullOidSelection = { NULL, CRYPT_ERROR, NULL };
754  BYTE buffer[ MAX_OID_SIZE + 8 ];
755  int length, oidEntry, iterationCount, status;
756 
757  assert( isWritePtr( stream, sizeof( STREAM ) ) );
758  assert( isReadPtr( oidSelection, \
759  sizeof( OID_INFO ) * noOidSelectionEntries ) );
760  assert( oidSelectionValue == NULL || \
761  isReadPtr( oidSelectionValue, sizeof( OID_INFO * ) ) );
762 
763  REQUIRES_S( noOidSelectionEntries > 0 && noOidSelectionEntries <= 50 );
764 
765  /* Clear return value */
766  if( oidSelectionValue != NULL )
767  *oidSelectionValue = &nullOidSelection;
768 
769  /* Read the OID data */
770  status = readRawObject( stream, buffer, MAX_OID_SIZE, &length,
772  if( cryptStatusError( status ) )
773  return( status );
774  ENSURES_S( length == sizeofOID( buffer ) );
775 
776  /* Try and find the entry for the OID. Since related groups of OIDs
777  typically have identical lengths, we use the last byte of the OID
778  as a quick-reject check to avoid performing a full OID comparison
779  for each entry */
780  for( oidEntry = 0, iterationCount = 0;
781  oidEntry < noOidSelectionEntries && \
782  oidSelection[ oidEntry ].oid != NULL && \
783  iterationCount < FAILSAFE_ITERATIONS_MED;
784  oidEntry++, iterationCount++ )
785  {
786  const BYTE *oidPtr = oidSelection[ oidEntry ].oid;
787  const int oidLength = sizeofOID( oidPtr );
788 
789  /* Check for a match-any wildcard OID */
790  if( oidLength == WILDCARD_OID_SIZE && \
791  !memcmp( oidPtr, WILDCARD_OID, WILDCARD_OID_SIZE ) )
792  {
793  /* The wildcard must be the last entry in the list */
794  ENSURES_S( oidEntry + 1 < noOidSelectionEntries && \
795  oidSelection[ oidEntry + 1 ].oid == NULL );
796  break;
797  }
798 
799  /* Check for a standard OID match */
800  if( length == oidLength && \
801  buffer[ length - 1 ] == oidPtr[ length - 1 ] && \
802  !memcmp( buffer, oidPtr, length ) )
803  break;
804  }
805  ENSURES_S( iterationCount < FAILSAFE_ITERATIONS_MED );
806  if( oidEntry >= noOidSelectionEntries || \
807  oidSelection[ oidEntry ].oid == NULL )
808  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
809 
810  if( oidSelectionValue != NULL )
811  *oidSelectionValue = &oidSelection[ oidEntry ];
812  return( CRYPT_OK );
813  }
814 
815 RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
816 int readOID( INOUT STREAM *stream,
817  IN_ARRAY( noOidSelectionEntries ) const OID_INFO *oidSelection,
818  IN_RANGE( 1, 50 ) const int noOidSelectionEntries,
820  noOidSelectionEntries ) int *selectionID )
821  {
822  const OID_INFO *oidSelectionInfo;
823  int status;
824 
825  assert( isWritePtr( stream, sizeof( STREAM ) ) );
826  assert( isReadPtr( oidSelection, \
827  sizeof( OID_INFO ) * noOidSelectionEntries ) );
828  assert( isWritePtr( selectionID, sizeof( int ) ) );
829 
830  REQUIRES_S( noOidSelectionEntries > 0 && noOidSelectionEntries <= 50 );
831 
832  /* Clear return value */
833  *selectionID = CRYPT_ERROR;
834 
835  status = readOIDEx( stream, oidSelection, noOidSelectionEntries,
836  &oidSelectionInfo );
837  if( cryptStatusOK( status ) )
838  *selectionID = oidSelectionInfo->selectionID;
839  return( status );
840  }
841 
842 RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
843 int readFixedOID( INOUT STREAM *stream,
844  IN_BUFFER( oidLength ) const BYTE *oid,
845  IN_LENGTH_OID const int oidLength )
846  {
847  CONST_INIT_STRUCT_A2( OID_INFO oidInfo[ 3 ], oid, NULL );
848 
849  assert( isWritePtr( stream, sizeof( STREAM ) ) );
850  assert( isReadPtr( oid, oidLength ) && \
851  oidLength == sizeofOID( oid ) && \
852  oid[ 0 ] == BER_OBJECT_IDENTIFIER );
853 
854  REQUIRES_S( oidLength >= MIN_OID_SIZE && oidLength <= MAX_OID_SIZE );
855  /* Must be first for static analysis tools */
856  REQUIRES_S( oidLength == sizeofOID( oid ) && \
857  oid[ 0 ] == BER_OBJECT_IDENTIFIER );
858 
859  /* Set up a one-entry OID_INFO list to pass down to readOID() */
860  CONST_SET_STRUCT_A( memset( oidInfo, 0, sizeof( OID_INFO ) * 3 ); \
861  oidInfo[ 0 ].oid = oid );
862  return( readOIDEx( stream, oidInfo, 3, NULL ) );
863  }
864 
865 /* Read a raw OID in encoded form */
866 
867 RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
868 int readEncodedOID( INOUT STREAM *stream,
869  OUT_BUFFER( oidMaxLength, *oidLength ) BYTE *oid,
870  IN_LENGTH_SHORT_MIN( 5 ) const int oidMaxLength,
871  OUT_LENGTH_SHORT_Z int *oidLength,
872  IN_TAG_ENCODED const int tag )
873  {
874  int length, status;
875 
876  assert( isWritePtr( stream, sizeof( STREAM ) ) );
877  assert( isWritePtr( oid, oidMaxLength ) );
878  assert( isWritePtr( oidLength, sizeof( int ) ) );
879 
880  REQUIRES_S( oidMaxLength >= MIN_OID_SIZE && \
881  oidMaxLength < MAX_INTLENGTH_SHORT );
882  REQUIRES_S( tag == NO_TAG || tag == BER_OBJECT_IDENTIFIER );
883 
884  /* Clear return values */
885  memset( oid, 0, min( 16, oidMaxLength ) );
886  *oidLength = 0;
887 
888  /* Read the encoded OID and make sure that it's the right size for a
889  minimal-length OID: tag (optional) + length + minimal-length OID
890  data */
891  status = readRawObject( stream, oid, oidMaxLength, &length, tag );
892  if( cryptStatusError( status ) )
893  return( status );
894  if( length < ( tag == NO_TAG ? 0 : 1 ) + 1 + 3 || length > oidMaxLength )
895  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
896  *oidLength = length;
897  return( CRYPT_OK );
898  }
899 
900 /* Read an octet string value */
901 
903 static int readString( INOUT STREAM *stream,
904  OUT_BUFFER_OPT( maxLength, *stringLength ) BYTE *string,
906  IN_LENGTH_SHORT const int minLength,
907  IN_LENGTH_SHORT const int maxLength,
908  IN_TAG_EXT const int tag,
909  const BOOLEAN isOctetString )
910  {
911  long length;
912  int status;
913 
914  assert( isWritePtr( stream, sizeof( STREAM ) ) );
915  assert( string == NULL || isWritePtr( string, maxLength ) );
916  assert( isWritePtr( stringLength, sizeof( int ) ) );
917 
918  REQUIRES_S( minLength > 0 && minLength <= maxLength && \
919  maxLength < MAX_INTLENGTH_SHORT );
920  REQUIRES_S( ( isOctetString && \
921  ( tag == NO_TAG || tag == DEFAULT_TAG ) ) || \
922  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
923 
924  /* Clear return values */
925  if( string != NULL )
926  memset( string, 0, min( 16, maxLength ) );
927  *stringLength = 0;
928 
929  /* Read the string, limiting the size to the maximum buffer size. If
930  it's an octet string we make this a hard limit, however if it's a
931  text string we simply read as much as will fit in the buffer and
932  discard the rest. This is required to handle the widespread ignoring
933  of string length limits in certificates and other PKI-related data */
934  if( isOctetString )
935  {
936  if( tag != NO_TAG && \
937  readTag( stream ) != selectTag( tag, BER_OCTETSTRING ) )
938  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
939  }
940  else
941  {
942  if( readTag( stream ) != tag )
943  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
944  }
945  status = readLengthValue( stream, &length, READLENGTH_SHORT );
946  if( cryptStatusError( status ) )
947  return( status );
948  if( length < minLength )
949  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
950  if( isOctetString && length > maxLength )
951  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
952  if( length <= 0 )
953  return( CRYPT_OK ); /* Zero-length string */
954  return( readConstrainedData( stream, string, maxLength, stringLength,
955  length ) );
956  }
957 
958 RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
959 int readOctetStringTag( INOUT STREAM *stream,
960  OUT_BUFFER( maxLength, *stringLength ) BYTE *string,
962  IN_LENGTH_SHORT const int minLength,
963  IN_LENGTH_SHORT const int maxLength,
964  IN_TAG_EXT const int tag )
965  {
966 
967  assert( isWritePtr( stream, sizeof( STREAM ) ) );
968  assert( string == NULL || isWritePtr( string, maxLength ) );
969  assert( stringLength == NULL || \
970  isWritePtr( stringLength, sizeof( int ) ) );
971 
972  REQUIRES_S( minLength > 0 && minLength <= maxLength && \
973  maxLength < MAX_INTLENGTH_SHORT );
974  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
975  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
976 
977  return( readString( stream, string, stringLength, minLength, maxLength,
978  tag, TRUE ) );
979  }
980 
981 /* Read a character string. This handles any of the myriad ASN.1 character
982  string types. The handling of the tag works somewhat differently here to
983  the usual manner in that since the function is polymorphic, the tag
984  defines the character string type and is always used (there's no
985  NO_TAG or DEFAULT_TAG option like the other functions use). This works
986  because the plethora of string types means that the higher-level routines
987  that read them invariably have to sort out the valid tag types
988  themselves */
989 
990 RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
991 int readCharacterString( INOUT STREAM *stream,
992  OUT_BUFFER( stringMaxLength, *stringLength ) void *string,
993  IN_LENGTH_SHORT const int stringMaxLength,
995  IN_TAG_EXT const int tag )
996  {
997  assert( isWritePtr( stream, sizeof( STREAM ) ) );
998  assert( string == NULL || isWritePtr( string, stringMaxLength ) );
999  assert( stringLength == NULL || \
1000  isWritePtr( stringLength, sizeof( int ) ) );
1001 
1002  REQUIRES_S( stringMaxLength > 0 && \
1003  stringMaxLength < MAX_INTLENGTH_SHORT );
1004  REQUIRES_S( tag >= 0 && tag < MAX_TAG_VALUE );
1005 
1006  return( readString( stream, string, stringLength, 1, stringMaxLength,
1007  tag, FALSE ) );
1008  }
1009 
1010 /* Read a bit string */
1011 
1012 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1013 int readBitStringTag( INOUT STREAM *stream,
1014  OUT_OPT_INT_Z int *bitString,
1015  IN_TAG_EXT const int tag )
1016  {
1017  int length, data, mask, flag, value = 0, noBits, i;
1018 
1019  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1020  assert( bitString == NULL || isWritePtr( bitString, sizeof( int ) ) );
1021 
1022  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
1023  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1024 
1025  /* Clear return value */
1026  if( bitString != NULL )
1027  *bitString = 0;
1028 
1029  /* Make sure that we have a bitstring with between 0 and sizeof( int )
1030  bits. This isn't as machine-dependant as it seems, the only place
1031  where bit strings longer than one or two bytes are used is with CMP's
1032  bizarre encoding of error subcodes that just provide further
1033  information above and beyond the main error code and text message,
1034  and CMP is highly unlikely to be used on a 16-bit machine */
1035  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_BITSTRING ) )
1036  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1037  length = sgetc( stream );
1038  if( cryptStatusError( length ) )
1039  return( length );
1040  length--; /* Adjust for bit count */
1041  if( length < 0 || length > 4 || length > sizeof( int ) )
1042  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1043  noBits = sgetc( stream );
1044  if( cryptStatusError( noBits ) )
1045  return( noBits );
1046  if( noBits < 0 || noBits > 7 )
1047  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1048  if( length <= 0 )
1049  return( CRYPT_OK ); /* Zero value */
1050  ENSURES_S( length >= 1 && length <= min( 4, sizeof( int ) ) );
1051  ENSURES_S( noBits >= 0 && noBits <= 7 );
1052 
1053  /* Convert the bit count from the unused-remainder bit count into the
1054  total bit count */
1055  noBits = ( length * 8 ) - noBits;
1056  ENSURES_S( noBits >= 0 && noBits <= 32 );
1057 
1058  /* ASN.1 bitstrings start at bit 0 so we need to reverse the order of
1059  the bits before we return the value. This uses a straightforward way
1060  of doing it rather than the more efficient but hard-to-follow:
1061 
1062  data = ( data & 0x55555555 ) << 1 | ( data >> 1 ) & 0x55555555;
1063  data = ( data & 0x33333333 ) << 2 | ( data >> 2 ) & 0x33333333;
1064  data = ( data & 0x0F0F0F0F ) << 4 | ( data >> 4 ) & 0x0F0F0F0F;
1065  data = ( data << 24 ) | ( ( data & 0xFF00 ) << 8 ) | \
1066  ( ( data >> 8 ) & 0xFF00 || ( data >> 24 );
1067 
1068  which swaps adjacent bits, then 2-bit fields, then 4-bit fields, and
1069  so on */
1070  data = sgetc( stream );
1071  if( cryptStatusError( data ) )
1072  return( data );
1073  for( mask = 0x80, i = 1; i < length; mask <<= 8, i++ )
1074  {
1075  const long dataValTmp = data << 8;
1076  const int dataTmp = sgetc( stream );
1077 
1078  if( cryptStatusError( dataTmp ) )
1079  return( dataTmp );
1080  if( data >= ( MAX_INTLENGTH >> 8 ) || \
1081  dataValTmp >= MAX_INTLENGTH - data )
1082  {
1083  /* Integer overflow */
1084  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1085  }
1086  data = dataValTmp | dataTmp;
1087  if( data < 0 || data >= MAX_INTLENGTH )
1088  {
1089  /* Integer overflow */
1090  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1091  }
1092  }
1093  for( flag = 1, i = 0; i < noBits; flag <<= 1, i++ )
1094  {
1095  if( data & mask )
1096  value |= flag;
1097  data <<= 1;
1098  }
1099  if( bitString != NULL )
1100  {
1102  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1103  *bitString = value;
1104  }
1105 
1106  return( CRYPT_OK );
1107  }
1108 
1109 /* Read a UTCTime and GeneralizedTime value */
1110 
1111 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1112 static int readTime( INOUT STREAM *stream, OUT time_t *timePtr,
1113  const BOOLEAN isUTCTime )
1114  {
1115  BYTE buffer[ 16 + 8 ], *bufPtr = buffer;
1116  struct tm theTime, gmTimeInfo, *gmTimeInfoPtr = &gmTimeInfo;
1117  time_t utcTime, gmTime;
1118  int value = 0, length, i, status;
1119 
1120  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1121  assert( isWritePtr( timePtr, sizeof( time_t ) ) );
1122 
1123  /* Clear return value */
1124  *timePtr = 0;
1125 
1126  /* Read the length field and make sure that it's of the correct size.
1127  There's only one encoding allowed although in theory the encoded
1128  value could range in length from 11 to 17 bytes for UTCTime and 13 to
1129  19 bytes for GeneralizedTime. We formerly also allowed 11-byte
1130  UTCTimes because an obsolete encoding rule allowed the time to be
1131  encoded without seconds and Sweden Post hadn't realised that this had
1132  changed yet, but these certs have now expired */
1133  length = sgetc( stream );
1134  if( cryptStatusError( length ) )
1135  return( length );
1136  if( ( isUTCTime && length != 13 ) || ( !isUTCTime && length != 15 ) )
1137  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1138  ENSURES_S( length == 13 || length == 15 );
1139 
1140  /* Read the encoded time data and make sure that the contents are
1141  valid */
1142  memset( buffer, 0, 16 );
1143  status = sread( stream, buffer, length );
1144  if( cryptStatusError( status ) )
1145  return( status );
1146  for( i = 0; i < length - 1; i++ )
1147  {
1148  if( !isDigit( buffer[ i ] ) )
1149  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1150  }
1151  if( buffer[ length - 1 ] != 'Z' )
1152  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1153 
1154  /* Decode the time fields */
1155  memset( &theTime, 0, sizeof( struct tm ) );
1156  theTime.tm_isdst = -1; /* Get the system to adjust for DST */
1157  if( !isUTCTime )
1158  {
1159  status = strGetNumeric( bufPtr, 2, &value, 19, 20 );
1160  if( cryptStatusError( status ) )
1161  return( status );
1162  value = ( value - 19 ) * 100; /* Adjust for the century */
1163  bufPtr += 2;
1164  }
1165  status = strGetNumeric( bufPtr, 2, &theTime.tm_year, 0, 99 );
1166  if( cryptStatusOK( status ) )
1167  {
1168  theTime.tm_year += value;
1169  status = strGetNumeric( bufPtr + 2, 2, &theTime.tm_mon, 1, 12 );
1170  }
1171  if( cryptStatusOK( status ) )
1172  {
1173  theTime.tm_mon--; /* Months are zero-based */
1174  status = strGetNumeric( bufPtr + 4, 2, &theTime.tm_mday, 1, 31 );
1175  }
1176  if( cryptStatusOK( status ) )
1177  status = strGetNumeric( bufPtr + 6, 2, &theTime.tm_hour, 0, 23 );
1178  if( cryptStatusOK( status ) )
1179  status = strGetNumeric( bufPtr + 8, 2, &theTime.tm_min, 0, 59 );
1180  if( cryptStatusOK( status ) )
1181  status = strGetNumeric( bufPtr + 10, 2, &theTime.tm_sec, 0, 59 );
1182  if( cryptStatusError( status ) )
1183  return( sSetError( stream, status ) );
1184 
1185  /* Finally, convert the decoded value to the local time. Since the
1186  UTCTime format doesn't take centuries into account (and you'd think
1187  that when the ISO came up with the world's least efficient time
1188  encoding format they could have spared another two bytes to fully
1189  specify the year), we have to adjust by one century for years < 50 if
1190  the format is UTCTime. Note that there are some implementations that
1191  currently roll over a century from 1970 (the Unix/Posix epoch and
1192  sort-of ISO/ANSI C epoch although they never come out and say it)
1193  but hopefully these will be fixed by 2050 when it would become an
1194  issue.
1195 
1196  In theory we could also check for an at least vaguely sane input
1197  value range on the grounds that (a) some systems' mktime()s may be
1198  broken and (b) some mktime()s may allow (and return) outrageous date
1199  values that others don't, however it's probably better to simply be
1200  consistent with what the system does rather than to try and
1201  second-guess the intent of the mktime() authors.
1202 
1203  "The time is out of joint; o cursed spite,
1204  That ever I was born to set it right" - Shakespeare, "Hamlet" */
1205  if( isUTCTime && theTime.tm_year < 50 )
1206  theTime.tm_year += 100;
1207  utcTime = mktime( &theTime );
1208  if( utcTime < 0 )
1209  {
1210  /* Some Java-based apps with 64-bit times use ridiculous validity
1211  dates (yes, we're going to be keeping the same key in active use
1212  for *forty years*) that postdate the time_t range when time_t is
1213  a signed 32-bit value. If we can't convert the time, we check
1214  for a year after the time_t overflow (2038) and try again. In
1215  theory we should just reject objects with such broken dates but
1216  since we otherwise accept all sorts of rubbish we at least try
1217  and accept these as well */
1218  if( theTime.tm_year >= 138 && theTime.tm_year < 180 )
1219  {
1220  theTime.tm_year = 136; /* 2036 */
1221  utcTime = mktime( &theTime );
1222  }
1223 
1224  /* Some broken apps set dates to 1/1/1970, handling times this close
1225  to the epoch is problematic because once any possible DST
1226  adjustment is taken into account it's no longer possible to
1227  represent the converted time as a time_t unless the system allows
1228  it to be negative (Windows doesn't, many Unixen do, but having
1229  cryptlib return a negative time value is probably a bad thing).
1230  To handle this, if we find a date set anywhere during January 1970
1231  we manually set the time to zero (the epoch) */
1232  if( theTime.tm_year == 70 && theTime.tm_mon == 0 )
1233  {
1234  *timePtr = 0;
1235  return( CRYPT_OK );
1236  }
1237  }
1238  if( utcTime < MIN_STORED_TIME_VALUE )
1239  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1240 
1241  /* Convert the UTC time to local time. This is complicated by the fact
1242  that although the C standard library can convert from local time ->
1243  UTC it can't convert the time back, so we treat the UTC time as
1244  local time (gmtime_s() always assumes that the input is local time)
1245  and covert to GMT and back, which should give the offset from GMT.
1246  Since we can't assume that time_t is signed we have to treat a
1247  negative and positive offset separately.
1248 
1249  An extra complication is added by daylight savings time adjustment,
1250  some (hopefully most by now) systems adjust for DST by default, some
1251  don't, and some allow it to be configured by the user so that it can
1252  vary from machine to machine so we have to make it explicit as part
1253  of the conversion process.
1254 
1255  Even this still isn't perfect because it displays the time adjusted
1256  for DST now rather than DST when the time value was created. This
1257  will occur when the code is run within about 12-13 hours either way
1258  of the time at which the DST switchover occurs at that particular
1259  locality and doesn't necessarily have to be during the switchover
1260  hour since being in a different time zone to GMT can change the time
1261  by many hours, flipping it across the switchover hour.
1262 
1263  This problem is more or less undecidable, the code used here has the
1264  property that the values for Windows agree with those for Unix and
1265  other systems, but it can't handle the DST flip because there's no
1266  way to find out whether it's happened to us or not */
1267  gmTimeInfoPtr = gmTime_s( &utcTime, gmTimeInfoPtr );
1268  if( gmTimeInfoPtr == NULL )
1269  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1270  gmTimeInfoPtr->tm_isdst = -1; /* Force correct DST adjustment */
1271  gmTime = mktime( gmTimeInfoPtr );
1272  if( gmTime < MIN_STORED_TIME_VALUE )
1273  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1274  if( utcTime < gmTime )
1275  *timePtr = utcTime - ( gmTime - utcTime );
1276  else
1277  *timePtr = utcTime + ( utcTime - gmTime );
1278 
1279  /* This still isn't quite perfect since it can't handle the time at a
1280  DST changeover. This is really a user problem ("Don't do that,
1281  then") but if necessary can be corrected by converting back to GMT as
1282  a sanity check and applying a +/- 1 hour correction if there's a
1283  mismatch */
1284 #if 0
1285  gmTimeInfoPtr = gmTime_s( timePtr );
1286  gmTimeInfoPtr->tm_isdst = -1;
1287  gmTime = mktime( gmTimeInfoPtr );
1288  if( gmTime != utcTime )
1289  {
1290  *timePtr += 3600; /* Try +1 first */
1291  gmTimeInfoPtr = gmTime_s( timePtr, gmTimeInfoPtr );
1292  gmTimeInfoPtr->tm_isdst = -1;
1293  gmTime = mktime( gmTimeInfoPtr );
1294  if( gmTime != utcTime )
1295  *timePtr -= 7200; /* Nope, use -1 instead */
1296  }
1297 #endif /* 0 */
1298 
1299  return( CRYPT_OK );
1300  }
1301 
1302 RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1303 int readUTCTimeTag( INOUT STREAM *stream, OUT time_t *timeVal,
1304  IN_TAG_EXT const int tag )
1305  {
1306  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1307  assert( isWritePtr( timeVal, sizeof( time_t ) ) );
1308 
1309  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
1310  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1311 
1312  /* Clear return value */
1313  *timeVal = 0;
1314 
1315  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_TIME_UTC ) )
1316  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1317  return( readTime( stream, timeVal, TRUE ) );
1318  }
1319 
1320 RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1321 int readGeneralizedTimeTag( INOUT STREAM *stream, OUT time_t *timeVal,
1322  IN_TAG_EXT const int tag )
1323  {
1324  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1325  assert( isWritePtr( timeVal, sizeof( time_t ) ) );
1326 
1327  REQUIRES_S( tag == NO_TAG || tag == DEFAULT_TAG || \
1328  ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1329 
1330  /* Clear return value */
1331  *timeVal = 0;
1332 
1333  if( tag != NO_TAG && readTag( stream ) != selectTag( tag, BER_TIME_GENERALIZED ) )
1334  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1335  return( readTime( stream, timeVal, FALSE ) );
1336  }
1337 
1338 /****************************************************************************
1339 * *
1340 * Read Routines for Constructed Objects *
1341 * *
1342 ****************************************************************************/
1343 
1344 /* Read the header for a constructed object. This performs a more strict
1345  check than the checkTag() function used when reading the tag because
1346  we know that we're reading a constructed object or hole and can restrict
1347  the permitted values accordingly. The behaviour of the read is
1348  controlled by the following flags:
1349 
1350  FLAG_BITSTRING: The object being read is a BIT STRING with an extra
1351  unused-bits count at the start. This explicit indication is
1352  required because implicit tagging can obscure the fact that what's
1353  being read is a BIT STRING.
1354 
1355  FLAG_INDEFOK: Indefinite-length objects are permitted for short-object
1356  reads.
1357 
1358  FLAG_UNIVERSAL: Normally we perform a sanity check to make sure that
1359  what we're reading has a valid tag for a constructed object or a
1360  hole, however if we're reading the object as a blob then we're more
1361  liberal in what we allow, although we still perform some minimal
1362  checking */
1363 
1364 #define READOBJ_FLAG_NONE 0x00 /* No flag */
1365 #define READOBJ_FLAG_BITSTRING 0x01 /* Object is BIT STRING */
1366 #define READOBJ_FLAG_INDEFOK 0x02 /* Indefinite lengths allowed */
1367 #define READOBJ_FLAG_UNIVERSAL 0x04 /* Relax type-checking requirements */
1368 #define READOBJ_FLAG_MAX 0x0F /* Maximum possible flag value */
1369 
1370 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1371 static int checkReadTag( INOUT STREAM *stream,
1372  IN_TAG_ENCODED_EXT const int tag,
1373  const BOOLEAN allowRelaxedMatch )
1374  {
1375  int tagValue;
1376 
1377  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1378 
1379  REQUIRES_S( ( tag == ANY_TAG ) || ( tag >= 1 && tag < MAX_TAG ) );
1380  /* Note tag != 0 */
1381 
1382  /* Read the identifier field */
1383  tagValue = readTag( stream );
1384  if( cryptStatusError( tagValue ) )
1385  return( tagValue );
1386  if( tag != ANY_TAG )
1387  {
1388  /* If we have to get an exact match, make sure that the tag matches
1389  what we're expecting */
1390  if( tagValue != tag )
1391  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1392 
1393  return( CRYPT_OK );
1394  }
1395 
1396  /* Even if we're prepared to accept (almost) any tag we still have to
1397  check for valid universal tags: BIT STRING, primitive or constructed
1398  OCTET STRING, SEQUENCE, or SET */
1399  if( tagValue == BER_BITSTRING || tagValue == BER_OCTETSTRING || \
1400  tagValue == ( BER_OCTETSTRING | BER_CONSTRUCTED ) || \
1401  tagValue == BER_SEQUENCE || tagValue == BER_SET )
1402  return( CRYPT_OK );
1403 
1404  /* In addition we can accept context-specific tagged items up to [10] */
1405  if( ( tagValue & BER_CLASS_MASK ) == BER_CONTEXT_SPECIFIC && \
1406  ( tagValue & BER_SHORT_ID_MASK ) <= MAX_CTAG_VALUE )
1407  return( CRYPT_OK );
1408 
1409  /* If we're reading an object as a genuine blob rather than a
1410  constructed object or hole we allow a wider range of tags that
1411  wouldn't normally be permitted as holes. Currently only INTEGERs
1412  are read in this manner (from their use as generic blobs in
1413  certificate serial numbers and the like) */
1414  if( allowRelaxedMatch && tagValue == BER_INTEGER )
1415  return( CRYPT_OK );
1416 
1417  /* Anything else is invalid */
1418  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1419  }
1420 
1421 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1422 static int readObjectHeader( INOUT STREAM *stream,
1423  OUT_OPT_LENGTH_Z int *length,
1424  IN_LENGTH_SHORT const int minLength,
1425  IN_TAG_ENCODED_EXT const int tag,
1426  IN_FLAGS_Z( READOBJ ) const int flags )
1427  {
1428  long dataLength;
1429  int status;
1430 
1431  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1432  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1433 
1434  REQUIRES_S( minLength >= 0 && minLength < MAX_INTLENGTH_SHORT );
1435  REQUIRES_S( ( tag == ANY_TAG ) || ( tag >= 1 && tag < MAX_TAG ) );
1436  /* Note tag != 0 */
1437  REQUIRES( flags >= READOBJ_FLAG_NONE && flags <= READOBJ_FLAG_MAX );
1438 
1439  /* Clear return value */
1440  if( length != NULL )
1441  *length = 0;
1442 
1443  /* Read the identifier field and length. If the indefiniteOK flag is
1444  set or the length is being ignored by the caller then we allow
1445  indefinite lengths. The latter is because it makes handling of
1446  infinitely-nested SEQUENCEs and whatnot easier if we don't have to
1447  worry about definite vs. indefinite-length encodings (ex duobus malis
1448  minimum eligendum est), and if indefinite lengths really aren't OK
1449  then they'll be picked up when the caller runs into the EOC at the
1450  end of the object */
1451  status = checkReadTag( stream, tag,
1452  ( flags & READOBJ_FLAG_UNIVERSAL ) ? TRUE : FALSE );
1453  if( cryptStatusError( status ) )
1454  return( status );
1455  status = readLengthValue( stream, &dataLength,
1456  ( ( flags & READOBJ_FLAG_INDEFOK ) || \
1457  length == NULL ) ? \
1459  if( cryptStatusError( status ) )
1460  return( status );
1461 
1462  /* If it's a bit string there's an extra unused-bits count. Since this
1463  is a hole encoding we don't bother about the actual value except to
1464  check that it has a sensible value */
1465  if( flags & READOBJ_FLAG_BITSTRING )
1466  {
1467  int value;
1468 
1469  if( dataLength != CRYPT_UNUSED )
1470  {
1471  dataLength--;
1472  if( dataLength < 0 || dataLength >= MAX_INTLENGTH )
1473  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1474  }
1475  value = sgetc( stream );
1476  if( cryptStatusError( value ) )
1477  return( value );
1478  if( value < 0 || value > 7 )
1479  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1480  }
1481 
1482  /* Make sure that the length is in order and return it to the caller if
1483  necessary */
1484  if( ( dataLength != CRYPT_UNUSED ) && \
1485  ( dataLength < minLength || dataLength > 32767 ) )
1486  return( sSetError( stream, CRYPT_ERROR_BADDATA ) );
1487  if( length != NULL )
1488  *length = dataLength;
1489  return( CRYPT_OK );
1490  }
1491 
1492 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1493 static int readLongObjectHeader( INOUT STREAM *stream,
1494  OUT_OPT_LENGTH_Z long *length,
1495  IN_TAG_ENCODED_EXT const int tag,
1496  IN_FLAGS_Z( READOBJ ) const int flags )
1497  {
1498  long dataLength;
1499  int status;
1500 
1501  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1502  assert( length == NULL || isWritePtr( length, sizeof( long ) ) );
1503 
1504  REQUIRES_S( ( tag == ANY_TAG ) || ( tag >= 1 && tag < MAX_TAG ) );
1505  /* Note tag != 0 */
1506  REQUIRES( flags == READOBJ_FLAG_NONE || \
1507  flags == READOBJ_FLAG_UNIVERSAL );
1508 
1509  /* Clear return value */
1510  if( length != NULL )
1511  *length = 0L;
1512 
1513  /* Read the identifier field and length */
1514  status = checkReadTag( stream, tag,
1515  ( flags & READOBJ_FLAG_UNIVERSAL ) ? TRUE : FALSE );
1516  if( cryptStatusError( status ) )
1517  return( status );
1518  status = readLengthValue( stream, &dataLength, READLENGTH_LONG_INDEF );
1519  if( cryptStatusError( status ) )
1520  return( status );
1521  if( length != NULL )
1522  *length = dataLength;
1523 
1524  return( CRYPT_OK );
1525  }
1526 
1527 /* Read an encapsulating SEQUENCE or SET or BIT STRING/OCTET STRING hole */
1528 
1529 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1530 int readSequence( INOUT STREAM *stream, OUT_OPT_LENGTH_Z int *length )
1531  {
1532  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1533  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1534 
1535  return( readObjectHeader( stream, length, 0, BER_SEQUENCE,
1536  READOBJ_FLAG_NONE ) );
1537  }
1538 
1539 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1540 int readSequenceI( INOUT STREAM *stream, OUT_OPT_LENGTH_INDEF int *length )
1541  {
1542  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1543  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1544 
1545  return( readObjectHeader( stream, length, 0, BER_SEQUENCE,
1547  }
1548 
1549 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1550 int readSet( INOUT STREAM *stream, OUT_OPT_LENGTH_Z int *length )
1551  {
1552  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1553  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1554 
1555  return( readObjectHeader( stream, length, 0, BER_SET,
1556  READOBJ_FLAG_NONE ) );
1557  }
1558 
1559 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1560 int readSetI( INOUT STREAM *stream, OUT_OPT_LENGTH_INDEF int *length )
1561  {
1562  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1563  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1564 
1565  return( readObjectHeader( stream, length, 0, BER_SET,
1567  }
1568 
1569 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1570 int readConstructed( INOUT STREAM *stream, OUT_OPT_LENGTH_Z int *length,
1571  IN_TAG const int tag )
1572  {
1573  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1574  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1575 
1576  REQUIRES_S( ( tag == DEFAULT_TAG ) || ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1577 
1578  return( readObjectHeader( stream, length, 0, ( tag == DEFAULT_TAG ) ? \
1579  BER_SEQUENCE : MAKE_CTAG( tag ),
1580  READOBJ_FLAG_NONE ) );
1581  }
1582 
1583 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1584 int readConstructedI( INOUT STREAM *stream, OUT_OPT_LENGTH_INDEF int *length,
1585  IN_TAG const int tag )
1586  {
1587  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1588  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1589 
1590  REQUIRES_S( ( tag == DEFAULT_TAG ) || ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1591 
1592  return( readObjectHeader( stream, length, 0, ( tag == DEFAULT_TAG ) ? \
1593  BER_SEQUENCE : MAKE_CTAG( tag ),
1595  }
1596 
1597 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1598 int readOctetStringHole( INOUT STREAM *stream, OUT_OPT_LENGTH_Z int *length,
1599  IN_LENGTH_SHORT const int minLength,
1600  IN_TAG const int tag )
1601  {
1602  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1603  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1604 
1605  REQUIRES_S( ( tag == DEFAULT_TAG ) || ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1606 
1607  return( readObjectHeader( stream, length, minLength,
1608  ( tag == DEFAULT_TAG ) ? \
1610  READOBJ_FLAG_NONE ) );
1611  }
1612 
1613 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1614 int readBitStringHole( INOUT STREAM *stream, OUT_OPT_LENGTH_Z int *length,
1615  IN_LENGTH_SHORT const int minLength,
1616  IN_TAG const int tag )
1617  {
1618  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1619  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1620 
1621  REQUIRES_S( ( tag == DEFAULT_TAG ) || ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1622 
1623  return( readObjectHeader( stream, length, minLength,
1624  ( tag == DEFAULT_TAG ) ? \
1626  READOBJ_FLAG_BITSTRING ) );
1627  }
1628 
1629 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1630 int readGenericHole( INOUT STREAM *stream, OUT_OPT_LENGTH_Z int *length,
1631  IN_LENGTH_SHORT const int minLength,
1632  IN_TAG const int tag )
1633  {
1634  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1635  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1636 
1637  ENSURES_S( ( tag == DEFAULT_TAG ) || ( tag > 0 && tag < MAX_TAG ) );
1638  /* In theory we should use MAX_TAG_VALUE but this function is
1639  frequently used as part of the sequence 'read tag;
1640  save tag; readGenericXYZ( tag );' so we have to allow all
1641  tag values */
1642 
1643  return( readObjectHeader( stream, length, minLength,
1644  ( tag == DEFAULT_TAG ) ? ANY_TAG : tag,
1645  READOBJ_FLAG_NONE ) );
1646  }
1647 
1648 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1649 int readGenericHoleI( INOUT STREAM *stream,
1650  OUT_OPT_LENGTH_INDEF int *length,
1651  IN_LENGTH_SHORT const int minLength,
1652  IN_TAG const int tag )
1653  {
1654  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1655  assert( length == NULL || isWritePtr( length, sizeof( int ) ) );
1656 
1657  ENSURES_S( ( tag == DEFAULT_TAG ) || ( tag > 0 && tag < MAX_TAG ) );
1658  /* See comment for readGenericHole() */
1659 
1660  return( readObjectHeader( stream, length, minLength,
1661  ( tag == DEFAULT_TAG ) ? ANY_TAG : tag,
1663  }
1664 
1665 /* Read an abnormally-long encapsulating SEQUENCE or OCTET STRING hole.
1666  This is used in place of the usual read in situations where potentially
1667  huge data quantities would fail the sanity check enforced by the
1668  standard read. This form always allows indefinite lengths, which are
1669  likely for large objects */
1670 
1671 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1672 int readLongSequence( INOUT STREAM *stream,
1673  OUT_OPT_LENGTH_INDEF long *length )
1674  {
1675  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1676  assert( length == NULL || isWritePtr( length, sizeof( long ) ) );
1677 
1678  return( readLongObjectHeader( stream, length, BER_SEQUENCE,
1679  READOBJ_FLAG_NONE ) );
1680  }
1681 
1682 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1683 int readLongSet( INOUT STREAM *stream, OUT_OPT_LENGTH_INDEF long *length )
1684  {
1685  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1686  assert( length == NULL || isWritePtr( length, sizeof( long ) ) );
1687 
1688  return( readLongObjectHeader( stream, length, BER_SET,
1689  READOBJ_FLAG_NONE ) );
1690  }
1691 
1692 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1693 int readLongConstructed( INOUT STREAM *stream,
1694  OUT_OPT_LENGTH_INDEF long *length,
1695  IN_TAG const int tag )
1696  {
1697  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1698  assert( length == NULL || isWritePtr( length, sizeof( long ) ) );
1699 
1700  REQUIRES_S( ( tag == DEFAULT_TAG ) || ( tag >= 0 && tag < MAX_TAG_VALUE ) );
1701 
1702  return( readLongObjectHeader( stream, length, ( tag == DEFAULT_TAG ) ? \
1703  BER_SEQUENCE : MAKE_CTAG( tag ),
1704  READOBJ_FLAG_NONE ) );
1705  }
1706 
1707 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1708 int readLongGenericHole( INOUT STREAM *stream,
1709  OUT_OPT_LENGTH_INDEF long *length,
1710  IN_TAG const int tag )
1711  {
1712  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1713  assert( length == NULL || isWritePtr( length, sizeof( long ) ) );
1714 
1715  ENSURES_S( ( tag == DEFAULT_TAG ) || ( tag > 0 && tag < MAX_TAG ) );
1716  /* See comment for readGenericHole() */
1717 
1718  return( readLongObjectHeader( stream, length,
1719  ( tag == DEFAULT_TAG ) ? ANY_TAG : tag,
1720  READOBJ_FLAG_NONE ) );
1721  }
1722 
1723 /* Read a generic object header, used to find the length of an object being
1724  read as a blob */
1725 
1726 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1727 int readGenericObjectHeader( INOUT STREAM *stream,
1728  OUT_LENGTH_INDEF long *length,
1729  const BOOLEAN isLongObject )
1730  {
1731  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1732  assert( isWritePtr( length, sizeof( long ) ) );
1733 
1734  /* Clear return value */
1735  *length = 0L;
1736 
1737  if( !isLongObject )
1738  {
1739  int localLength, status;
1740 
1741  status = readObjectHeader( stream, &localLength, 0, ANY_TAG,
1744  if( cryptStatusOK( status ) )
1745  *length = localLength;
1746  return( status );
1747  }
1748 
1749  return( readLongObjectHeader( stream, length, ANY_TAG,
1751  }
1752 
1753 /* Read an arbitrary-length constructed object's data into a memory buffer.
1754  This is the arbitrary-length form of readRawObject() */
1755 
1756 #define OBJECT_HEADER_DATA_SIZE 16
1757 
1758 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
1759 int readRawObjectAlloc( INOUT STREAM *stream,
1760  OUT_BUFFER_ALLOC_OPT( *length ) void **objectPtrPtr,
1762  IN_LENGTH_SHORT_MIN( 32 ) const int minLength,
1763  IN_LENGTH_SHORT const int maxLength )
1764  {
1765  STREAM headerStream;
1766  BYTE buffer[ OBJECT_HEADER_DATA_SIZE + 8 ];
1767  void *objectData;
1768  int objectLength, headerSize = DUMMY_INIT, status;
1769 
1770  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1771  assert( isWritePtr( objectPtrPtr, sizeof( void * ) ) );
1772  assert( isWritePtr( objectLengthPtr, sizeof( int ) ) );
1773 
1774  REQUIRES_S( minLength >= OBJECT_HEADER_DATA_SIZE && \
1775  minLength < maxLength && \
1776  maxLength < MAX_INTLENGTH_SHORT );
1777 
1778  /* Clear return values */
1779  *objectPtrPtr = NULL;
1780  *objectLengthPtr = 0;
1781 
1782  /* Find out how much data we need to read. This may be a non-seekable
1783  stream so we have to grab the first OBJECT_HEADER_DATA_SIZE bytes
1784  from the stream and decode them to see what's next */
1785  status = sread( stream, buffer, OBJECT_HEADER_DATA_SIZE );
1786  if( cryptStatusError( status ) )
1787  return( status );
1788  sMemConnect( &headerStream, buffer, OBJECT_HEADER_DATA_SIZE );
1789  status = readGenericHole( &headerStream, &objectLength,
1791  if( cryptStatusOK( status ) )
1792  headerSize = stell( &headerStream );
1793  sMemDisconnect( &headerStream );
1794  if( cryptStatusError( status ) )
1795  {
1796  sSetError( stream, status );
1797  return( status );
1798  }
1799 
1800  /* Make sure that the object has a sensible length */
1801  if( objectLength < minLength || objectLength > maxLength )
1802  {
1803  sSetError( stream, CRYPT_ERROR_BADDATA );
1804  return( status );
1805  }
1806 
1807  /* Allocate storage for the object data and copy the already-read
1808  portion to the start of the storage */
1809  objectLength += headerSize;
1810  if( ( objectData = clAlloc( "readObjectData", objectLength ) ) == NULL )
1811  {
1812  /* This isn't technically a stream error, but all ASN.1 stream
1813  functions need to set the stream error status */
1814  sSetError( stream, CRYPT_ERROR_MEMORY );
1815  return( CRYPT_ERROR_MEMORY );
1816  }
1817  memcpy( objectData, buffer, OBJECT_HEADER_DATA_SIZE );
1818 
1819  /* Read the remainder of the object data into the memory buffer and
1820  check that the overall object is valid */
1821  status = sread( stream, ( BYTE * ) objectData + OBJECT_HEADER_DATA_SIZE,
1822  objectLength - OBJECT_HEADER_DATA_SIZE );
1823  if( cryptStatusError( status ) )
1824  return( status );
1825  status = checkObjectEncoding( objectData, objectLength );
1826  if( cryptStatusError( status ) )
1827  {
1828  sSetError( stream, CRYPT_ERROR_BADDATA );
1829  return( status );
1830  }
1831 
1832  *objectPtrPtr = objectData;
1833  *objectLengthPtr = objectLength;
1834 
1835  return( CRYPT_OK );
1836  }