Cryptography Reference
In-Depth Information
The function receive_tls_msg , as you can probably imagine, is responsible
for reading a packet off the socket, stripping off the TLS header, stripping
off the handshake header if the message is a handshake message, and process-
ing the message itself. This is shown in Listing 6-18.
Listing 6-18: “tls.c” receive_tls_msg
/**
* Read a TLS packet off of the connection (assuming there's one waiting)
* and try to update the security parameters based on the type of message
* received. If the read times out, or if an alert is received, return an error
* code; return 0 on success.
* TODO - assert that the message received is of the type expected (for example,
* if a server hello is expected but not received, this is a fatal error per
* section 7.3).
* returns -1 if an error occurred (this routine will have sent an
* appropriate alert). Otherwise, return the number of bytes read if the packet
* includes application data; 0 if the packet was a handshake. -1 also
* indicates that an alert was received.
*/
static int receive_tls_msg( int connection,
TLSParameters *parameters )
{
TLSPlaintext message;
unsigned char *read_pos, *msg_buf;
unsigned char header[ 5 ]; // size of TLSPlaintext
int bytes_read, accum_bytes;
// STEP 1 - read off the TLS Record layer
if ( recv( connection, header, 5, 0 ) <= 0 )
{
// No data available; it's up to the caller whether this is an error or not.
return -1;
}
message.type = header[ 0 ];
message.version.major = header[ 1 ];
message.version.minor = header[ 2 ];
memcpy( &message.length, header + 3, 2 );
message.length = htons( message.length );
Adding a Receive Loop
First, the TLSPlaintext header is read from the connection and validated.
The error handling here leaves a bit to be desired, but ignore that for the
time being. If everything goes correctly, message.length holds the number
of bytes remaining in the current message. Because TCP doesn't guarantee
that all bytes are available right away, it's necessary to enter a receive loop
in Listing 6-19:
 
Search WWH ::




Custom Search