cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
decode.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib Datagram Decoding Routines *
4 * Copyright Peter Gutmann 1996-2009 *
5 * *
6 ****************************************************************************/
7 
8 #if defined( INC_ALL )
9  #include "asn1.h"
10  #include "misc_rw.h"
11  #include "pgp_rw.h"
12  #include "envelope.h"
13 #else
14  #include "enc_dec/asn1.h"
15  #include "enc_dec/misc_rw.h"
16  #include "enc_dec/pgp_rw.h"
17  #include "envelope/envelope.h"
18 #endif /* Compiler-specific includes */
19 
20 /* .... NO! ... ... MNO! ...
21  ..... MNO!! ...................... MNNOO! ...
22  ..... MMNO! ......................... MNNOO!! .
23  .... MNOONNOO! MMMMMMMMMMPPPOII! MNNO!!!! .
24  ... !O! NNO! MMMMMMMMMMMMMPPPOOOII!! NO! ....
25  ...... ! MMMMMMMMMMMMMPPPPOOOOIII! ! ...
26  ........ MMMMMMMMMMMMPPPPPOOOOOOII!! .....
27  ........ MMMMMOOOOOOPPPPPPPPOOOOMII! ...
28  ....... MMMMM.. OPPMMP .,OMI! ....
29  ...... MMMM:: o.,OPMP,.o ::I!! ...
30  .... NNM:::.,,OOPM!P,.::::!! ....
31  .. MMNNNNNOOOOPMO!!IIPPO!!O! .....
32  ... MMMMMNNNNOO:!!:!!IPPPPOO! ....
33  .. MMMMMNNOOMMNNIIIPPPOO!! ......
34  ...... MMMONNMMNNNIIIOO!..........
35  ....... MN MOMMMNNNIIIIIO! OO ..........
36  ......... MNO! IiiiiiiiiiiiI OOOO ...........
37  ...... NNN.MNO! . O!!!!!!!!!O . OONO NO! ........
38  .... MNNNNNO! ...OOOOOOOOOOO . MMNNON!........
39  ...... MNNNNO! .. PPPPPPPPP .. MMNON!........
40  ...... OO! ................. ON! .......
41  ................................
42 
43  Be very careful when modifying this code, the data manipulation that it
44  performs is somewhat tricky */
45 
46 #ifdef USE_ENVELOPES
47 
48 /****************************************************************************
49 * *
50 * Utility Routines *
51 * *
52 ****************************************************************************/
53 
54 /* Sanity-check the envelope state */
55 
57 static BOOLEAN sanityCheck( const ENVELOPE_INFO *envelopeInfoPtr )
58  {
59  assert( isReadPtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
60 
61  /* Make sure that the buffer position is within bounds */
62  if( envelopeInfoPtr->buffer == NULL || \
63  envelopeInfoPtr->bufPos < 0 || \
64  envelopeInfoPtr->bufPos > envelopeInfoPtr->bufSize || \
65  envelopeInfoPtr->bufSize < MIN_BUFFER_SIZE || \
66  envelopeInfoPtr->bufSize >= MAX_INTLENGTH )
67  return( FALSE );
68 
69  /* Make sure that the block buffer position is within bounds */
70  if( envelopeInfoPtr->blockSize > 0 && \
71  ( envelopeInfoPtr->blockBufferPos < 0 || \
72  envelopeInfoPtr->blockBufferPos >= envelopeInfoPtr->blockSize || \
73  envelopeInfoPtr->blockSize > CRYPT_MAX_IVSIZE ) )
74  return( FALSE );
75 
76  /* Make sure that the out-of-band data buffer is within bounds */
77  if( envelopeInfoPtr->oobBufPos < 0 || \
78  envelopeInfoPtr->oobBufPos > OOB_BUFFER_SIZE )
79  return( FALSE );
80 
81  /* Make sure that the envelope internal bookeeping is OK */
82  if( envelopeInfoPtr->segmentSize < 0 || \
83  envelopeInfoPtr->segmentSize >= MAX_INTLENGTH || \
84  envelopeInfoPtr->dataLeft < 0 || \
85  envelopeInfoPtr->dataLeft >= MAX_INTLENGTH )
86  return( FALSE );
87 
88  return( TRUE );
89  }
90 
91 /****************************************************************************
92 * *
93 * Header Processing Routines *
94 * *
95 ****************************************************************************/
96 
97 /* Handle the end-of-data and PKCS #5 block padding if necessary:
98 
99  pad
100  +-------+-------+-------+
101  | | | |
102  +-------+-------+-------+
103  ^ ^
104  | |
105  padPtr bPos */
106 
108 static int processDataEnd( INOUT ENVELOPE_INFO *envelopeInfoPtr )
109  {
110  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
111 
112  REQUIRES( sanityCheck( envelopeInfoPtr ) );
113 
114  /* If we're using a block cipher, undo the PKCS #5 padding which is
115  present at the end of the block */
116  if( envelopeInfoPtr->blockSize > 1 )
117  {
118  int padSize, i;
119 
120  /* Make sure that the padding size is valid */
121  padSize = envelopeInfoPtr->buffer[ envelopeInfoPtr->bufPos - 1 ];
122  if( padSize < 1 || padSize > envelopeInfoPtr->blockSize || \
123  padSize > envelopeInfoPtr->bufPos )
124  return( CRYPT_ERROR_BADDATA );
125 
126  /* Check the padding data */
127  envelopeInfoPtr->bufPos -= padSize;
128  for( i = 0; i < padSize - 1; i++ )
129  {
130  if( envelopeInfoPtr->buffer[ envelopeInfoPtr->bufPos + i ] != padSize )
131  return( CRYPT_ERROR_BADDATA );
132  }
133  ENSURES( envelopeInfoPtr->bufPos >= 0 && \
134  envelopeInfoPtr->bufPos < envelopeInfoPtr->bufSize );
135  }
136 
137  /* Remember that we've reached the end of the payload and where the
138  payload ends ("This was the end of the river all right") */
139  envelopeInfoPtr->dataFlags |= ENVDATA_ENDOFCONTENTS;
140  envelopeInfoPtr->dataLeft = envelopeInfoPtr->bufPos;
141 
142  ENSURES( sanityCheck( envelopeInfoPtr ) );
143 
144  return( CRYPT_OK );
145  }
146 
147 /* Process a sub-segment */
148 
149 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
150 static int processSegment( INOUT ENVELOPE_INFO *envelopeInfoPtr,
151  INOUT STREAM *stream,
152  OUT_LENGTH_Z long *segmentLength )
153  {
154  int status;
155 
156  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
157  assert( isWritePtr( stream, sizeof( STREAM ) ) );
158  assert( isWritePtr( segmentLength, sizeof( long ) ) );
159 
160  REQUIRES( sanityCheck( envelopeInfoPtr ) );
161 
162  /* Clear return value */
163  *segmentLength = 0;
164 
165  /* Check for the EOCs that mark the end of the overall data */
166  status = checkEOC( stream );
167  if( cryptStatusError( status ) )
168  return( status );
169  if( status == TRUE )
170  {
171  /* We've seen the EOC, wrap up the processing */
172  return( processDataEnd( envelopeInfoPtr ) );
173  }
174 
175  /* It's a new sub-segment, get its length */
176  status = readLongGenericHole( stream, segmentLength, BER_OCTETSTRING );
177  if( cryptStatusError( status ) )
178  return( status );
179  if( *segmentLength == CRYPT_UNUSED )
180  {
181  /* An indefinite-length encoding within a constructed data item
182  isn't allowed */
183  return( CRYPT_ERROR_BADDATA );
184  }
185 
186  return( CRYPT_OK );
187  }
188 
189 #ifdef USE_PGP
190 
191 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
192 static int processPgpSegment( INOUT ENVELOPE_INFO *envelopeInfoPtr,
193  INOUT STREAM *stream,
194  OUT_LENGTH_Z long *segmentLength )
195  {
196  int status;
197 
198  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
199  assert( isWritePtr( stream, sizeof( STREAM ) ) );
200  assert( isWritePtr( segmentLength, sizeof( long ) ) );
201 
202  REQUIRES( sanityCheck( envelopeInfoPtr ) );
203 
204  /* Clear return value */
205  *segmentLength = 0;
206 
207  /* Get the next sub-segment's length */
208  status = pgpReadPartialLength( stream, segmentLength );
209  if( cryptStatusError( status ) )
210  {
211  /* If we get an OK_SPECIAL returned it's just an indication that
212  we've got another partial length (with other segments to follow)
213  and not an actual error */
214  if( status == OK_SPECIAL )
215  return( CRYPT_OK );
216 
217  /* Alongside normal errors this may also be an OK_SPECIAL to
218  indicate that we got another partial length (with other segments
219  to follow), which the caller will handle as a non-error */
220  return( status );
221  }
222 
223  /* We've read a length that doesn't use the indefinite-length encoding
224  so it's the last data segment, shift from indefinite to definite-
225  length mode */
226 #if 0 /* 2/04/08 It's not really a NOSEGMENT it's just a short definite-
227  length segment */
228  envelopeInfoPtr->dataFlags |= ENVDATA_NOSEGMENT;
229 #endif /* 0 */
230  if( *segmentLength <= 0 )
231  {
232  /* It's a terminating zero-length segment, wrap up the processing.
233  Unlike CMS, PGP can add other odds and ends at this point so we
234  don't exit yet but fall through to the code that follows */
235  status = processDataEnd( envelopeInfoPtr );
236  if( cryptStatusError( status ) )
237  return( status );
238  }
239 
240  /* If this is a packet with an MDC packet tacked on, adjust the data
241  length for the length of the MDC packet */
242  if( envelopeInfoPtr->dataFlags & ENVDATA_HASATTACHEDOOB )
243  {
244  /* If the MDC data is larger than the length of the last segment,
245  adjust its effefctive size to zero. This is rather problematic
246  in that if the sender chooses to break the MDC packet across the
247  partial-header boundary it'll include some of the MDC data with
248  the payload, but there's no easy solution to this, the problem
249  lies in the PGP spec for allowing a length encoding form that
250  makes one-pass processing impossible. Hopefully implementations
251  will realise this and never break the MDC data over a partial-
252  length header */
253  *segmentLength -= PGP_MDC_PACKET_SIZE;
254  if( *segmentLength < 0 )
255  {
256  DEBUG_DIAG(( "MDC data was broken over a partial-length "
257  "segment" ));
258  assert( DEBUG_WARN );
259 
260  *segmentLength = 0;
261  }
262  }
263 
264  /* Convert the last segment into a definite-length segment. When we
265  return from this the calling code will immediately call
266  getNextSegment() again since we've consumed some input, at which
267  point the definite-length payload size will be set and the call will
268  return with OK_SPECIAL to tell the caller that there's no more length
269  information to fetch */
270  envelopeInfoPtr->payloadSize = *segmentLength;
271  *segmentLength = 0;
272 
273  ENSURES( sanityCheck( envelopeInfoPtr ) );
274 
275  return( CRYPT_OK );
276  }
277 #endif /* USE_PGP */
278 
279 /* Decode the header for the next segment in the buffer. Returns the number
280  of bytes consumed or zero if more data is required to decode the header */
281 
282 typedef enum {
283  SEGMENT_NONE, /* No segment status */
284  SEGMENT_FIXEDLENGTH, /* Single fixed-length segment, no more segments
285  to process */
286  SEGMENT_INSUFFICIENTDATA,/* Need more data to continue */
287  SEGMENT_ENDOFDATA, /* No more data to process */
288  SEGMENT_LAST /* Last possible segment status */
289  } SEGMENT_STATUS;
290 
291 CHECK_RETVAL_SPECIAL STDC_NONNULL_ARG( ( 1, 2, 4, 5 ) ) \
292 static int getNextSegment( INOUT ENVELOPE_INFO *envelopeInfoPtr,
293  IN_BUFFER( length ) const BYTE *buffer,
294  IN_LENGTH const int length,
295  OUT_LENGTH_SHORT_Z int *bytesConsumed,
296  OUT_ENUM_OPT( SEGMENT ) SEGMENT_STATUS *segmentStatus )
297  {
298  STREAM stream;
299  long segmentLength;
300  int status;
301 
302  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
303  assert( isReadPtr( buffer, length ) );
304  assert( isWritePtr( bytesConsumed, sizeof( int ) ) );
305  assert( isWritePtr( segmentStatus, sizeof( SEGMENT_STATUS ) ) );
306 
307  REQUIRES( sanityCheck( envelopeInfoPtr ) );
308  REQUIRES( length > 0 && length < MAX_INTLENGTH );
309 
310  /* Clear return values */
311  *bytesConsumed = 0;
312  *segmentStatus = SEGMENT_NONE;
313 
314  /* If we've already processed the entire payload, don't do anything.
315  This can happen when we're using the definite encoding form, since
316  the EOC flag is set elsewhere as soon as the entire payload has been
317  copied to the buffer */
318  if( envelopeInfoPtr->dataFlags & ENVDATA_ENDOFCONTENTS )
319  {
320  REQUIRES( envelopeInfoPtr->segmentSize <= 0 );
321 
322  *segmentStatus = SEGMENT_ENDOFDATA;
323  return( OK_SPECIAL );
324  }
325 
326  /* If we're using the definite encoding form there's a single segment
327  equal in length to the entire payload */
328  if( envelopeInfoPtr->payloadSize != CRYPT_UNUSED )
329  {
330  envelopeInfoPtr->segmentSize = envelopeInfoPtr->payloadSize;
331  *segmentStatus = SEGMENT_FIXEDLENGTH;
332  return( OK_SPECIAL );
333  }
334 
335  /* If we're using the indefinite form but it's an envelope type that
336  doesn't segment data the length is implicitly defined as "until we
337  run out of input". This odd situation is encountered in some cases
338  when working with PGP data such as compressed data for which there's
339  no length stored or when we're synchronising the envelope data prior
340  to processing and there are abitrary further packets (typically PGP
341  signature packets, where we want to process the packets in a
342  connected series rather than stopping at the end of the first packet
343  in the series) following the current one. In both cases we don't
344  know the overall length because we'd need to be able to look ahead
345  an arbitrary distance in the stream to figure out where the
346  compressed data or any further packets end */
347  if( envelopeInfoPtr->dataFlags & ENVDATA_NOLENGTHINFO )
348  {
349  REQUIRES( envelopeInfoPtr->segmentSize <= 0 );
350 
351  *segmentStatus = SEGMENT_FIXEDLENGTH;
352  return( OK_SPECIAL );
353  }
354 
355  /* If there's not enough data left to contain the header for a
356  reasonable-sized segment, tell the caller to try again with more data
357  (the bytesConsumed value has already been set to zero earlier). For
358  a PGP envelope a partial header is a single byte, for a PKCS #7/CMS
359  envelope it's two bytes (tag + length) but most segments will be
360  longer than 256 bytes, requiring at least three bytes of tag + length
361  data. A reasonable tradeoff seems to be to require three bytes
362  before trying to decode the length */
363  if( length < 3 )
364  {
365  *segmentStatus = SEGMENT_INSUFFICIENTDATA;
366  return( CRYPT_OK );
367  }
368 
369  /* Get the sub-segment info */
370  sMemConnect( &stream, buffer, length );
371 #ifdef USE_PGP
372  if( envelopeInfoPtr->type == CRYPT_FORMAT_PGP )
373  {
374  status = processPgpSegment( envelopeInfoPtr, &stream,
375  &segmentLength );
376  }
377  else
378 #endif /* USE_PGP */
379  {
380  status = processSegment( envelopeInfoPtr, &stream,
381  &segmentLength );
382  }
383  if( cryptStatusOK( status ) )
384  *bytesConsumed = stell( &stream );
385  sMemDisconnect( &stream );
386  if( cryptStatusError( status ) )
387  {
388  /* If we got an underflow error this isn't fatal since we can
389  continue when the user pushes more data, so we return normally
390  with bytesConsumed set to zero */
391  if( status == CRYPT_ERROR_UNDERFLOW )
392  {
393  *segmentStatus = SEGMENT_INSUFFICIENTDATA;
394  return( CRYPT_OK );
395  }
396  return( status );
397  }
398  ENSURES( *bytesConsumed > 0 && *bytesConsumed <= length );
399 
400  /* We got the length, return the information to the caller */
401  envelopeInfoPtr->segmentSize = segmentLength;
402 
403  ENSURES( sanityCheck( envelopeInfoPtr ) );
404 
405  return( CRYPT_OK );
406  }
407 
408 /****************************************************************************
409 * *
410 * Copy to Envelope *
411 * *
412 ****************************************************************************/
413 
414 /* Copy encrypted data blocks into the envelope buffer with any overflow
415  held in the block buffer. Only complete blocks are copied into the main
416  envelope buffer, if there's not enough data present for a complete block
417  it's temporarily held in the block buffer:
418 
419  bytesFromBB bytesToBB
420  bufPos--+ | |
421  v<+>|<-- qBytesToCopy ->|<+>|
422  +-----------+-----------------------+ |
423  | |///| | | | | Main buffer
424  +-----------+-----------------------+-------+
425  ^ ^ |///| | Overflow block buffer
426  | | +-------+
427  Prev.bBuf New data ^
428  contents |
429  New data remaining */
430 
431 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
432 static int copyEncryptedDataBlocks( INOUT ENVELOPE_INFO *envelopeInfoPtr,
433  IN_BUFFER( length ) const BYTE *buffer,
434  IN_LENGTH const int length,
436  {
437  BYTE *bufPtr = envelopeInfoPtr->buffer + envelopeInfoPtr->bufPos;
438  int bytesFromBB = 0, quantizedBytesToCopy, bytesToBB, status;
439 
440  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
441  assert( isReadPtr( buffer, length ) );
442  assert( isWritePtr( bytesCopied, sizeof( int ) ) );
443 
444  REQUIRES( sanityCheck( envelopeInfoPtr ) );
445  REQUIRES( length > 0 && length < MAX_INTLENGTH && \
446  envelopeInfoPtr->bufPos + \
447  envelopeInfoPtr->blockBufferPos + \
448  length <= envelopeInfoPtr->bufSize + \
449  envelopeInfoPtr->blockSize );
450  REQUIRES( !( envelopeInfoPtr->dataFlags & ENVDATA_NOLENGTHINFO ) );
451 
452  /* Clear return value */
453  *bytesCopied = 0;
454 
455  /* If the new data will fit entirely into the block buffer, copy it in
456  now and return */
457  if( envelopeInfoPtr->blockBufferPos + length < envelopeInfoPtr->blockSize )
458  {
459  memcpy( envelopeInfoPtr->blockBuffer + envelopeInfoPtr->blockBufferPos,
460  buffer, length );
461  envelopeInfoPtr->blockBufferPos += length;
462 
463  /* Adjust the segment size based on what we've consumed */
464  envelopeInfoPtr->segmentSize -= length;
465  *bytesCopied = length;
466 
467  ENSURES( sanityCheck( envelopeInfoPtr ) );
468 
469  return( CRYPT_OK );
470  }
471 
472  /* If there isn't room in the main buffer for even one more block, exit
473  without doing anything (bytesCopied is still set to zero from the
474  earlier code). This leads to slightly anomalous behaviour where,
475  with no room for a complete block in the main buffer, copying in a
476  data length smaller than the block buffer will lead to the data being
477  absorbed by the block buffer due to the previous section of code, but
478  copying in a length larger than the block buffer will result in no
479  data at all being absorbed even if there's still room in the block
480  buffer, see the long comment in copyData() for a full discussion of
481  this process */
482  if( envelopeInfoPtr->bufPos + \
483  envelopeInfoPtr->blockSize > envelopeInfoPtr->bufSize )
484  {
485  /* There's no room for even one more block */
486  return( CRYPT_OK );
487  }
488 
489  /* There's room for at least one more block in the buffer. First, if
490  there are leftover bytes in the block buffer, move them into the main
491  buffer */
492  if( envelopeInfoPtr->blockBufferPos > 0 )
493  {
494  REQUIRES( bytesFromBB >= 0 && \
495  bytesFromBB <= envelopeInfoPtr->blockSize );
496 
497  bytesFromBB = envelopeInfoPtr->blockBufferPos;
498  memcpy( bufPtr, envelopeInfoPtr->blockBuffer, bytesFromBB );
499  }
500  envelopeInfoPtr->blockBufferPos = 0;
501 
502  /* Determine how many bytes we can copy into the buffer to fill it to
503  the nearest available block size */
504  quantizedBytesToCopy = ( length + bytesFromBB ) & \
505  envelopeInfoPtr->blockSizeMask;
506  quantizedBytesToCopy -= bytesFromBB;
507  ENSURES( quantizedBytesToCopy > 0 && quantizedBytesToCopy <= length && \
508  envelopeInfoPtr->bufPos + bytesFromBB + \
509  quantizedBytesToCopy <= envelopeInfoPtr->bufSize );
510  ENSURES( ( ( bytesFromBB + quantizedBytesToCopy ) & \
511  ( envelopeInfoPtr->blockSize - 1 ) ) == 0 );
512 
513  /* Now copy across a number of bytes which is a multiple of the block
514  size and decrypt them. Note that we have to use memmove() rather
515  than memcpy() because if we're sync'ing data in the buffer we're
516  doing a copy within the buffer rather than copying in data from
517  an external source */
518  memmove( bufPtr + bytesFromBB, buffer, quantizedBytesToCopy );
519  if( envelopeInfoPtr->dataFlags & ENVDATA_AUTHENCACTIONSACTIVE )
520  {
521  /* We're performing authenticated encryotion, hash the ciphertext
522  before decrypting it */
523  status = hashEnvelopeData( envelopeInfoPtr->actionList, bufPtr,
524  bytesFromBB + quantizedBytesToCopy );
525  if( cryptStatusError( status ) )
526  return( status );
527  }
528  status = krnlSendMessage( envelopeInfoPtr->iCryptContext,
529  IMESSAGE_CTX_DECRYPT, bufPtr,
530  bytesFromBB + quantizedBytesToCopy );
531  if( cryptStatusError( status ) )
532  return( status );
533  envelopeInfoPtr->bufPos += bytesFromBB + quantizedBytesToCopy;
534  envelopeInfoPtr->segmentSize -= length;
535  ENSURES( envelopeInfoPtr->bufPos >= 0 && \
536  envelopeInfoPtr->bufPos <= envelopeInfoPtr->bufSize );
537  ENSURES( envelopeInfoPtr->segmentSize >= 0 && \
538  envelopeInfoPtr->segmentSize < MAX_INTLENGTH );
539 
540  /* If the payload has a definite length and we've reached its end, set
541  the EOC flag to make sure that we don't go any further */
542  if( envelopeInfoPtr->payloadSize != CRYPT_UNUSED && \
543  envelopeInfoPtr->segmentSize <= 0 )
544  {
545  status = processDataEnd( envelopeInfoPtr );
546  if( cryptStatusError( status ) )
547  return( status );
548 
549  ENSURES( sanityCheck( envelopeInfoPtr ) );
550 
551  *bytesCopied = length;
552  return( CRYPT_OK );
553  }
554 
555  /* Copy any remainder (the difference between the amount to copy and the
556  blocksize-quantized amount) into the block buffer */
557  bytesToBB = length - quantizedBytesToCopy;
558  REQUIRES( bytesToBB >= 0 && bytesToBB <= envelopeInfoPtr->blockSize );
559  if( bytesToBB > 0 )
560  {
561  memcpy( envelopeInfoPtr->blockBuffer, buffer + quantizedBytesToCopy,
562  bytesToBB );
563  }
564  envelopeInfoPtr->blockBufferPos = bytesToBB;
565 
566  ENSURES( sanityCheck( envelopeInfoPtr ) );
567 
568  *bytesCopied = length;
569  return( CRYPT_OK );
570  }
571 
572 /* Copy possibly encrypted data into the envelope with special handling for
573  block encryption modes. Returns the number of bytes copied:
574 
575  bPos bSize
576  | |
577  v v
578  +-----------------------+---------------+
579  | | | | | | Main buffer
580  +-----------------------+---------------+
581 
582  +-------+
583  |///| | Overflow block buffer
584  +-------+
585  ^ ^
586  |blBufSize
587  blBufPos
588 
589  The main buffer only contains data amounts quantised to the encryption
590  block size. Any additional data is copied into the block buffer, a
591  staging buffer used to accumulate data until it can be transferred to
592  the main buffer for decryption */
593 
594 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
595 static int copyData( INOUT ENVELOPE_INFO *envelopeInfoPtr,
596  IN_BUFFER( length ) const BYTE *buffer,
597  IN_LENGTH const int length,
598  OUT_LENGTH_Z int *bytesCopied )
599  {
600  BYTE *bufPtr = envelopeInfoPtr->buffer + envelopeInfoPtr->bufPos;
601  int bytesToCopy = length, bytesLeft, status;
602 
603  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
604  assert( isReadPtr( buffer, length ) );
605  assert( isWritePtr( bytesCopied, sizeof( int ) ) );
606 
607  REQUIRES( sanityCheck( envelopeInfoPtr ) );
608  REQUIRES( length > 0 && length < MAX_INTLENGTH );
609 
610  /* Clear return value */
611  *bytesCopied = 0;
612 
613  /* Figure out how much we can copy across. First we calculate the
614  minimum of the amount of data passed in and the amount remaining in
615  the current segment */
616  if( !( envelopeInfoPtr->dataFlags & ENVDATA_NOLENGTHINFO ) && \
617  bytesToCopy > envelopeInfoPtr->segmentSize )
618  bytesToCopy = envelopeInfoPtr->segmentSize;
619 
620  /* Now we check to see if this is affected by the total free space
621  remaining in the buffer. If we're processing data blocks we can have
622  two cases, one in which the limit is the amount of buffer space
623  available and the other in which the limit is the amount of data
624  available. If the limit is set by the available data then we don't
625  have to worry about flushing extra data out of the block buffer into
626  the main buffer but if the limit is set by the available buffer space
627  we have to reduce the amount that we can copy in based on any extra
628  data that will be flushed out of the block buffer.
629 
630  There are two possible approaches that can be used when the block
631  buffer is involved. The first one copies as much as we can into the
632  buffer and, if that isn't enough, maxes out the block buffer with as
633  much remaining data as possible. The second only copies in as much as
634  can fit into the buffer, even if there's room in the block buffer for
635  a few more bytes. The second approach is preferable because although
636  either will give the impression of a not-quite-full buffer into which
637  no more data can be copied, the second minimizes the amount of data
638  which is moved into and out of the block buffer.
639 
640  The first approach may seem slightly more logical, but will only
641  cause confusion in the long run. Consider copying (say) 43 bytes to
642  a 43-byte buffer. The first time this will succeed, after which there
643  will be 40 bytes in the buffer (reported to the caller) and 3 in the
644  block buffer. If the caller tries to copy in 3 more bytes to "fill"
645  the main buffer, they'll again vanish into the block buffer. A second
646  call with three more bytes will copy 2 bytes and return with 1 byte
647  uncopied. In effect this method of using the block buffer extends the
648  blocksize-quantized main buffer by the size of the block buffer, which
649  will only cause confusion when data appears to vanish when copied into
650  it.
651 
652  In the following length calculation the block buffer content is
653  counted as part of the total content in order to implement the second
654  buffer-filling strategy */
655  bytesLeft = envelopeInfoPtr->bufSize - \
656  ( envelopeInfoPtr->bufPos + envelopeInfoPtr->blockBufferPos );
657  if( bytesLeft <= 0 )
658  {
659  /* There's no room left to copy anything in, return now (bytesCopied
660  is still set to zero from the earlier code). We can't check this
661  in the calling code because it doesn't know about the internal
662  buffer-handling strategy that we use so we perform an explicit
663  check here */
664  return( CRYPT_OK );
665  }
666  if( bytesLeft < bytesToCopy )
667  bytesToCopy = bytesLeft;
668  ENSURES( bytesToCopy > 0 && bytesToCopy <= length );
669 
670  /* If its a block encryption mode we need to provide special handling for
671  odd data lengths that don't match the block size */
672  if( envelopeInfoPtr->blockSize > 1 )
673  {
674  return( copyEncryptedDataBlocks( envelopeInfoPtr, buffer,
675  bytesToCopy, bytesCopied ) );
676  }
677 
678  /* It's unencrypted data or data that's encrypted with a stream cipher,
679  just copy over as much of the segment as we can and decrypt it if
680  necessary. We use memmove() for the same reason as given above */
681  memmove( bufPtr, buffer, bytesToCopy );
682  if( envelopeInfoPtr->iCryptContext != CRYPT_ERROR )
683  {
684  if( envelopeInfoPtr->dataFlags & ENVDATA_AUTHENCACTIONSACTIVE )
685  {
686  /* We're performing authenticated encryotion, hash the
687  ciphertext before decrypting it */
688  status = hashEnvelopeData( envelopeInfoPtr->actionList, bufPtr,
689  bytesToCopy );
690  if( cryptStatusError( status ) )
691  return( status );
692  }
693  status = krnlSendMessage( envelopeInfoPtr->iCryptContext,
694  IMESSAGE_CTX_DECRYPT, bufPtr,
695  bytesToCopy );
696  if( cryptStatusError( status ) )
697  return( status );
698  }
699  envelopeInfoPtr->bufPos += bytesToCopy;
700  if( !( envelopeInfoPtr->dataFlags & ENVDATA_NOLENGTHINFO ) )
701  envelopeInfoPtr->segmentSize -= bytesToCopy;
702 
703  /* If the payload has a definite length and we've reached its end, set
704  the EOC flag to make sure that we don't go any further */
705  if( envelopeInfoPtr->payloadSize != CRYPT_UNUSED && \
706  envelopeInfoPtr->segmentSize <= 0 )
707  {
708  status = processDataEnd( envelopeInfoPtr );
709  if( cryptStatusError( status ) )
710  return( status );
711  }
712 
713  ENSURES( bytesToCopy > 0 && bytesToCopy <= length );
714  ENSURES( sanityCheck( envelopeInfoPtr ) );
715 
716  *bytesCopied = bytesToCopy;
717  return( CRYPT_OK );
718  }
719 
720 /* Copy data into the de-enveloping envelope. Returns the number of bytes
721  copied */
722 
723 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
724 static int copyToDeenvelope( INOUT ENVELOPE_INFO *envelopeInfoPtr,
725  IN_BUFFER( length ) const BYTE *buffer,
726  IN_LENGTH const int length )
727  {
728  BYTE *bufPtr = ( BYTE * ) buffer;
729  int currentLength = length, bytesCopied, iterationCount;
730 
731  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
732  assert( isReadPtr( buffer, length ) );
733 
734  REQUIRES( sanityCheck( envelopeInfoPtr ) );
735  REQUIRES( length > 0 && length < MAX_INTLENGTH );
736 
737  /* If we're trying to copy data into a full buffer, return a count of 0
738  bytes (the calling routine may convert this to an overflow error if
739  necessary) */
740  if( envelopeInfoPtr->bufPos >= envelopeInfoPtr->bufSize )
741  return( 0 );
742 
743  /* If we're verifying a detached signature, just hash the data and exit.
744  We don't have to check whether hashing is active or not because it'll
745  always be active for detached data sicne this is the only thing
746  that's done with it */
747  if( envelopeInfoPtr->flags & ENVELOPE_DETACHED_SIG )
748  {
749  int status;
750 
751  REQUIRES( envelopeInfoPtr->dataFlags & ENVDATA_HASHACTIONSACTIVE );
752 
753  status = hashEnvelopeData( envelopeInfoPtr->actionList,
754  buffer, currentLength );
755  return( cryptStatusError( status ) ? status : currentLength );
756  }
757 
758  /* Keep processing data until either we run out of input or we can't copy
759  in any more data. The code sequence within this loop acts as a simple
760  FSM so that if we exit at any point then the next call to this
761  function will resume where we left off */
762  iterationCount = 0;
763  do
764  {
765  int segmentCount, status;
766 
767  /* If there's no segment information currently available we need to
768  process a segment header before we can handle any data. The use
769  of a loop is necessary to handle some broken implementations that
770  emit zero-length sub-segments, and as a corollary it also helps
771  avoid a pile of special-case code to manage PGP's strange way of
772  handling the last segment in indefinite-length encodings. We
773  limit the segment count to FAILSAFE_ITERATIONS_SMALL sub-segments
774  to make sure that we don't spend forever trying to process
775  extremely broken data */
776  for( segmentCount = 0; \
777  segmentCount < FAILSAFE_ITERATIONS_SMALL && \
778  envelopeInfoPtr->segmentSize <= 0; \
779  segmentCount++ )
780  {
781  SEGMENT_STATUS segmentStatus;
782  int bytesConsumed;
783 
784  status = getNextSegment( envelopeInfoPtr, bufPtr, currentLength,
785  &bytesConsumed, &segmentStatus );
786  if( status == OK_SPECIAL )
787  {
788  /* If we've reached the end of the payload, we're done */
789  if( segmentStatus == SEGMENT_ENDOFDATA )
790  return( length - currentLength );
791 
792  /* We got the length via some other mechanism because it's a
793  definite-length or non-segmenting encoding, no input was
794  consumed and we can exit */
795  ENSURES( segmentStatus == SEGMENT_FIXEDLENGTH );
796  break;
797  }
798  if( cryptStatusError( status ) )
799  return( status );
800  if( bytesConsumed <= 0 )
801  {
802  const int prevBytesConsumed = length - currentLength;
803 
804  /* We don't have enough input data left to read the
805  information for the next segment, exit. If we couldn't
806  process any data at all we return a more specific
807  underflow error rather than just a zero byte-count */
808  ENSURES( segmentStatus == SEGMENT_INSUFFICIENTDATA );
809  ENSURES( sanityCheck( envelopeInfoPtr ) );
810  return( ( prevBytesConsumed <= 0 ) ?
811  CRYPT_ERROR_UNDERFLOW : prevBytesConsumed );
812  }
813  bufPtr += bytesConsumed;
814  currentLength -= bytesConsumed;
815 
816  /* If we've reached the EOC or consumed all of the input data,
817  exit */
818  if( ( envelopeInfoPtr->dataFlags & ENVDATA_ENDOFCONTENTS ) || \
819  currentLength <= 0 )
820  {
821  ENSURES( sanityCheck( envelopeInfoPtr ) );
822  return( length - currentLength );
823  }
824  }
825  if( segmentCount >= FAILSAFE_ITERATIONS_SMALL )
826  {
827  /* We've processed FAILSAFE_ITERATIONS_SMALL consecutive sub-
828  segments in a row, there's something wrong with the input
829  data */
830  return( CRYPT_ERROR_BADDATA );
831  }
832  ENSURES( currentLength > 0 && currentLength <= length && \
833  currentLength < MAX_INTLENGTH );
834 
835  /* Copy the data into the envelope, decrypting it as we go if
836  necessary. In theory we could also check to see whether any
837  more data can fit into the buffer before trying to copy it in
838  but since this would require knowledge of the internal buffer-
839  handling strategy used by copyData() we always call it and rely
840  on a bytesCopied value of zero to indicate that the tank is
841  full */
842  status = copyData( envelopeInfoPtr, bufPtr, currentLength,
843  &bytesCopied );
844  if( cryptStatusError( status ) )
845  return( status );
846  bufPtr += bytesCopied;
847  currentLength -= bytesCopied;
848 
849  ENSURES( sanityCheck( envelopeInfoPtr ) );
850  ENSURES( currentLength >= 0 && currentLength <= length && \
851  currentLength < MAX_INTLENGTH );
852 
853  assert( ( envelopeInfoPtr->segmentSize >= 0 ) || \
854  ( ( envelopeInfoPtr->dataFlags & ENVDATA_NOSEGMENT ) && \
855  ( envelopeInfoPtr->payloadSize == CRYPT_UNUSED ) && \
856  ( envelopeInfoPtr->segmentSize == CRYPT_UNUSED ) ) );
857  }
858  while( currentLength > 0 && bytesCopied > 0 && \
859  iterationCount++ < FAILSAFE_ITERATIONS_LARGE );
860  ENSURES( iterationCount < FAILSAFE_ITERATIONS_LARGE );
861 
862  ENSURES( sanityCheck( envelopeInfoPtr ) );
863  return( length - currentLength );
864  }
865 
866 /****************************************************************************
867 * *
868 * Copy from Envelope *
869 * *
870 ****************************************************************************/
871 
872 /* Copy buffered out-of-band data from earlier processing to the output.
873  This is only required for PGP envelopes where we have to burrow down into
874  nested content in order to figure out what to do with it */
875 
876 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
877 static int copyOobData( INOUT ENVELOPE_INFO *envelopeInfoPtr,
878  OUT_BUFFER( maxLength, *length ) BYTE *buffer,
879  IN_LENGTH const int maxLength,
880  OUT_LENGTH_Z int *length,
881  const BOOLEAN retainInBuffer )
882  {
883  const int oobBytesToCopy = min( maxLength, envelopeInfoPtr->oobBufPos );
884  const int oobRemainder = envelopeInfoPtr->oobBufPos - oobBytesToCopy;
885 
886  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
887  assert( isWritePtr( buffer, maxLength ) );
888  assert( isWritePtr( length, sizeof( int ) ) );
889 
890  REQUIRES( sanityCheck( envelopeInfoPtr ) );
891  REQUIRES( maxLength > 0 && maxLength < MAX_INTLENGTH );
892  REQUIRES( oobBytesToCopy > 0 && \
893  oobBytesToCopy <= envelopeInfoPtr->oobBufPos && \
894  oobBytesToCopy <= OOB_BUFFER_SIZE );
895 
896  memcpy( buffer, envelopeInfoPtr->oobBuffer, oobBytesToCopy );
897  *length = oobBytesToCopy;
898 
899  /* If we're retaining the data in the OOB, we're done */
900  if( retainInBuffer )
901  {
902  ENSURES( sanityCheck( envelopeInfoPtr ) );
903 
904  return( CRYPT_OK );
905  }
906 
907  /* We're moving data out of the OOB buffer, adjust the OOB buffer
908  contents */
909  if( oobRemainder > 0 )
910  {
911  REQUIRES( rangeCheck( oobBytesToCopy, oobRemainder,
912  OOB_BUFFER_SIZE ) );
913  memmove( envelopeInfoPtr->oobBuffer,
914  envelopeInfoPtr->oobBuffer + oobBytesToCopy, oobRemainder );
915  }
916  envelopeInfoPtr->oobBufPos = oobRemainder;
917 
918  ENSURES( sanityCheck( envelopeInfoPtr ) );
919 
920  return( CRYPT_OK );
921  }
922 
923 /* Copy data from the envelope. Returns the number of bytes copied */
924 
925 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
926 static int copyFromDeenvelope( INOUT ENVELOPE_INFO *envelopeInfoPtr,
927  OUT_BUFFER( maxLength, *length ) BYTE *buffer,
928  IN_LENGTH const int maxLength,
929  OUT_LENGTH_Z int *length,
930  IN_FLAGS( ENVCOPY ) const int flags )
931  {
932  const BOOLEAN isLookaheadRead = ( flags & ENVCOPY_FLAG_OOBDATA ) ? \
933  TRUE : FALSE;
934  int bytesToCopy = maxLength, bytesCopied, oobBytesCopied = 0;
935  int remainder, status;
936 
937  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
938  assert( isWritePtr( buffer, maxLength ) );
939  assert( isWritePtr( length, sizeof( int ) ) );
940 
941  REQUIRES( sanityCheck( envelopeInfoPtr ) );
942  REQUIRES( maxLength > 0 && maxLength < MAX_INTLENGTH );
943  REQUIRES( !isLookaheadRead || \
944  ( isLookaheadRead && \
945  ( bytesToCopy > 0 && bytesToCopy <= OOB_BUFFER_SIZE ) ) );
946  REQUIRES( flags == ENVCOPY_FLAG_NONE || flags == ENVCOPY_FLAG_OOBDATA );
947 
948  /* Clear return values */
949  memset( buffer, 0, min( 16, bytesToCopy ) );
950  *length = 0;
951 
952  /* If we're verifying a detached signature the data is communicated
953  out-of-band so there's nothing to copy out (the length is still set
954  to zero from the earlier code */
955  if( envelopeInfoPtr->flags & ENVELOPE_DETACHED_SIG )
956  return( CRYPT_OK );
957 
958  /* If there's buffered out-of-band data from an earlier lookahead read
959  present, insert it into the output stream */
960  if( envelopeInfoPtr->oobBufPos > 0 )
961  {
962  status = copyOobData( envelopeInfoPtr, buffer, bytesToCopy,
963  &oobBytesCopied, isLookaheadRead );
964  if( cryptStatusError( status ) )
965  return( status );
966  bytesToCopy -= oobBytesCopied;
967  buffer += oobBytesCopied;
968  if( bytesToCopy <= 0 )
969  {
970  *length = oobBytesCopied;
971 
972  ENSURES( sanityCheck( envelopeInfoPtr ) );
973  return( CRYPT_OK );
974  }
975  }
976  ENSURES( bytesToCopy > 0 && bytesToCopy <= maxLength && \
977  bytesToCopy < MAX_INTLENGTH );
978 
979  /* If we're using compression, expand the data from the buffer to the
980  output via the zStream */
981 #ifdef USE_COMPRESSION
982  if( envelopeInfoPtr->flags & ENVELOPE_ZSTREAMINITED )
983  {
984  const int originalInLength = bytesToCopy;
985  const int bytesIn = \
986  ( envelopeInfoPtr->dataLeft > 0 && \
987  envelopeInfoPtr->dataLeft < envelopeInfoPtr->bufPos ) ? \
988  envelopeInfoPtr->dataLeft : envelopeInfoPtr->bufPos;
989 
990  /* Decompress the data into the output buffer. Note that we use the
991  length value to determine the length of the output rather than
992  bytesToCopy since the ratio of bytes in the buffer to bytes of
993  output isn't 1:1 as it is for other content types.
994 
995  When using PGP 2.x-compatible decompression we have to allow a
996  return status of Z_BUF_ERROR because it uses a compression format
997  from a pre-release version of InfoZip that doesn't include
998  header or trailer information so the decompression code can't
999  definitely tell that it's reached the end of its input data but
1000  can only report that it can't go any further.
1001 
1002  When we're trying to suck all remaining compressed data from the
1003  zstream we may get a (rather misleadingly named) Z_BUF_ERROR if
1004  there's both no internally buffered data left and no new input
1005  available to produce any output. If this is the case we simply
1006  treat it as a nothing-copied condition, since decompression will
1007  continue when the user provides more input.
1008 
1009  We can also get a Z_BUF_ERROR for some types of (non-fatal) error
1010  situations, for example if we're flushing out data still present
1011  in the zstream (avail_in == 0) and there's a problem such as the
1012  compressor needing more data but there's none available, the zlib
1013  code will report it as a Z_BUF_ERROR. In this case we convert it
1014  into a (recoverable) underflow error, which isn't always accurate
1015  but is more useful than the generic CRYPT_ERROR_FAILED */
1016  envelopeInfoPtr->zStream.next_in = envelopeInfoPtr->buffer;
1017  envelopeInfoPtr->zStream.avail_in = bytesIn;
1018  envelopeInfoPtr->zStream.next_out = buffer;
1019  envelopeInfoPtr->zStream.avail_out = bytesToCopy;
1020  status = inflate( &envelopeInfoPtr->zStream, Z_SYNC_FLUSH );
1021  if( status != Z_OK && status != Z_STREAM_END && \
1022  !( status == Z_BUF_ERROR && \
1023  envelopeInfoPtr->type == CRYPT_FORMAT_PGP ) && \
1024  !( status == Z_BUF_ERROR && bytesIn == 0 ) )
1025  {
1026  ENSURES( status != Z_STREAM_ERROR ); /* Parameter error */
1027  return( ( status == Z_DATA_ERROR ) ? CRYPT_ERROR_BADDATA : \
1028  ( status == Z_MEM_ERROR ) ? CRYPT_ERROR_MEMORY : \
1029  ( status == Z_BUF_ERROR ) ? CRYPT_ERROR_UNDERFLOW : \
1031  }
1032 
1033  /* Adjust the status information based on the data copied from the
1034  buffer into the zStream (bytesCopied) and the data flushed from
1035  the zStream to the output (bytesToCopy) */
1036  bytesCopied = bytesIn - envelopeInfoPtr->zStream.avail_in;
1037  bytesToCopy -= envelopeInfoPtr->zStream.avail_out;
1038  ENSURES( bytesCopied >= 0 && bytesCopied < MAX_INTLENGTH && \
1039  bytesToCopy >= 0 && bytesToCopy <= originalInLength && \
1040  bytesToCopy < MAX_INTLENGTH );
1041 
1042 #if 0 /* 7/6/07 This check doesn't seem to serve any useful purpose since
1043  EOCs are handled at a higher level. In particular the
1044  check for a single pair of EOCs produces false positives
1045  when there's a string of EOCs present at the end of the
1046  data. This code goes back to at least 3.0 while the EOC
1047  handling has changed a fair bit since then so it's likely
1048  that it's an artefact from much older code */
1049  /* If we consumed all of the input and there's extra data left after
1050  the end of the data stream, it's EOC information, mark that as
1051  consumed as well */
1052  if( envelopeInfoPtr->zStream.avail_in <= 0 && \
1053  envelopeInfoPtr->dataLeft > 0 && \
1054  envelopeInfoPtr->dataLeft < envelopeInfoPtr->bufPos )
1055  {
1056  if( envelopeInfoPtr->type != CRYPT_FORMAT_PGP && \
1057  ( !( envelopeInfoPtr->dataFlags & ENVDATA_ENDOFCONTENTS ) || \
1058  ( envelopeInfoPtr->bufPos - envelopeInfoPtr->dataLeft != 2 ) ) )
1059  {
1060  /* We should only have the EOC octets { 0x00 0x00 } present
1061  at this point */
1062  retIntError();
1063  }
1064  envelopeInfoPtr->dataLeft = envelopeInfoPtr->bufPos;
1065  }
1066 #endif /* 0 */
1067 
1068  /* If we're doing a lookahead read we can't just copy the data out
1069  of the envelope buffer as we would for any other content type
1070  because we can't undo the decompression step, so we copy the data
1071  that was decompressed into the output buffer to a local buffer
1072  and insert it into the output stream on the next non-lookahead
1073  read. The size of the read from the OOB buffer has been limited
1074  previously when existing data was detected in the OOB buffer so
1075  the total of the current OOB buffer contents and the amount to
1076  read can never exceed the OOB buffer size */
1077  if( isLookaheadRead )
1078  {
1079  REQUIRES( envelopeInfoPtr->oobBufPos + \
1080  originalInLength <= OOB_BUFFER_SIZE );
1081 
1082  memcpy( envelopeInfoPtr->oobBuffer + envelopeInfoPtr->oobBufPos,
1083  buffer, originalInLength );
1084  envelopeInfoPtr->oobBufPos += originalInLength;
1085  }
1086  }
1087  else
1088 #endif /* USE_COMPRESSION */
1089  {
1090  /* Copy out as much of the data as we can, making sure that we don't
1091  overrun into any following data */
1092  if( bytesToCopy > envelopeInfoPtr->bufPos )
1093  bytesToCopy = envelopeInfoPtr->bufPos;
1094  if( envelopeInfoPtr->dataLeft > 0 && \
1095  bytesToCopy > envelopeInfoPtr->dataLeft )
1096  bytesToCopy = envelopeInfoPtr->dataLeft;
1097  ENSURES( bytesToCopy >= 0 && bytesToCopy <= maxLength && \
1098  bytesToCopy < MAX_INTLENGTH );
1099 
1100  /* We perform the postcondition check here because there are
1101  numerous exit points in the following code and this avoids having
1102  to check at every one */
1103  ENSURES( sanityCheck( envelopeInfoPtr ) );
1104 
1105  /* If we're using a block encryption mode and we haven't seen the
1106  end-of-contents yet and there's no data waiting in the block
1107  buffer (which would mean that there's more data to come), we
1108  can't copy out the last block because it might contain padding,
1109  so we decrease the effective data amount by one block's worth */
1110  if( envelopeInfoPtr->blockSize > 1 && \
1111  !( envelopeInfoPtr->dataFlags & ENVDATA_ENDOFCONTENTS ) && \
1112  envelopeInfoPtr->blockBufferPos > 0 )
1113  bytesToCopy -= envelopeInfoPtr->blockSize;
1114 
1115  /* If we've ended up with nothing to copy (e.g. due to blocking
1116  requirements), exit */
1117  if( bytesToCopy <= 0 )
1118  {
1119  *length = oobBytesCopied;
1120  return( CRYPT_OK );
1121  }
1122  ENSURES( bytesToCopy > 0 && bytesToCopy < MAX_INTLENGTH );
1123 
1124  /* If we've seen the end-of-contents octets and there's no payload
1125  left to copy out, exit */
1126  if( ( envelopeInfoPtr->dataFlags & ENVDATA_ENDOFCONTENTS ) && \
1127  envelopeInfoPtr->dataLeft <= 0 )
1128  {
1129  *length = oobBytesCopied;
1130  return( CRYPT_OK );
1131  }
1132 
1133  /* If we're doing a lookahead read just copy the data out without
1134  adjusting the read-data values */
1135  if( isLookaheadRead )
1136  {
1137  REQUIRES( bytesToCopy > 0 && bytesToCopy <= OOB_BUFFER_SIZE );
1138 
1139  memcpy( buffer, envelopeInfoPtr->buffer, bytesToCopy );
1140  *length = bytesToCopy;
1141  return( CRYPT_OK );
1142  }
1143 
1144  /* Hash the payload data if necessary */
1145  if( envelopeInfoPtr->dataFlags & ENVDATA_HASHACTIONSACTIVE )
1146  {
1147  status = hashEnvelopeData( envelopeInfoPtr->actionList,
1148  envelopeInfoPtr->buffer,
1149  bytesToCopy );
1150  if( cryptStatusError( status ) )
1151  return( status );
1152  }
1153 
1154  /* We're not using compression, copy the data across directly */
1155  memcpy( buffer, envelopeInfoPtr->buffer, bytesToCopy );
1156  bytesCopied = bytesToCopy;
1157  }
1158  ENSURES( envelopeInfoPtr->bufPos - bytesCopied >= 0 );
1159 
1160  /* Move any remaining data down to the start of the buffer */
1161  remainder = envelopeInfoPtr->bufPos - bytesCopied;
1162  ENSURES( remainder >= 0 && remainder < MAX_INTLENGTH && \
1163  bytesCopied >= 0 && bytesCopied < MAX_INTLENGTH && \
1164  bytesCopied + remainder <= envelopeInfoPtr->bufSize );
1165  if( remainder > 0 && bytesCopied > 0 )
1166  {
1167  REQUIRES( rangeCheck( bytesCopied, remainder,
1168  envelopeInfoPtr->bufSize ) );
1169  memmove( envelopeInfoPtr->buffer,
1170  envelopeInfoPtr->buffer + bytesCopied, remainder );
1171  }
1172  envelopeInfoPtr->bufPos = remainder;
1173 
1174  /* If there's data following the payload, adjust the end-of-payload
1175  pointer to reflect the data that we've just copied out */
1176  if( envelopeInfoPtr->dataLeft > 0 && bytesCopied > 0 )
1177  envelopeInfoPtr->dataLeft -= bytesCopied;
1178  ENSURES( envelopeInfoPtr->dataLeft >= 0 && \
1179  envelopeInfoPtr->dataLeft < MAX_INTLENGTH );
1180  *length = oobBytesCopied + bytesToCopy;
1181 
1182  ENSURES( sanityCheck( envelopeInfoPtr ) );
1183  return( CRYPT_OK );
1184  }
1185 
1186 /****************************************************************************
1187 * *
1188 * Extra Data Management Functions *
1189 * *
1190 ****************************************************************************/
1191 
1192 /* Synchronise the deenveloping data stream */
1193 
1194 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1195 static int syncDeenvelopeData( INOUT ENVELOPE_INFO *envelopeInfoPtr,
1196  INOUT STREAM *stream )
1197  {
1198  const long dataStartPos = stell( stream );
1199  const int oldBufPos = envelopeInfoPtr->bufPos;
1200  const int bytesLeft = sMemDataLeft( stream );
1201  int bytesCopied;
1202 
1203  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
1204  assert( isWritePtr( stream, sizeof( STREAM ) ) );
1205 
1206  REQUIRES( sanityCheck( envelopeInfoPtr ) );
1207  REQUIRES( dataStartPos >= 0 && dataStartPos < MAX_INTLENGTH );
1208 
1209  /* After the envelope header has been processed, what's left is payload
1210  data that requires special processing because of segmenting and
1211  decryption and hashing requirements, so we feed it in via a
1212  copyToDeenvelope() of the data in the buffer. This is a rather ugly
1213  hack, but it works because we're moving data backwards in the buffer
1214  so there shouldn't be any problems for the rare instances where the
1215  data overlaps. In the worst case (PKCS #7/CMS short definite-length
1216  OCTET STRING) we only consume two bytes, the tag and one-byte length,
1217  but since we're using memmove() in copyData() this shouldn't be a
1218  problem.
1219 
1220  Since we're in effect restarting from the payload data, we reset
1221  everything that counts to point back to the start of the buffer where
1222  we'll be moving the payload data. We don't have to worry about the
1223  copyToDeenvelope() overflowing the envelope since the source is the
1224  envelope buffer so the data must fit within the envelope */
1225  envelopeInfoPtr->bufPos = 0;
1226  if( bytesLeft <= 0 )
1227  {
1228  /* Handle the special case of the data ending at exactly this point */
1229  sseek( stream, 0 );
1230  return( CRYPT_ERROR_UNDERFLOW );
1231  }
1232  sMemDisconnect( stream );
1233  sMemConnect( stream, envelopeInfoPtr->buffer, bytesLeft );
1234  bytesCopied = envelopeInfoPtr->copyToEnvelopeFunction( envelopeInfoPtr,
1235  envelopeInfoPtr->buffer + dataStartPos, bytesLeft );
1236  if( cryptStatusError( bytesCopied ) )
1237  {
1238  /* Undo the buffer position reset. This isn't 100% effective if
1239  there are multiple segments present and we hit an error after
1240  we've copied down enough data to overwrite what's at the start,
1241  but in most cases it allows us to undo the copyToEnvelope(), and
1242  if the data is corrupted we won't be able to get any further
1243  anyway */
1244  envelopeInfoPtr->bufPos = oldBufPos;
1245  ENSURES( sanityCheck( envelopeInfoPtr ) );
1246  return( bytesCopied );
1247  }
1248  ENSURES( bytesCopied >= 0 && bytesCopied < MAX_INTLENGTH );
1249 
1250  /* If we copied over less than the total available and have hit the
1251  end-of-data marker it means that there's extra data following the
1252  payload. We need to move this down to the end of the decoded payload
1253  data since copyToDeenvelope() stops copying as soon as it hits the
1254  end-of-data. We use memmove() rather than memcpy() for this since
1255  we're copying to/from the same buffer:
1256 
1257  dataStartPos
1258  |
1259  v<--- bLeft --->|
1260  +---------------+---------------+--------
1261  | |///////////////| Start
1262  +---------------+---------------+--------
1263 
1264  dataStartPos
1265  |
1266  |<- bCop -->| v |<-bToC>|
1267  +---------------+---------------+--------
1268  |//payload//| | |///////| After copyToDeenvelope
1269  +---------------+---------------+--------
1270  ^ ^
1271  | |
1272  dataLeft dStartPos + bCopied
1273 
1274  +-----------+-------+--------------------
1275  |//payload//|///////| EOC
1276  +-----------+-------+--------------------
1277  ^ ^
1278  | |
1279  dLeft bufPos */
1280  if( ( envelopeInfoPtr->dataFlags & ENVDATA_ENDOFCONTENTS ) && \
1281  bytesCopied < bytesLeft )
1282  {
1283  const int bytesToCopy = bytesLeft - bytesCopied;
1284 
1285  REQUIRES( bytesToCopy > 0 && bytesToCopy < MAX_INTLENGTH && \
1286  envelopeInfoPtr->dataLeft + \
1287  bytesToCopy <= envelopeInfoPtr->bufSize && \
1288  bytesCopied + dataStartPos + \
1289  bytesToCopy <= envelopeInfoPtr->bufSize );
1290  memmove( envelopeInfoPtr->buffer + envelopeInfoPtr->dataLeft,
1291  envelopeInfoPtr->buffer + dataStartPos + bytesCopied,
1292  bytesToCopy );
1293  envelopeInfoPtr->bufPos = envelopeInfoPtr->dataLeft + bytesToCopy;
1294  }
1295 
1296  ENSURES( sanityCheck( envelopeInfoPtr ) );
1297  return( CRYPT_OK );
1298  }
1299 
1300 /* Process additional out-of-band data that doesn't get copied into/out of
1301  the de-enveloping envelope */
1302 
1303 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1304 static int processExtraData( INOUT ENVELOPE_INFO *envelopeInfoPtr,
1305  IN_BUFFER( length ) const void *buffer,
1306  IN_LENGTH const int length )
1307  {
1308  int status;
1309 
1310  assert( isWritePtr( envelopeInfoPtr, sizeof( ENVELOPE_INFO ) ) );
1311  assert( length == 0 || isReadPtr( buffer, length ) );
1312 
1313  REQUIRES( sanityCheck( envelopeInfoPtr ) );
1314  REQUIRES( length >= 0 && length < MAX_INTLENGTH );
1315 
1316  /* If the hash value was supplied externally (which means that there's
1317  nothing for us to hash since it's already been done by the caller),
1318  there won't be any hash actions active and we can return immediately */
1319  if( !( envelopeInfoPtr->dataFlags & ( ENVDATA_HASHACTIONSACTIVE | \
1321  return( ( length > 0 ) ? CRYPT_ERROR_BADDATA : CRYPT_OK );
1322 
1323  /* If we're still processing data, hash it. Since authenticated-
1324  encrypted content hashes the ciphertext before decryption rather than
1325  the plaintext we only perform hashing of nonzero-length data if we're
1326  working with straight signed or MACed data */
1327  if( length > 0 )
1328  {
1329  if( !( envelopeInfoPtr->dataFlags & ENVDATA_HASHACTIONSACTIVE ) )
1330  return( CRYPT_OK );
1331  return( hashEnvelopeData( envelopeInfoPtr->actionList, buffer,
1332  length ) );
1333  }
1334 
1335  /* We're finishing up the hashing, clear the hashing-active flag to
1336  prevent data from being hashed again if it's processed by other
1337  code such as copyFromDeenvelope() */
1338  status = hashEnvelopeData( envelopeInfoPtr->actionList, "", 0 );
1339  if( cryptStatusError( status ) )
1340  return( status );
1341  envelopeInfoPtr->dataFlags &= ~( ENVDATA_HASHACTIONSACTIVE | \
1342  ENVDATA_AUTHENCACTIONSACTIVE );
1343 
1344  return( CRYPT_OK );
1345  }
1346 
1347 /****************************************************************************
1348 * *
1349 * Envelope Access Routines *
1350 * *
1351 ****************************************************************************/
1352 
1353 STDC_NONNULL_ARG( ( 1 ) ) \
1354 void initDeenvelopeStreaming( INOUT ENVELOPE_INFO *envelopeInfoPtr )
1355  {
1356  /* Set the access method pointers */
1357  envelopeInfoPtr->copyToEnvelopeFunction = copyToDeenvelope;
1358  envelopeInfoPtr->copyFromEnvelopeFunction = copyFromDeenvelope;
1359  envelopeInfoPtr->syncDeenvelopeData = syncDeenvelopeData;
1360  envelopeInfoPtr->processExtraData = processExtraData;
1361  }
1362 #endif /* USE_ENVELOPES */