cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
ssl_rd.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib SSL v3/TLS Session Read Routines *
4 * Copyright Peter Gutmann 1998-2010 *
5 * *
6 ****************************************************************************/
7 
8 #if defined( INC_ALL )
9  #include "crypt.h"
10  #include "misc_rw.h"
11  #include "session.h"
12  #include "ssl.h"
13 #else
14  #include "crypt.h"
15  #include "enc_dec/misc_rw.h"
16  #include "session/session.h"
17  #include "session/ssl.h"
18 #endif /* Compiler-specific includes */
19 
20 #ifdef USE_SSL
21 
22 /****************************************************************************
23 * *
24 * Legacy SSLv2 Functions *
25 * *
26 ****************************************************************************/
27 
28 #ifdef ALLOW_SSLV2_HELLO /* 28/01/08 Disabled since it's now finally
29  removed in MSIE and Firefox */
30 
31 /* Handle a legacy SSLv2 client hello:
32 
33  uint16 length code = { 0x80, len }
34  byte type = SSL_HAND_CLIENT_HELLO
35  byte[2] vers = { 0x03, 0x0n } */
36 
37 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
38 static int handleSSLv2Header( SESSION_INFO *sessionInfoPtr,
40  const BYTE *bufPtr )
41  {
42  STREAM stream;
43  int length, value, status;
44 
45  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
46  assert( isWritePtr( handshakeInfo, sizeof( SSL_HANDSHAKE_INFO ) ) );
47 
48  REQUIRES( bufPtr[ 0 ] == SSL_MSG_V2HANDSHAKE );
49 
50  /* Make sure that the length is in order. Beyond the header we need at
51  least the three 16-bit field lengths, one 24-bit cipher suite, and at
52  least 16 bytes of nonce */
53  bufPtr++; /* Skip SSLv2 length ID, already checked by caller */
54  length = *bufPtr++;
55  if( length < ID_SIZE + VERSIONINFO_SIZE + \
56  ( UINT16_SIZE * 3 ) + 3 + 16 || \
57  length > sessionInfoPtr->receiveBufSize )
58  {
61  "Invalid legacy SSLv2 hello packet length %d", length ) );
62  }
63 
64  /* Due to the different ordering of header fields in SSLv2, the type and
65  version is regarded as part of the payload that needs to be
66  hashed, rather than the header as for SSLv3 */
67  sMemConnect( &stream, bufPtr, ID_SIZE + VERSIONINFO_SIZE );
68  status = hashHSPacketRead( handshakeInfo, &stream );
69  ENSURES( cryptStatusOK( status ) );
70  value = sgetc( &stream );
71  if( value != SSL_HAND_CLIENT_HELLO )
72  {
73  sMemDisconnect( &stream );
76  "Unexpected legacy SSLv2 packet type %d, should be %d",
77  value, SSL_HAND_CLIENT_HELLO ) );
78  }
79  status = processVersionInfo( sessionInfoPtr, &stream,
80  &handshakeInfo->clientOfferedVersion );
81  if( cryptStatusError( status ) )
82  {
83  sMemDisconnect( &stream );
84  return( status );
85  }
86  length -= stell( &stream );
87  sMemDisconnect( &stream );
88 
89  /* Read the packet payload */
90  status = sread( &sessionInfoPtr->stream, sessionInfoPtr->receiveBuffer,
91  length );
92  if( cryptStatusError( status ) )
93  {
94  sNetGetErrorInfo( &sessionInfoPtr->stream,
95  &sessionInfoPtr->errorInfo );
96  return( status );
97  }
98  if( status != length )
99  {
100  /* If we timed out during the handshake phase, treat it as a hard
101  timeout error */
104  "Timeout during legacy SSLv2 hello packet read, only got "
105  "%d of %d bytes", status, length ) );
106  }
107  sessionInfoPtr->receiveBufPos = 0;
108  sessionInfoPtr->receiveBufEnd = length;
109  sMemConnect( &stream, sessionInfoPtr->receiveBuffer, length );
110  status = hashHSPacketRead( handshakeInfo, &stream );
111  sMemDisconnect( &stream );
112  ENSURES( cryptStatusOK( status ) );
113 
114  /* SSLv2 puts the version information in the header so we set the SSLv2
115  flag in the handshake information to ensure that it doesn't get
116  confused with a normal SSL packet type */
117  handshakeInfo->isSSLv2 = TRUE;
118 
119  return( length );
120  }
121 #endif /* ALLOW_SSLV2_HELLO */
122 
123 /****************************************************************************
124 * *
125 * Utility Functions *
126 * *
127 ****************************************************************************/
128 
129 /* Get a string description of overall and handshake packet types, used for
130  diagnostic error messages */
131 
132 CHECK_RETVAL_PTR \
133 const char *getSSLPacketName( IN_RANGE( 0, 255 ) const int packetType )
134  {
135  typedef struct {
136  const int packetType;
137  const char *packetName;
138  } PACKET_NAME_INFO;
139  static const PACKET_NAME_INFO packetNameInfo[] = {
140  { SSL_MSG_CHANGE_CIPHER_SPEC, "change_cipher_spec" },
141  { SSL_MSG_ALERT, "alert" },
142  { SSL_MSG_HANDSHAKE, "handshake" },
143  { SSL_MSG_APPLICATION_DATA, "application_data" },
144  { CRYPT_ERROR, "<Unknown type>" },
145  { CRYPT_ERROR, "<Unknown type>" }
146  };
147  int i;
148 
149  REQUIRES_EXT( ( packetType >= 0 && packetType <= 0xFF ),
150  "<Internal error>" );
151 
152  for( i = 0; packetNameInfo[ i ].packetType != packetType && \
153  packetNameInfo[ i ].packetType != CRYPT_ERROR && \
154  i < FAILSAFE_ARRAYSIZE( packetNameInfo, PACKET_NAME_INFO );
155  i++ );
156  REQUIRES_EXT( ( i < FAILSAFE_ARRAYSIZE( packetNameInfo, \
157  PACKET_NAME_INFO ) ),
158  "<Internal error>" );
159 
160  return( packetNameInfo[ i ].packetName );
161  }
162 
163 CHECK_RETVAL_PTR \
164 const char *getSSLHSPacketName( IN_RANGE( 0, 255 ) const int packetType )
165  {
166  typedef struct {
167  const int packetType;
168  const char *packetName;
169  } PACKET_NAME_INFO;
170  static const PACKET_NAME_INFO packetNameInfo[] = {
171  { SSL_HAND_CLIENT_HELLO, "client_hello" },
172  { SSL_HAND_SERVER_HELLO, "server_hello" },
173  { SSL_HAND_CERTIFICATE, "certificate" },
174  { SSL_HAND_SERVER_KEYEXCHANGE, "server_key_exchange" },
175  { SSL_HAND_SERVER_CERTREQUEST, "certificate_request" },
176  { SSL_HAND_SERVER_HELLODONE, "server_hello_done" },
177  { SSL_HAND_CLIENT_CERTVERIFY, "certificate_verify" },
178  { SSL_HAND_CLIENT_KEYEXCHANGE, "client_key_exchange" },
179  { SSL_HAND_FINISHED, "finished" },
180  { SSL_HAND_SUPPLEMENTAL_DATA, "supplemental_data" },
181  { CRYPT_ERROR, "<Unknown type>" },
182  { CRYPT_ERROR, "<Unknown type>" }
183  };
184  int i;
185 
186  REQUIRES_EXT( ( packetType >= 0 && packetType <= 0xFF ),
187  "<Internal error>" );
188 
189  for( i = 0; packetNameInfo[ i ].packetType != packetType && \
190  packetNameInfo[ i ].packetType != CRYPT_ERROR && \
191  i < FAILSAFE_ARRAYSIZE( packetNameInfo, PACKET_NAME_INFO );
192  i++ );
193  REQUIRES_EXT( ( i < FAILSAFE_ARRAYSIZE( packetNameInfo, \
194  PACKET_NAME_INFO ) ),
195  "<Internal error>" );
196 
197  return( packetNameInfo[ i ].packetName );
198  }
199 
200 /* Process version information. This is always called with sufficient data
201  in the input stream so we don't have to worry about special-casing error
202  reporting for stream read errors */
203 
204 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
205 int processVersionInfo( INOUT SESSION_INFO *sessionInfoPtr,
206  INOUT STREAM *stream,
208  {
209  int version;
210 
211  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
212  assert( isWritePtr( stream, sizeof( STREAM ) ) );
213  assert( clientVersion == NULL || \
214  isWritePtr( clientVersion, sizeof( int ) ) );
215 
216  /* Clear return value */
217  if( clientVersion != NULL )
218  *clientVersion = CRYPT_ERROR;
219 
220  /* Check the major version number */
221  version = sgetc( stream );
222  if( version != SSL_MAJOR_VERSION )
223  {
226  "Invalid major version number %d, should be 3", version ) );
227  }
228 
229  /* Check the minor version number. If we've already got the version
230  established, make sure that it matches the existing one, otherwise
231  determine which version we'll be using */
232  version = sgetc( stream );
233  if( clientVersion == NULL )
234  {
235  if( version != sessionInfoPtr->version )
236  {
239  "Invalid version number 3.%d, should be 3.%d",
240  version, sessionInfoPtr->version ) );
241  }
242  return( CRYPT_OK );
243  }
244  switch( version )
245  {
247  /* If the other side can't do TLS, fall back to SSL */
248  if( sessionInfoPtr->version >= SSL_MINOR_VERSION_TLS )
249  sessionInfoPtr->version = SSL_MINOR_VERSION_SSL;
250  break;
251 
253  /* If the other side can't do TLS 1.1, fall back to TLS 1.0 */
254  if( sessionInfoPtr->version >= SSL_MINOR_VERSION_TLS11 )
255  sessionInfoPtr->version = SSL_MINOR_VERSION_TLS;
256  break;
257 
259  /* If the other side can't do TLS 1.2, fall back to TLS 1.1 */
260  if( sessionInfoPtr->version >= SSL_MINOR_VERSION_TLS12 )
261  sessionInfoPtr->version = SSL_MINOR_VERSION_TLS11;
262  break;
263 
265  /* If the other side can't do post-TLS 1.2, fall back to
266  TLS 1.2 */
267  if( sessionInfoPtr->version > SSL_MINOR_VERSION_TLS12 )
268  sessionInfoPtr->version = SSL_MINOR_VERSION_TLS12;
269  break;
270 
271  default:
272  /* If we're the server and the client has offered a vaguely
273  sensible version, fall back to the highest version that we
274  support */
275  if( isServer( sessionInfoPtr ) && \
276  version <= SSL_MINOR_VERSION_TLS12 + 2 )
277  {
278  sessionInfoPtr->version = SSL_MINOR_VERSION_TLS12;
279  break;
280  }
281 
282  /* It's nothing that we can handle */
285  "Invalid protocol version 3.%d", version ) );
286  }
287 
288  /* If there's a requirement for a minimum version, make sure that it's
289  been met */
290  if( sessionInfoPtr->sessionSSL->minVersion > 0 && \
291  version < sessionInfoPtr->sessionSSL->minVersion )
292  {
295  "Invalid version number 3.%d, should be at least 3.%d",
296  version, sessionInfoPtr->sessionSSL->minVersion ) );
297  }
298 
299  *clientVersion = version;
300  return( CRYPT_OK );
301  }
302 
303 /****************************************************************************
304 * *
305 * Check a Packet *
306 * *
307 ****************************************************************************/
308 
309 /* Check that the header of an SSL packet is in order:
310 
311  byte type
312  byte[2] vers = { 0x03, 0x0n }
313  uint16 length
314  [ byte[] iv - TLS 1.1+ ]
315 
316  This is always called with sufficient data in the input stream that we
317  don't have to worry about special-casing error reporting for stream read
318  errors.
319 
320  If this is the initial hello packet then we request a dummy version
321  information read since the peer's version isn't known yet this point. The
322  actual version information is taken from the hello packet data, not from
323  the SSL wrapper */
324 
325 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
326 static int checkPacketHeader( INOUT SESSION_INFO *sessionInfoPtr,
327  INOUT STREAM *stream,
331  const int packetType,
332  IN_LENGTH_Z const int minLength,
333  IN_LENGTH const int maxLength )
334  {
335  SSL_INFO *sslInfo = sessionInfoPtr->sessionSSL;
336  const int expectedPacketType = \
337  ( packetType == SSL_MSG_FIRST_HANDSHAKE ) ? \
338  SSL_MSG_HANDSHAKE : packetType;
339  int value, length, status;
340 
341  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
342  assert( isWritePtr( stream, sizeof( STREAM ) ) );
343  assert( isWritePtr( packetLength, sizeof( int ) ) );
344 
345  REQUIRES( ( packetType >= SSL_MSG_FIRST && \
346  packetType <= SSL_MSG_LAST ) || \
347  ( packetType == SSL_MSG_FIRST_HANDSHAKE ) );
348  REQUIRES( ( packetType == SSL_MSG_APPLICATION_DATA && \
349  minLength == 0 ) || \
350  ( minLength > 0 && minLength < MAX_INTLENGTH ) );
351  REQUIRES( maxLength >= minLength && maxLength < MAX_INTLENGTH );
352 
353  /* Clear return value */
354  *packetLength = 0;
355 
356  /* Check the packet type */
357  value = sgetc( stream );
358  if( value != expectedPacketType )
359  {
360  /* There is one special case in which a mismatch is allowed and
361  that's when we're expecting a data packet and we instead get a
362  handshake packet, which may be a rehandshake request from the
363  server. Unfortunately we can't tell that at this point because
364  the packet is encrypted, so all that we can do is set a flag
365  indicating that when we process the actual payload we need to
366  check for a re-handshake */
367  if( expectedPacketType == SSL_MSG_APPLICATION_DATA && \
368  value == SSL_MSG_HANDSHAKE && \
369  !isServer( sessionInfoPtr ) )
370  {
371  /* Tell the body-read code to check for a rehandshake (via a
372  hello_request) in the decrypted packet payload */
373  sessionInfoPtr->protocolFlags |= SSL_PFLAG_CHECKREHANDSHAKE;
374  }
375  else
376  {
379  "Unexpected %s (%d) packet, expected %s (%d)",
380  getSSLPacketName( value ), value,
381  getSSLPacketName( expectedPacketType ),
382  expectedPacketType ) );
383  }
384  }
385  status = processVersionInfo( sessionInfoPtr, stream,
386  ( packetType == SSL_MSG_FIRST_HANDSHAKE ) ? &value : NULL );
387  if( cryptStatusError( status ) )
388  return( status );
389 
390  /* Check the packet length */
391  length = readUint16( stream );
392  if( sessionInfoPtr->flags & SESSION_ISSECURE_READ )
393  {
394  if( length < sslInfo->ivSize + minLength + \
395  sessionInfoPtr->authBlocksize || \
396  length > sslInfo->ivSize + MAX_PACKET_SIZE + \
397  sessionInfoPtr->authBlocksize + 256 || \
398  length > maxLength )
399  status = CRYPT_ERROR_BADDATA;
400  }
401  else
402  {
403  if( length < minLength || length > MAX_PACKET_SIZE || \
404  length > maxLength )
405  status = CRYPT_ERROR_BADDATA;
406  }
407  if( cryptStatusError( status ) )
408  {
411  "Invalid packet length %d for %s (%d) packet",
412  length, getSSLPacketName( packetType ), packetType ) );
413  }
414 
415  /* Load the TLS 1.1+ explicit IV if necessary */
416  if( ( sessionInfoPtr->flags & SESSION_ISSECURE_READ ) && \
417  sslInfo->ivSize > 0 )
418  {
419  int ivLength;
420 
421  status = loadExplicitIV( sessionInfoPtr, stream, &ivLength );
422  if( cryptStatusError( status ) )
423  {
426  "Error loading TLS explicit IV" ) );
427  }
428  length -= ivLength;
429  ENSURES( length >= minLength + sessionInfoPtr->authBlocksize && \
430  length <= maxLength );
431  }
432  *packetLength = length;
433 
434  return( CRYPT_OK );
435  }
436 
437 /* Check that the header of an SSL packet and SSL handshake packet is in
438  order. This is always called with sufficient data in the input stream so
439  we don't have to worry about special-casing error reporting for stream
440  read errors, however for the handshake packet read we do need to check
441  the length because several of these can be encapsulated within a single
442  SSL packet so we can't check the exact space requirements in advance */
443 
444 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
445 int checkPacketHeaderSSL( INOUT SESSION_INFO *sessionInfoPtr,
446  INOUT STREAM *stream,
447  OUT_LENGTH_Z int *packetLength )
448  {
449  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
450  assert( isWritePtr( stream, sizeof( STREAM ) ) );
451  assert( isWritePtr( packetLength, sizeof( int ) ) );
452 
453  return( checkPacketHeader( sessionInfoPtr, stream, packetLength,
455  sessionInfoPtr->receiveBufSize ) );
456  }
457 
458 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
459 int checkHSPacketHeader( INOUT SESSION_INFO *sessionInfoPtr,
460  INOUT STREAM *stream,
461  OUT_LENGTH_Z int *packetLength,
463  SSL_HAND_LAST ) const int packetType,
464  IN_LENGTH_SHORT_Z const int minSize )
465  {
466  int type, length;
467 
468  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
469  assert( isWritePtr( stream, sizeof( STREAM ) ) );
470  assert( isWritePtr( packetLength, sizeof( int ) ) );
471 
472  REQUIRES( packetType >= SSL_HAND_FIRST && packetType <= SSL_HAND_LAST );
473  REQUIRES( minSize >= 0 && minSize < MAX_INTLENGTH_SHORT );
474  /* May be zero for change cipherspec */
475 
476  /* Clear return value */
477  *packetLength = 0;
478 
479  /* Make sure that there's enough data left in the stream to safely read
480  the header from it. This will be caught anyway by the checks below,
481  but performing the check here makes the error reporting a bit more
482  precise */
483  if( sMemDataLeft( stream ) < 1 + LENGTH_SIZE )
484  {
487  "Invalid handshake packet header" ) );
488  }
489 
490  /* byte ID = type
491  uint24 length */
492  type = sgetc( stream );
493  if( type != packetType )
494  {
497  "Invalid handshake packet %s (%d), expected %s (%d)",
498  getSSLHSPacketName( type ), type,
499  getSSLHSPacketName( packetType ), packetType ) );
500  }
501  length = readUint24( stream );
502  if( length < minSize || length > MAX_PACKET_SIZE || \
503  length > sMemDataLeft( stream ) )
504  {
507  "Invalid length %d for %s (%d) handshake packet",
508  length, getSSLHSPacketName( type ), type ) );
509  }
510  *packetLength = length;
511  DEBUG_PRINT(( "Read %s (%d) handshake packet, length %ld.\n",
512  getSSLHSPacketName( type ), type, length ));
513  DEBUG_DUMP_DATA( sessionInfoPtr->receiveBuffer + stell( stream ),
514  length );
515 
516  return( CRYPT_OK );
517  }
518 
519 /****************************************************************************
520 * *
521 * Read/Unwrap a Packet *
522 * *
523 ****************************************************************************/
524 
525 /* Unwrap an SSL data packet:
526 
527  data
528  |------------ MAC'd
529  v======================== Encrypted
530  +-----+-----+-----------+-----+-----+
531  | hdr |(IV) | data | MAC | pad |
532  +-----+-----+-----------+-----+-----+
533  |<---- dataMaxLen ----->|
534  |<- dLen -->|
535 
536  data
537  |
538  v================ AuthEnc'd
539  +-----+-----+---------------+-----+
540  | hdr |(IV) | data | ICV |
541  +-----+-----+---------------+-----+
542  |<--- dataMaxLen ---->|
543  |<--- dLen ---->|
544 
545  This decrypts the data, removes the padding if necessary, checks and
546  removes the MAC/ICV, and returns the payload length. Processing of the
547  header and IV have already been performed during the packet header
548  read */
549 
550 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
551 int unwrapPacketSSL( INOUT SESSION_INFO *sessionInfoPtr,
553  *dataLength ) void *data,
554  IN_LENGTH const int dataMaxLength,
557  SSL_HAND_LAST ) const int packetType )
558  {
559  BYTE dummyDataBuffer[ CRYPT_MAX_HASHSIZE + 8 ];
560  BOOLEAN badDecrypt = FALSE;
561  int length = dataMaxLength, payloadLength, status;
562 
563  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) && \
564  sessionInfoPtr->flags & SESSION_ISSECURE_READ );
565  assert( isWritePtr( data, dataMaxLength ) );
566  assert( isWritePtr( dataLength, sizeof( int ) ) );
567 
568  REQUIRES( dataMaxLength >= sessionInfoPtr->authBlocksize && \
569  dataMaxLength <= MAX_PACKET_SIZE + \
570  sessionInfoPtr->authBlocksize + 256 );
571  REQUIRES( packetType >= SSL_HAND_FIRST && packetType <= SSL_HAND_LAST );
572 
573  /* Clear return value */
574  *dataLength = 0;
575 
576  /* Make sure that the length is a multiple of the block cipher size */
577  if( sessionInfoPtr->cryptBlocksize > 1 && \
578  ( dataMaxLength % sessionInfoPtr->cryptBlocksize ) )
579  {
582  "Invalid encrypted packet length %d relative to cipher "
583  "block size %d for %s (%d) packet", dataMaxLength,
584  sessionInfoPtr->cryptBlocksize,
585  getSSLPacketName( packetType ), packetType ) );
586  }
587 
588  /* If we're using GCM then the ICV isn't encrypted, and we have to
589  process the packet metadata that's normally MACed as GCM AAD */
590  if( sessionInfoPtr->protocolFlags & SSL_PFLAG_GCM )
591  {
592  SSL_INFO *sslInfo = sessionInfoPtr->sessionSSL;
593 
594  /* Shorten the packet by the size of the ICV */
595  length -= sessionInfoPtr->authBlocksize;
596  if( length < 0 || length > MAX_PACKET_SIZE )
597  {
600  "Invalid payload length %d for %s (%d) packet",
601  length, getSSLPacketName( packetType ),
602  packetType ) );
603  }
604 
605  /* Process the packet metadata as GCM AAD */
606  status = macDataTLSGCM( sessionInfoPtr->iCryptInContext,
607  sslInfo->readSeqNo, sessionInfoPtr->version,
608  length, packetType );
609  if( cryptStatusError( status ) )
610  return( status );
611  sslInfo->readSeqNo++;
612  }
613 
614  /* Decrypt the packet in the buffer. We allow zero-length blocks (once
615  the padding is stripped) because some versions of OpenSSL send these
616  as a kludge to work around pre-TLS 1.1 chosen-IV attacks */
617  status = decryptData( sessionInfoPtr, data, length, &length );
618  if( cryptStatusError( status ) )
619  {
620  if( status != CRYPT_ERROR_BADDATA )
621  return( status );
622 
623  /* There's been a padding error, don't exit immediately but record
624  that there was a problem for after we've done the MACing.
625  Delaying the error reporting until then helps prevent timing
626  attacks of the kind described by Brice Canvel, Alain Hiltgen,
627  Serge Vaudenay, and Martin Vuagnoux in "Password Interception
628  in a SSL/TLS Channel", Crypto'03, LNCS No.2729, p.583. These
629  are close to impossible in most cases because we delay sending
630  the close notify over a much longer period than the MAC vs.non-
631  MAC time difference and because it requires repeatedly connecting
632  with a fixed-format secret such as a password at the same
633  location in the packet (which MS Outlook does however manage to
634  do), but we take this step anyway just to be safe */
635  badDecrypt = TRUE;
636  length = min( dataMaxLength,
637  MAX_PACKET_SIZE + sessionInfoPtr->authBlocksize );
638  }
639  if( sessionInfoPtr->protocolFlags & SSL_PFLAG_GCM )
640  {
641  /* If we're using GCM then the ICV check has already been
642  performed as part of the decryption and we're done */
643  if( cryptStatusError( status ) )
644  return( status );
645 
646  *dataLength = length;
647  return( CRYPT_OK );
648  }
649  payloadLength = length - sessionInfoPtr->authBlocksize;
650  if( payloadLength < 0 || payloadLength > MAX_PACKET_SIZE )
651  {
652  /* This is a bit of an odd situation and can really only occur if
653  we've been sent a malformed packet for which removing the padding
654  reduces the remaining data size to less than the minimum required
655  to store a MAC. In order to avoid being used as a timing oracle
656  we create a minimum-length dummy MAC value and use that as the
657  MAC for a zero-length packet, with the same error suppression as
658  for a bad decrypt */
659  data = dummyDataBuffer;
660  payloadLength = 0;
661  length = sessionInfoPtr->authBlocksize;
662  memset( data, 0, length );
663  badDecrypt = TRUE;
664  }
665 
666  /* MAC the decrypted data. The badDecrypt flag suppresses the reporting
667  of a MAC error due to an earlier bad decrypt, which has already been
668  reported by decryptData() */
669  if( sessionInfoPtr->version == SSL_MINOR_VERSION_SSL )
670  status = checkMacSSL( sessionInfoPtr, data, length, payloadLength,
671  packetType, badDecrypt );
672  else
673  status = checkMacTLS( sessionInfoPtr, data, length, payloadLength,
674  packetType, badDecrypt );
675  if( badDecrypt )
676  {
677  /* Report the delayed decrypt error, held to this point to make
678  timing attacks more difficult */
679  return( CRYPT_ERROR_BADDATA );
680  }
681  if( cryptStatusError( status ) )
682  return( status );
683 
684  *dataLength = payloadLength;
685  return( CRYPT_OK );
686  }
687 
688 /* Read an SSL handshake packet. Since the data transfer phase has its own
689  read/write code we can perform some special-case handling based on this */
690 
691 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 3 ) ) \
692 int readHSPacketSSL( INOUT SESSION_INFO *sessionInfoPtr,
693  INOUT_OPT SSL_HANDSHAKE_INFO *handshakeInfo,
694  OUT_LENGTH_Z int *packetLength,
696  SSL_MSG_LAST_SPECIAL ) const int packetType )
697  {
698  STREAM stream;
699  BYTE headerBuffer[ SSL_HEADER_SIZE + CRYPT_MAX_IVSIZE + 8 ];
700  const int localPacketType = \
701  ( packetType == SSL_MSG_FIRST_ENCRHANDSHAKE ) ? \
702  SSL_MSG_HANDSHAKE : packetType;
703  int bytesToRead, length, status;
704 
705  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
706  assert( ( handshakeInfo == NULL ) || \
707  isWritePtr( handshakeInfo, sizeof( SSL_HANDSHAKE_INFO ) ) );
708  assert( isWritePtr( packetLength, sizeof( int ) ) );
709 
710  REQUIRES( ( packetType >= SSL_MSG_FIRST && \
711  packetType <= SSL_MSG_LAST ) || \
712  ( packetType == SSL_MSG_FIRST_HANDSHAKE || \
713  packetType == SSL_MSG_FIRST_ENCRHANDSHAKE ) );
714  REQUIRES( sessionInfoPtr->receiveBufStartOfs >= SSL_HEADER_SIZE && \
715  sessionInfoPtr->receiveBufStartOfs < \
717 
718  /* Clear return value */
719  *packetLength = 0;
720 
721  /* Read and process the header */
722  status = readFixedHeaderAtomic( sessionInfoPtr, headerBuffer,
723  sessionInfoPtr->receiveBufStartOfs );
724  if( cryptStatusError( status ) )
725  {
726  /* This is the first packet for which encryption has been turned on.
727  Some implementations handle crypto failures badly, simply closing
728  the connection rather than returning an alert message as they're
729  supposed to. In particular IIS, due to the separation of
730  protocol and transport layers, has the HTTP server layer close
731  the connect before any error-handling at the SSL protocol layer
732  can take effect. To deal with this problem, we assume that a
733  closed connection in this situation is due to a crypto problem
734  rather than a networking problem */
735  if( status == CRYPT_ERROR_READ && \
736  packetType == SSL_MSG_FIRST_ENCRHANDSHAKE )
737  {
741  "Other side unexpectedly closed the connection, "
742  "probably due to incorrect encryption keys being "
743  "negotiated during the handshake: " ) );
744  }
745  return( status );
746  }
747 
748  /* Check for an SSL alert message */
749  if( headerBuffer[ 0 ] == SSL_MSG_ALERT )
750  {
751  return( processAlert( sessionInfoPtr, headerBuffer,
752  sessionInfoPtr->receiveBufStartOfs ) );
753  }
754 
755  /* Decode and process the SSL packet header */
756  if( packetType == SSL_MSG_FIRST_HANDSHAKE && \
757  headerBuffer[ 0 ] == SSL_MSG_V2HANDSHAKE )
758  {
759 #ifdef ALLOW_SSLV2_HELLO /* 28/01/08 Disabled since it's now finally been
760  removed from MSIE and Firefox */
761  /* It's an SSLv2 handshake, handle it specially */
762  status = length = handleSSLv2Header( sessionInfoPtr, handshakeInfo,
763  headerBuffer );
764  if( cryptStatusError( status ) )
765  return( status );
766  *packetLength = length;
767  return( OK_SPECIAL );
768 #else
771  "Client sent obsolete handshake for the insecure SSLv2 "
772  "protocol" ) );
773 #endif /* ALLOW_SSLV2_HELLO */
774  }
775  sMemConnect( &stream, headerBuffer, sessionInfoPtr->receiveBufStartOfs );
776  status = checkPacketHeader( sessionInfoPtr, &stream, &bytesToRead,
777  localPacketType,
778  ( localPacketType == SSL_MSG_CHANGE_CIPHER_SPEC ) ? \
779  1 : MIN_PACKET_SIZE,
780  sessionInfoPtr->receiveBufSize );
781  sMemDisconnect( &stream );
782  if( cryptStatusError( status ) )
783  return( status );
784 
785  /* Read the payload packet(s) */
786  status = length = \
787  sread( &sessionInfoPtr->stream, sessionInfoPtr->receiveBuffer,
788  bytesToRead );
789  if( cryptStatusError( status ) )
790  {
791  sNetGetErrorInfo( &sessionInfoPtr->stream,
792  &sessionInfoPtr->errorInfo );
793  return( status );
794  }
795  if( length != bytesToRead )
796  {
797  /* If we timed out during the handshake phase, treat it as a hard
798  timeout error */
801  "Timed out reading packet data for %s (%d) packet, only "
802  "got %d of %d bytes", getSSLPacketName( localPacketType ),
803  localPacketType, length, bytesToRead ) );
804  }
805  sessionInfoPtr->receiveBufPos = 0;
806  sessionInfoPtr->receiveBufEnd = length;
807  if( handshakeInfo != NULL )
808  {
809  sMemConnect( &stream, sessionInfoPtr->receiveBuffer, length );
810  status = hashHSPacketRead( handshakeInfo, &stream );
811  sMemDisconnect( &stream );
812  if( cryptStatusError( status ) )
813  return( status );
814  }
815  *packetLength = length;
816 
817  return( CRYPT_OK );
818  }
819 
820 /* Read the next handshake stream packet */
821 
822 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
823 int refreshHSStream( INOUT SESSION_INFO *sessionInfoPtr,
824  INOUT SSL_HANDSHAKE_INFO *handshakeInfo )
825  {
826  STREAM *stream = &handshakeInfo->stream;
827  int length, status;
828 
829  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
830  assert( isWritePtr( handshakeInfo, sizeof( SSL_HANDSHAKE_INFO ) ) );
831 
832  /* If there's still data present in the stream, there's nothing left
833  to do */
834  length = sMemDataLeft( stream );
835  if( length > 0 )
836  {
837  /* We need enough data to contain at least a handshake packet header
838  in order to continue */
839  if( length < 1 + LENGTH_SIZE || length > MAX_INTLENGTH )
840  {
843  "Invalid handshake packet data length %d", length ) );
844  }
845 
846  return( CRYPT_OK );
847  }
848 
849  /* Refill the stream */
850  sMemDisconnect( stream );
851  status = readHSPacketSSL( sessionInfoPtr, handshakeInfo, &length,
853  if( cryptStatusError( status ) )
854  return( status );
855  return( sMemConnect( stream, sessionInfoPtr->receiveBuffer, length ) );
856  }
857 
858 /****************************************************************************
859 * *
860 * Receive SSL Alerts *
861 * *
862 ****************************************************************************/
863 
864 /* SSL alert information */
865 
866 typedef struct {
867  const int type; /* SSL alert type */
868  const char *message; /* Description string */
869  const int messageLength;
870  const int cryptlibError; /* Equivalent cryptlib error status */
871  } ALERT_INFO;
872 
873 const static ALERT_INFO alertInfo[] = {
874  { SSL_ALERT_CLOSE_NOTIFY, "Close notify", 12, CRYPT_ERROR_COMPLETE },
875  { SSL_ALERT_UNEXPECTED_MESSAGE, "Unexpected message", 18, CRYPT_ERROR_FAILED },
876  { SSL_ALERT_BAD_RECORD_MAC, "Bad record MAC", 14, CRYPT_ERROR_SIGNATURE },
877  { TLS_ALERT_DECRYPTION_FAILED, "Decryption failed", 17, CRYPT_ERROR_WRONGKEY },
878  { TLS_ALERT_RECORD_OVERFLOW, "Record overflow", 15, CRYPT_ERROR_OVERFLOW },
879  { SSL_ALERT_DECOMPRESSION_FAILURE, "Decompression failure", 21, CRYPT_ERROR_FAILED },
880  { SSL_ALERT_HANDSHAKE_FAILURE, "Handshake failure", 17, CRYPT_ERROR_FAILED },
881  { SSL_ALERT_NO_CERTIFICATE, "No certificate", 14, CRYPT_ERROR_PERMISSION },
882  { SSL_ALERT_BAD_CERTIFICATE, "Bad certificate", 15, CRYPT_ERROR_INVALID },
883  { SSL_ALERT_UNSUPPORTED_CERTIFICATE, "Unsupported certificate", 23, CRYPT_ERROR_INVALID },
884  { SSL_ALERT_CERTIFICATE_REVOKED, "Certificate revoked", 19, CRYPT_ERROR_INVALID },
885  { SSL_ALERT_CERTIFICATE_EXPIRED, "Certificate expired", 19, CRYPT_ERROR_INVALID },
886  { SSL_ALERT_CERTIFICATE_UNKNOWN, "Certificate unknown", 19, CRYPT_ERROR_INVALID },
887  { TLS_ALERT_ILLEGAL_PARAMETER, "Illegal parameter", 17, CRYPT_ERROR_FAILED },
888  { TLS_ALERT_UNKNOWN_CA, "Unknown CA", 10, CRYPT_ERROR_INVALID },
889  { TLS_ALERT_ACCESS_DENIED, "Access denied", 13, CRYPT_ERROR_PERMISSION },
890  { TLS_ALERT_DECODE_ERROR, "Decode error", 12, CRYPT_ERROR_FAILED },
891  { TLS_ALERT_DECRYPT_ERROR, "Decrypt error", 13, CRYPT_ERROR_WRONGKEY },
892  { TLS_ALERT_EXPORT_RESTRICTION, "Export restriction", 18, CRYPT_ERROR_FAILED },
893  { TLS_ALERT_PROTOCOL_VERSION, "Protocol version", 16, CRYPT_ERROR_NOTAVAIL },
894  { TLS_ALERT_INSUFFICIENT_SECURITY, "Insufficient security", 21, CRYPT_ERROR_NOSECURE },
895  { TLS_ALERT_INTERNAL_ERROR, "Internal error", 14, CRYPT_ERROR_FAILED },
896  { TLS_ALERT_USER_CANCELLED, "User cancelled", 14, CRYPT_ERROR_FAILED },
897  { TLS_ALERT_NO_RENEGOTIATION, "No renegotiation", 16, CRYPT_ERROR_FAILED },
898  { TLS_ALERT_UNSUPPORTED_EXTENSION, "Unsupported extension", 21, CRYPT_ERROR_NOTAVAIL },
899  { TLS_ALERT_CERTIFICATE_UNOBTAINABLE, "Certificate unobtainable", 24, CRYPT_ERROR_NOTFOUND },
900  { TLS_ALERT_UNRECOGNIZED_NAME, "Unrecognized name", 17, CRYPT_ERROR_FAILED },
901  { TLS_ALERT_BAD_CERTIFICATE_STATUS_RESPONSE, "Bad certificate status response", 31, CRYPT_ERROR_FAILED },
902  { TLS_ALERT_BAD_CERTIFICATE_HASH_VALUE, "Bad certificate hash value", 26, CRYPT_ERROR_FAILED },
903  { TLS_ALERT_UNKNOWN_PSK_IDENTITY, "Unknown PSK identity", 20, CRYPT_ERROR_NOTFOUND },
904  { CRYPT_ERROR, NULL }, { CRYPT_ERROR, NULL }
905  };
906 
907 /* Process an alert packet. IIS often just drops the connection rather than
908  sending an alert when it encounters a problem, although we try and work
909  around some of the known problems, e.g. by sending a canary in the client
910  hello to force IIS to at least send back something rather than just
911  dropping the connection, see ssl_hs.c. In addition when communicating
912  with IIS the only error indication that we sometimes get will be a
913  "Connection closed by remote host" rather than an SSL-level error message,
914  see the comment in readHSPacketSSL() for the reason for this. Also, when
915  it encounters an unknown certificate MSIE will complete the handshake and
916  then close the connection (via a proper close alert in this case rather
917  than just closing the connection), wait while the user clicks OK several
918  times, and then restart the connection via an SSL resume. Netscape in
919  contrast just hopes that the session won't time out while waiting for the
920  user to click OK. As a result cryptlib sees a closed connection and
921  aborts the session setup process when talking to MSIE, requiring a second
922  call to the session setup to continue with the resumed session */
923 
924 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
925 int processAlert( INOUT SESSION_INFO *sessionInfoPtr,
926  IN_BUFFER( headerLength ) const void *header,
927  IN_LENGTH const int headerLength )
928  {
929  STREAM stream;
930  BYTE buffer[ 256 + 8 ];
931  int length, type, i, status;
932 
933  assert( isWritePtr( sessionInfoPtr, sizeof( SESSION_INFO ) ) );
934  assert( isReadPtr( header, headerLength ) );
935 
936  REQUIRES( headerLength > 0 && headerLength < MAX_INTLENGTH );
937 
938  /* Process the alert packet header */
939  sMemConnect( &stream, header, headerLength );
940  status = checkPacketHeader( sessionInfoPtr, &stream, &length,
942  sessionInfoPtr->receiveBufSize );
943  if( cryptStatusError( status ) )
944  {
945  sMemDisconnect( &stream );
946  return( status );
947  }
948  if( sessionInfoPtr->flags & SESSION_ISSECURE_READ )
949  {
950  if( length < ALERTINFO_SIZE || length > 256 )
951  status = CRYPT_ERROR_BADDATA;
952  }
953  else
954  {
955  if( length != ALERTINFO_SIZE )
956  status = CRYPT_ERROR_BADDATA;
957  }
958  sMemDisconnect( &stream );
959  if( cryptStatusError( status ) )
960  {
963  "Invalid alert message length %d", length ) );
964  }
965 
966  /* Read and process the alert packet */
967  status = sread( &sessionInfoPtr->stream, buffer, length );
968  if( cryptStatusError( status ) )
969  {
970  sNetGetErrorInfo( &sessionInfoPtr->stream,
971  &sessionInfoPtr->errorInfo );
972  return( status );
973  }
974  if( status != length )
975  {
976  /* If we timed out before we could get all of the alert data, bail
977  out without trying to perform any further processing. We're
978  about to shut down the session anyway so there's no point in
979  potentially stalling for ages trying to find a lost byte */
980  sendCloseAlert( sessionInfoPtr, TRUE );
981  sessionInfoPtr->flags |= SESSION_SENDCLOSED;
984  "Timed out reading alert message, only got %d of %d "
985  "bytes", status, length ) );
986  }
987  if( ( sessionInfoPtr->flags & SESSION_ISSECURE_READ ) && \
988  ( length > ALERTINFO_SIZE || \
989  isStreamCipher( sessionInfoPtr->cryptAlgo ) ) )
990  {
991  /* We only try and decrypt if the alert information is big enough to
992  be encrypted, i.e. it contains the fixed-size data + padding.
993  This situation can occur if there's an error moving from the non-
994  secure to the secure state. However, if it's a stream cipher the
995  ciphertext and plaintext are the same size so we always have to
996  try the decryption.
997 
998  Before calling unwrapPacketSSL() we set the receive-buffer end-
999  position indicator, which isn't otherwise explicitly used but is
1000  required for a sanity check in the unwrap code */
1001  sessionInfoPtr->receiveBufEnd = length;
1002  status = unwrapPacketSSL( sessionInfoPtr, buffer, length, &length,
1003  SSL_MSG_ALERT );
1004  if( cryptStatusError( status ) )
1005  {
1006  sendCloseAlert( sessionInfoPtr, TRUE );
1007  sessionInfoPtr->flags |= SESSION_SENDCLOSED;
1008  return( status );
1009  }
1010  }
1011 
1012  /* Tell the other side that we're going away */
1013  sendCloseAlert( sessionInfoPtr, TRUE );
1014  sessionInfoPtr->flags |= SESSION_SENDCLOSED;
1015 
1016  /* Process the alert information. In theory we should also make the
1017  session non-resumable if the other side goes away without sending a
1018  close alert, but this leads to too many problems with non-resumable
1019  sessions if we do so. For example many protocols do their own
1020  end-of-data indication (e.g. "Connection: close" in HTTP and BYE in
1021  SMTP) and so don't bother with a close alert. In other cases
1022  implementations just drop the connection without sending a close
1023  alert, carried over from many early Unix protocols that used a
1024  connection close to signify end-of-data, which has caused problems
1025  ever since for newer protocols that want to keep the connection open.
1026  Other implementations still send their alert but then immediately
1027  close the connection. Because of this haphazard approach to closing
1028  connections many implementations allow a session to be resumed even
1029  if no close alert is sent. In order to be compatible with this
1030  behaviour, we do the same (thus perpetuating the problem). If
1031  necessary this can be fixed by calling deleteSessionCacheEntry() if
1032  the connection is closed without a close alert having been sent */
1033  if( buffer[ 0 ] != SSL_ALERTLEVEL_WARNING && \
1034  buffer[ 0 ] != SSL_ALERTLEVEL_FATAL )
1035  {
1038  "Invalid alert message level %d", buffer[ 0 ] ) );
1039  }
1040  type = buffer[ 1 ];
1041  for( i = 0; alertInfo[ i ].type != CRYPT_ERROR && \
1042  alertInfo[ i ].type != type && \
1043  i < FAILSAFE_ARRAYSIZE( alertInfo, ALERT_INFO ); i++ );
1044  ENSURES( i < FAILSAFE_ARRAYSIZE( alertInfo, ALERT_INFO ) );
1045  if( alertInfo[ i ].type == CRYPT_ERROR )
1046  {
1049  "Unknown alert message type %d at alert level %d",
1050  type, buffer[ 0 ] ) );
1051  }
1052  retExtStr( alertInfo[ i ].cryptlibError,
1053  ( alertInfo[ i ].cryptlibError, SESSION_ERRINFO,
1054  alertInfo[ i ].message, alertInfo[ i ].messageLength,
1055  ( sessionInfoPtr->version == SSL_MINOR_VERSION_SSL ) ? \
1056  "Received SSL alert message: " : \
1057  "Received TLS alert message: " ) );
1058  }
1059 #endif /* USE_SSL */