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