After a bit of research, I've come up with this little function to determine if a client is attempting to negotiate an SSL/TLS connection to my server, before I actually try to hand off the socket to OpenSSL. This function returns true if SSL/TLS detected, otherwise it returns false.
I'd like some input on ways to improve it, if any, particularly if there are any security problems lurking in this code. Ideally, I'd like to be able to determine which version of TLS is being negotiated, but buffer[2] is always 1, regardless of which version of TLS is incoming. If this is not something I can get from the initial packet, that's fine, but it would be a "nice to have" feature.Code:bool DetectSslTlsHandshake(int socket) { unsigned char buffer[6]; // Sniff the first few bytes from the client to see if it might be SSL/TLS. // Use the MSG_PEEK flag so as not to remove them from the buffer. int bytes = recv(socket, buffer, sizeof(buffer), MSG_PEEK); if (bytes >= 3) { if (buffer[0] & 0x80) // SSLv2 maybe { int length = (int(buffer[0] & 0x7f) << 8) + buffer[1]; if (length > 9) // likely SSLv2 { if (buffer[2] == 0x01) // definitely SSLv2 { std::cout << "SSL v2.0 Handshake detected" << std::endl; return true; } } } else if (bytes >= 6 && buffer[0] == 0x16) // SSLv3/TLSv1.x maybe { if (buffer[1] == 3) // very likely SSLv3/TLSv1.x handshake { if (buffer[2]) // TLS v1.x { std::cout << "TLS v1.x Handshake detected" << std::endl; } else // SSL v3.0 { std::cout << "SSL v3.0 Handshake detected" << std::endl; } return true; } } } return false; }