Esempio n. 1
0
/*
	Delete an SSL session.  Some information on the session may stay around
	in the session resumption cache.
	SECURITY - We memset relevant values to zero before freeing to reduce 
	the risk of our keys floating around in memory after we're done.
*/
void matrixSslDeleteSession(ssl_t *ssl)
{

	if (ssl == NULL) {
		return;
	}
	ssl->flags |= SSL_FLAGS_CLOSED;
/*
	If we have a sessionId, for servers we need to clear the inUse flag in 
	the session cache so the ID can be replaced if needed.  In the client case
	the caller should have called matrixSslGetSessionId already to copy the
	master secret and sessionId, so free it now.

	In all cases except a successful updateSession call on the server, the
	master secret must be freed.
*/
#ifdef USE_SERVER_SIDE_SSL
	if (ssl->sessionIdLen > 0 && (ssl->flags & SSL_FLAGS_SERVER)) {
		matrixUpdateSession(ssl);
	}
#endif /* USE_SERVER_SIDE_SSL */
	ssl->sessionIdLen = 0;

#ifdef USE_CLIENT_SIDE_SSL
	if (ssl->sec.cert) {
		psX509FreeCert(ssl->sec.cert);
		ssl->sec.cert = NULL;
	}

#endif /* USE_CLIENT_SIDE_SSL */



/*
	Premaster could also be allocated if this DeleteSession is the result
	of a failed handshake.  This test is fine since all frees will NULL pointer
*/
	if (ssl->sec.premaster) {
		psFree(ssl->sec.premaster);
	}
	if (ssl->fragMessage) {
		psFree(ssl->fragMessage);
	}




/*
	Free the data buffers
*/
	psFree(ssl->outbuf);
	psFree(ssl->inbuf);
	
/*
	The cipher and mac contexts are inline in the ssl structure, so
	clearing the structure clears those states as well.
*/
	memset(ssl, 0x0, sizeof(ssl_t));
	psFree(ssl);
}
Esempio n. 2
0
/*
	The workhorse for parsing handshake messages.  Also enforces the state
	machine	for proper ordering of handshake messages.
	Parameters:
	ssl - ssl context
	inbuf - buffer to read handshake message from
	len - data length for the current ssl record.  The ssl record
		can contain multiple handshake messages, so we may need to parse
		them all here.
	Return:
		SSL_SUCCESS
		SSL_PROCESS_DATA
		SSL_ERROR - see ssl->err for details
*/
static int32 parseSSLHandshake(ssl_t *ssl, char *inbuf, int32 len)
{
	unsigned char	*c;
	unsigned char	*end;
	unsigned char	hsType;
	int32			hsLen, rc, parseLen = 0; 
	uint32			cipher = 0;
	unsigned char	hsMsgHash[SSL_MD5_HASH_SIZE + SSL_SHA1_HASH_SIZE];

#ifdef USE_SERVER_SIDE_SSL
	unsigned char	*p;
	int32			suiteLen, challengeLen, pubKeyLen, extLen;
#endif /* USE_SERVER_SIDE_SSL */

#ifdef USE_CLIENT_SIDE_SSL
	int32			sessionIdLen, certMatch, certTypeLen, i;
	sslRsaCert_t	*subjectCert;
	int32			valid, certLen, certChainLen, anonCheck;
	sslRsaCert_t	*cert, *currentCert;
#endif /* USE_CLIENT_SIDE_SSL */

	rc = SSL_SUCCESS;
	c = (unsigned char*)inbuf;
	end = (unsigned char*)(inbuf + len);

parseHandshake:
	if (end - c < 1) {
		ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
		matrixStrDebugMsg("Invalid length of handshake message\n", NULL);
		return SSL_ERROR;
	}
	hsType = *c; c++;
/*
	hsType is the received handshake type and ssl->hsState is the expected
	handshake type.  If it doesn't match, there are some possible cases
	that are not errors.  These are checked here. 
*/
	if (hsType != ssl->hsState && 
			(hsType != SSL_HS_CLIENT_HELLO || ssl->hsState != SSL_HS_DONE)) {

/*
		A mismatch is possible in the client authentication case.
		The optional CERTIFICATE_REQUEST may be appearing instead of 
		SERVER_HELLO_DONE.
*/
		if ((hsType == SSL_HS_CERTIFICATE_REQUEST) &&
				(ssl->hsState == SSL_HS_SERVER_HELLO_DONE)) {
/*
			This is where the client is first aware of requested client
			authentication so we set the flag here.
*/
			ssl->flags |= SSL_FLAGS_CLIENT_AUTH;
			ssl->hsState = SSL_HS_CERTIFICATE_REQUEST;
		} else {
/*
			The final possible mismatch allowed is for a HELLO_REQEST message.
			Indicates a rehandshake initiated from the server.
*/
			if ((hsType == SSL_HS_HELLO_REQUEST) &&
					(ssl->hsState == SSL_HS_DONE) &&
					!(ssl->flags & SSL_FLAGS_SERVER)) {
				sslResetContext(ssl);
				ssl->hsState = hsType;
			} else {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixIntDebugMsg("Invalid type of handshake message: %d\n",
					hsType);
				return SSL_ERROR;
			}
		}
	}
	if (hsType == SSL_HS_CLIENT_HELLO) { 
		sslInitHSHash(ssl);
		if (ssl->hsState == SSL_HS_DONE) {
/*
			Rehandshake. Server receiving client hello on existing connection
*/
			sslResetContext(ssl);
			ssl->hsState = hsType;
		}
	}

/*
	We need to get a copy of the message hashes to compare to those sent
	in the finished message (which does not include a hash of itself)
	before we update the handshake hashes
*/
	if (ssl->hsState == SSL_HS_FINISHED) {
		sslSnapshotHSHash(ssl, hsMsgHash, 
			(ssl->flags & SSL_FLAGS_SERVER) ? 0 : SSL_FLAGS_SERVER);
	}

/*
	Process the handshake header and update the ongoing handshake hash
	SSLv3:
		1 byte type
		3 bytes length
	SSLv2:
		1 byte type
*/
	if (ssl->rec.majVer >= SSL3_MAJ_VER) {
		if (end - c < 3) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid length of handshake message\n", NULL);
			return SSL_ERROR;
		}
		hsLen = *c << 16; c++;
		hsLen += *c << 8; c++;
		hsLen += *c; c++;
		if (end - c < hsLen) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid handshake length\n", NULL);
			return SSL_ERROR;
		}
			sslUpdateHSHash(ssl, c - ssl->hshakeHeadLen,
				hsLen + ssl->hshakeHeadLen);

	} else if (ssl->rec.majVer == SSL2_MAJ_VER) {
/*
		Assume that the handshake len is the same as the incoming ssl record
		length minus 1 byte (type), this is verified in SSL_HS_CLIENT_HELLO
*/
		hsLen = len - 1;
		sslUpdateHSHash(ssl, (unsigned char*)inbuf, len);
	} else {
		ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
		matrixIntDebugMsg("Invalid record version: %d\n", ssl->rec.majVer);
		return SSL_ERROR;
	}
/*
	Finished with header.  Process each type of handshake message.
*/
	switch(ssl->hsState) {

#ifdef USE_SERVER_SIDE_SSL
	case SSL_HS_CLIENT_HELLO:
/*
		First two bytes are the highest supported major and minor SSL versions
		We support only 3.0 (support 3.1 in commercial version)
*/
		if (end - c < 2) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid ssl header version length\n", NULL);
			return SSL_ERROR;
		}
		ssl->reqMajVer = *c; c++;
		ssl->reqMinVer = *c; c++;
		if (ssl->reqMajVer >= SSL3_MAJ_VER) {
			ssl->majVer = ssl->reqMajVer;
			ssl->minVer = SSL3_MIN_VER;

		} else {
			ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
			matrixIntDebugMsg("Unsupported ssl version: %d\n", ssl->reqMajVer);
			return SSL_ERROR;
		}
/*
		Support SSLv3 and SSLv2 ClientHello messages.  Browsers usually send v2
		messages for compatibility
*/
		if (ssl->rec.majVer > SSL2_MAJ_VER) {
/*
			Next is a 32 bytes of random data for key generation
			and a single byte with the session ID length
*/
			if (end - c < SSL_HS_RANDOM_SIZE + 1) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid length of random data\n", NULL);
				return SSL_ERROR;
			}
			memcpy(ssl->sec.clientRandom, c, SSL_HS_RANDOM_SIZE);
			c += SSL_HS_RANDOM_SIZE;
			ssl->sessionIdLen = *c; c++;
/*
			If a session length was specified, the client is asking to
			resume a previously established session to speed up the handshake.
*/
			if (ssl->sessionIdLen > 0) {
				if (ssl->sessionIdLen > SSL_MAX_SESSION_ID_SIZE || 
						end - c < ssl->sessionIdLen) {
					ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
					return SSL_ERROR;
				}
				memcpy(ssl->sessionId, c, ssl->sessionIdLen);
				c += ssl->sessionIdLen;
/*
				Look up the session id for ssl session resumption.  If found, we
				load the pre-negotiated masterSecret and cipher.
				A resumed request must meet the following restrictions:
					The id must be present in the lookup table
					The requested version must match the original version
					The cipher suite list must contain the original cipher suite
*/
				if (matrixResumeSession(ssl) >= 0) {
					ssl->flags &= ~SSL_FLAGS_CLIENT_AUTH;
					ssl->flags |= SSL_FLAGS_RESUMED;
				} else {
					memset(ssl->sessionId, 0, SSL_MAX_SESSION_ID_SIZE);
					ssl->sessionIdLen = 0;
				}
			} else {
/*
				Always clear the RESUMED flag if no client session id specified
*/
				ssl->flags &= ~SSL_FLAGS_RESUMED;
			}
/*
			Next is the two byte cipher suite list length, network byte order.  
			It must not be zero, and must be a multiple of two.
*/
			if (end - c < 2) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid cipher suite list length\n", NULL);
				return SSL_ERROR;
			}
			suiteLen = *c << 8; c++;
			suiteLen += *c; c++;
			if (suiteLen == 0 || suiteLen & 1) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixIntDebugMsg("Unable to parse cipher suite list: %d\n", 
					suiteLen);
				return SSL_ERROR;
			}
/*
			Now is 'suiteLen' bytes of the supported cipher suite list,
			listed in order of preference.  Loop through and find the 
			first cipher suite we support.
*/
			if (end - c < suiteLen) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				return SSL_ERROR;
			}
			p = c + suiteLen;
			while (c < p) {
				cipher = *c << 8; c++;
				cipher += *c; c++;
/*
				A resumed session can only match the cipher originally 
				negotiated. Otherwise, match the first cipher that we support
*/
				if (ssl->flags & SSL_FLAGS_RESUMED) {
					sslAssert(ssl->cipher);
					if (ssl->cipher->id == cipher) {
						c = p;
						break;
					}
				} else {
					if ((ssl->cipher = sslGetCipherSpec(cipher)) != NULL) {
						c = p;
						break;
					}
				}
			}
/*
			If we fell to the default cipher suite, we didn't have
			any in common with the client, or the client is being bad
			and requesting the null cipher!
*/
			if (ssl->cipher == NULL || ssl->cipher->id != cipher || 
					cipher == SSL_NULL_WITH_NULL_NULL) {
				matrixStrDebugMsg("Can't support requested cipher\n", NULL);
				ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
				ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
				return SSL_ERROR;
			}

/*
			Decode the compression parameters.  Always length one (first byte)
			and value 0 (second byte).  There are no compression schemes defined
			for SSLv3
*/
			if (end - c < 1) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid compression header length\n", NULL);
				return SSL_ERROR;
			}
			extLen = *c++;
			if (end - c < extLen) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid compression header length\n", NULL);
				return SSL_ERROR;
			}
			c += extLen;

			if (ssl->reqMinVer == SSL3_MIN_VER && extLen != 1) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid compression header\n", NULL);
				return SSL_ERROR;
			}
/*
			This might be TLS.  If so, there could be extension data
			to parse here:  Two byte length and extension info.
			http://www.faqs.org/rfcs/rfc3546.html
*/
			if (ssl->reqMinVer >= TLS_MIN_VER && c != end) {
				if (end - c < 2) {
					ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
					matrixStrDebugMsg("Invalid extension header len\n", NULL);
					return SSL_ERROR;
				}
				extLen = *c << 8; c++;
				extLen += *c; c++;
				if (end - c < extLen) {
					ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
					matrixStrDebugMsg("Invalid extension header len\n", NULL);
					return SSL_ERROR;
				}
/*
				At this point, c points to the first byte of the extension field
				and extLen is the number of extension bytes.  Parsing of 
				individual extension values would happen here, but for now we
				just skip over all extensions, ignoring them.
*/
				c += extLen;
			}
		} else {
/*
			Parse a SSLv2 ClientHello message.  The same information is 
			conveyed but the order and format is different.
			First get the cipher suite length, session id length and challenge
			(client random) length - all two byte values, network byte order.
*/
			if (end - c < 6) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Can't parse hello message\n", NULL);
				return SSL_ERROR;
			}
			suiteLen = *c << 8; c++;
			suiteLen += *c; c++;
			if (suiteLen == 0 || suiteLen % 3 != 0) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Can't parse hello message\n", NULL);
				return SSL_ERROR;
			}
			ssl->sessionIdLen = *c << 8; c++;
			ssl->sessionIdLen += *c; c++;
/*
			A resumed session would use a SSLv3 ClientHello, not SSLv2.
*/
			if (ssl->sessionIdLen != 0) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Bad resumption request\n", NULL);
				return SSL_ERROR;
			}
			challengeLen = *c << 8; c++;
			challengeLen += *c; c++;
			if (challengeLen < 16 || challengeLen > 32) {
				matrixStrDebugMsg("Bad challenge length\n", NULL);
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				return SSL_ERROR;
			}
/*
			Validate the three lengths that were just sent to us, don't
			want any buffer overflows while parsing the remaining data
*/
			if (end - c != suiteLen + ssl->sessionIdLen + challengeLen) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				return SSL_ERROR;
			}
/*
			Parse the cipher suite list similar to the SSLv3 method, except
			each suite is 3 bytes, instead of two bytes.  We define the suite
			as an integer value, so either method works for lookup.
			We don't support session resumption from V2 handshakes, so don't 
			need to worry about matching resumed cipher suite.
*/
			p = c + suiteLen;
			while (c < p) {
				cipher = *c << 16; c++;
				cipher += *c << 8; c++;
				cipher += *c; c++;
				if ((ssl->cipher = sslGetCipherSpec(cipher)) != NULL) {
					c = p;
					break;
				}
			}
			if (ssl->cipher == NULL || 
					ssl->cipher->id == SSL_NULL_WITH_NULL_NULL) {
				ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
				ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
				matrixStrDebugMsg("Can't support requested cipher\n", NULL);
				return SSL_ERROR;
			}
/*
			We don't allow session IDs for v2 ClientHellos
*/
			if (ssl->sessionIdLen > 0) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("SSLv2 sessions not allowed\n", NULL);
				return SSL_ERROR;
			}
/*
			The client random (between 16 and 32 bytes) fills the least 
			significant bytes in the (always) 32 byte SSLv3 client random field.
*/
			memset(ssl->sec.clientRandom, 0x0, SSL_HS_RANDOM_SIZE);
			memcpy(ssl->sec.clientRandom + (SSL_HS_RANDOM_SIZE - challengeLen), 
				c, challengeLen);
			c += challengeLen;
		}
/*
		ClientHello should be the only one in the record.
*/
		if (c != end) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid final client hello length\n", NULL);
			return SSL_ERROR;
		}

/*
		If we're resuming a handshake, then the next handshake message we
		expect is the finished message.  Otherwise we do the full handshake.
*/
		if (ssl->flags & SSL_FLAGS_RESUMED) {
			ssl->hsState = SSL_HS_FINISHED;
		} else {
			ssl->hsState = SSL_HS_CLIENT_KEY_EXCHANGE;
		}
/*
		Now that we've parsed the ClientHello, we need to tell the caller that
		we have a handshake response to write out.
		The caller should call sslWrite upon receiving this return code.
*/
		rc = SSL_PROCESS_DATA;
		break;

	case SSL_HS_CLIENT_KEY_EXCHANGE:
/*
		RSA: This message contains the premaster secret encrypted with the 
		server's public key (from the Certificate).  The premaster
		secret is 48 bytes of random data, but the message may be longer
		than that because the 48 bytes are padded before encryption 
		according to PKCS#1v1.5.  After encryption, we should have the 
		correct length.
*/
		if (end - c < hsLen) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid ClientKeyExchange length\n", NULL);
			return SSL_ERROR;
		}
		sslActivatePublicCipher(ssl);

		pubKeyLen = hsLen;



/*
			Now have a handshake pool to allocate the premaster storage
*/
			ssl->sec.premasterSize = SSL_HS_RSA_PREMASTER_SIZE;
			ssl->sec.premaster = psMalloc(ssl->hsPool,
				SSL_HS_RSA_PREMASTER_SIZE);

			if (ssl->decryptPriv(ssl->hsPool, ssl->keys->cert.privKey, c,
					pubKeyLen, ssl->sec.premaster, ssl->sec.premasterSize) != 
					ssl->sec.premasterSize) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Failed to decrypt premaster\n", NULL);
				return SSL_ERROR;
			}

/*
			The first two bytes of the decrypted message should be the client's 
			requested version number (which may not be the same as the final 
			negotiated version). The other 46 bytes - pure random!
			SECURITY - 
			Some SSL clients (Including Microsoft IE 6.0) incorrectly set the
			first two bytes to the negotiated version rather than the requested
			version.  This is known in OpenSSL as the SSL_OP_TLS_ROLLBACK_BUG
			We allow this to slide only if we don't support TLS, TLS was
			requested and the negotiated versions match.
*/
			if (*ssl->sec.premaster != ssl->reqMajVer) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Incorrect version in ClientKeyExchange\n",
					NULL);
				return SSL_ERROR;
			}
			if (*(ssl->sec.premaster + 1) != ssl->reqMinVer) {
				if (ssl->reqMinVer < TLS_MIN_VER ||
						*(ssl->sec.premaster + 1) != ssl->minVer) {
					ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
					matrixStrDebugMsg("Incorrect version in ClientKeyExchange\n",
						NULL);
					return SSL_ERROR;
				}
			}

/*
		Now that we've got the premaster secret, derive the various
		symmetric keys using it and the client and server random values.
		Update the cached session (if found) with the masterSecret and
		negotiated cipher.	
*/
		sslDeriveKeys(ssl);

		matrixUpdateSession(ssl);

		c += pubKeyLen;
		ssl->hsState = SSL_HS_FINISHED;


		break;
#endif /* USE_SERVER_SIDE_SSL */

	case SSL_HS_FINISHED:
/*
		Before the finished handshake message, we should have seen the
		CHANGE_CIPHER_SPEC message come through in the record layer, which
		would have activated the read cipher, and set the READ_SECURE flag.
		This is the first handshake message that was sent securely.
*/
		if (!(ssl->flags & SSL_FLAGS_READ_SECURE)) {
			ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
			matrixStrDebugMsg("Finished before ChangeCipherSpec\n", NULL);
			return SSL_ERROR;
		}
/*
		The contents of the finished message is a 16 byte MD5 hash followed
		by a 20 byte sha1 hash of all the handshake messages so far, to verify
		that nothing has been tampered with while we were still insecure.
		Compare the message to the value we calculated at the beginning of
		this function.
*/
			if (hsLen != SSL_MD5_HASH_SIZE + SSL_SHA1_HASH_SIZE) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid Finished length\n", NULL);
				return SSL_ERROR;
			}
		if (end - c < hsLen) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid Finished length\n", NULL);
			return SSL_ERROR;
		}
		if (memcmp(c, hsMsgHash, hsLen) != 0) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid handshake msg hash\n", NULL);
			return SSL_ERROR;
		}
		c += hsLen;
		ssl->hsState = SSL_HS_DONE;
/*
		Now that we've parsed the Finished message, if we're a resumed 
		connection, we're done with handshaking, otherwise, we return
		SSL_PROCESS_DATA to get our own cipher spec and finished messages
		sent out by the caller.
*/
		if (ssl->flags & SSL_FLAGS_SERVER) {
			if (!(ssl->flags & SSL_FLAGS_RESUMED)) {
				rc = SSL_PROCESS_DATA;
			}
		} else {
			if (ssl->flags & SSL_FLAGS_RESUMED) {
				rc = SSL_PROCESS_DATA;
			}
		}
#ifdef USE_CLIENT_SIDE_SSL
/*
		Free handshake pool, of which the cert is the primary member.
		There is also an attempt to free the handshake pool during
		the sending of the finished message to deal with client
		and server and differing handshake types.  Both cases are 
		attempted keep the lifespan of this pool as short as possible.
		This is the default case for the server side.
*/
		if (ssl->sec.cert) {
			matrixX509FreeCert(ssl->sec.cert);
			ssl->sec.cert = NULL;
		}
#endif /* USE_CLIENT_SIDE */
		break;

#ifdef USE_CLIENT_SIDE_SSL
	case SSL_HS_HELLO_REQUEST:
/*	
		No body message and the only one in record flight
*/
		if (end - c != 0) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid hello request message\n", NULL);
			return SSL_ERROR;
		}
/*
		Intentionally not changing state here to SERVER_HELLO.  The
		encodeResponse case	this will fall into needs to distinguish
		between calling the normal sslEncodeResponse or encodeClientHello.
		The HELLO_REQUEST state is used to make that determination and the
		writing of CLIENT_HELLO will properly move the state along itself.
*/
		rc = SSL_PROCESS_DATA;
		break;

	case SSL_HS_SERVER_HELLO: 
/*
		First two bytes are the negotiated SSL version
		We support only 3.0 (other options are 2.0 or 3.1)
*/
		if (end - c < 2) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid ssl header version length\n", NULL);
			return SSL_ERROR;
		}
		ssl->reqMajVer = *c; c++;
		ssl->reqMinVer = *c; c++;
		if (ssl->reqMajVer != ssl->majVer) {
			ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
			matrixIntDebugMsg("Unsupported ssl version: %d\n", ssl->reqMajVer);
			return SSL_ERROR;
		}
		
/*
		Next is a 32 bytes of random data for key generation
		and a single byte with the session ID length
*/
		if (end - c < SSL_HS_RANDOM_SIZE + 1) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid length of random data\n", NULL);
			return SSL_ERROR;
		}
		memcpy(ssl->sec.serverRandom, c, SSL_HS_RANDOM_SIZE);
		c += SSL_HS_RANDOM_SIZE;
		sessionIdLen = *c; c++;
		if (sessionIdLen > SSL_MAX_SESSION_ID_SIZE || 
				end - c < sessionIdLen) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			return SSL_ERROR;
		}
/*
		If a session length was specified, the server has sent us a
		session Id.  We may have requested a specific session, and the
		server may or may not agree to use that session.
*/
		if (sessionIdLen > 0) {
			if (ssl->sessionIdLen > 0) {
				if (memcmp(ssl->sessionId, c, sessionIdLen) == 0) {
					ssl->flags |= SSL_FLAGS_RESUMED;
				} else {
					ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
					memset(ssl->sec.masterSecret, 0x0, SSL_HS_MASTER_SIZE);
					ssl->sessionIdLen = sessionIdLen;
					memcpy(ssl->sessionId, c, sessionIdLen);
					ssl->flags &= ~SSL_FLAGS_RESUMED;
				}
			} else {
				ssl->sessionIdLen = sessionIdLen;
				memcpy(ssl->sessionId, c, sessionIdLen);
			}
			c += sessionIdLen;
		} else {
			if (ssl->sessionIdLen > 0) {
				ssl->cipher = sslGetCipherSpec(SSL_NULL_WITH_NULL_NULL);
				memset(ssl->sec.masterSecret, 0x0, SSL_HS_MASTER_SIZE);
				ssl->sessionIdLen = 0;
				memset(ssl->sessionId, 0x0, SSL_MAX_SESSION_ID_SIZE);
				ssl->flags &= ~SSL_FLAGS_RESUMED;
			}
		}
/*
		Next is the two byte cipher suite
*/
		if (end - c < 2) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid cipher suite length\n", NULL);
			return SSL_ERROR;
		}
		cipher = *c << 8; c++;
		cipher += *c; c++;

/*
		A resumed session can only match the cipher originally 
		negotiated. Otherwise, match the first cipher that we support
*/
		if (ssl->flags & SSL_FLAGS_RESUMED) {
			sslAssert(ssl->cipher);
			if (ssl->cipher->id != cipher) {
				ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
				matrixStrDebugMsg("Can't support resumed cipher\n", NULL);
				return SSL_ERROR;
			}
		} else {
			if ((ssl->cipher = sslGetCipherSpec(cipher)) == NULL) {
				ssl->err = SSL_ALERT_HANDSHAKE_FAILURE;
				matrixStrDebugMsg("Can't support requested cipher\n", NULL);
				return SSL_ERROR;
			}
		}

/*
		Decode the compression parameters.  Always zero.
		There are no compression schemes defined for SSLv3
*/
		if (end - c < 1 || *c != 0) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid compression value\n", NULL);
			return SSL_ERROR;
		}
/*
		At this point, if we're resumed, we have all the required info
		to derive keys.  The next handshake message we expect is
		the Finished message.
*/
		c++;
		if (ssl->flags & SSL_FLAGS_RESUMED) {
			sslDeriveKeys(ssl);
			ssl->hsState = SSL_HS_FINISHED;
		} else {
			ssl->hsState = SSL_HS_CERTIFICATE;
		}
		break;

	case SSL_HS_CERTIFICATE: 
		if (end - c < 3) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid Certificate message\n", NULL);
			return SSL_ERROR;
		}
		certChainLen = *c << 16; c++;
		certChainLen |= *c << 8; c++;
		certChainLen |= *c; c++;
		if (certChainLen == 0) {
			if (ssl->majVer == SSL3_MAJ_VER && ssl->minVer == SSL3_MIN_VER) {
				ssl->err = SSL_ALERT_NO_CERTIFICATE;
			} else {
				ssl->err = SSL_ALERT_BAD_CERTIFICATE;
			}
			matrixStrDebugMsg("No certificate sent to verify\n", NULL);
			return SSL_ERROR;
		}
		if (end - c < 3) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid Certificate message\n", NULL);
			return SSL_ERROR;
		}

		if (!(ssl->flags & SSL_FLAGS_SERVER)) {
/*
			As a client, we are aware we are in an RSA authentication state
			at this point.  And now that we have a handshake pool, storage
			for the known premaster secret can be allocated.
*/
			ssl->sec.premasterSize = SSL_HS_RSA_PREMASTER_SIZE;
			ssl->sec.premaster = psMalloc(ssl->hsPool,
				SSL_HS_RSA_PREMASTER_SIZE);
		}

		i = 0;
		while (certChainLen > 0) {
			certLen = *c << 16; c++;
			certLen |= *c << 8; c++;
			certLen |= *c; c++;

			if (end - c < certLen) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid certificate length\n", NULL);
				return SSL_ERROR;
			}
/*
			Extract the binary cert message into the cert structure
*/
			if ((parseLen = matrixX509ParseCert(ssl->hsPool, c, certLen, &cert)) < 0) {
				ssl->err = SSL_ALERT_BAD_CERTIFICATE;
				matrixStrDebugMsg("Can't parse certificate\n", NULL);
				return SSL_ERROR;
			}
			c += parseLen;

			if (i++ == 0) {
				ssl->sec.cert = cert;
				currentCert = ssl->sec.cert;
			} else {
				currentCert->next = cert;
				currentCert = currentCert->next;
			}
			certChainLen -= (certLen + 3);
		}
/*
		May have received a chain of certs in the message.  Spec says they
		must be in order so that each subsequent one is the parent of the
		previous.  Confirm this now.
*/
		if (matrixX509ValidateCertChain(ssl->hsPool, ssl->sec.cert,
				&subjectCert, &valid) < 0) {
			ssl->err = SSL_ALERT_BAD_CERTIFICATE;
			matrixStrDebugMsg("Couldn't validate certificate chain\n", NULL);
			return SSL_ERROR;	
		}
/*
		There may not be a caCert set.  The validate implemenation will just
		take the subject cert and make sure it is a self signed cert.
*/
		if (matrixX509ValidateCert(ssl->hsPool, subjectCert, 
				ssl->keys == NULL ? NULL : ssl->keys->caCerts,
				&subjectCert->valid) < 0) {
			ssl->err = SSL_ALERT_BAD_CERTIFICATE;
			matrixStrDebugMsg("Error validating certificate\n", NULL);
			return SSL_ERROR;
		}
		if (subjectCert->valid < 0) {
			matrixStrDebugMsg(
				"Warning: Cert did not pass default validation checks\n", NULL);
/*
			If there is no user callback, fail on validation check because there
			will be no intervention to give it a second look.
*/
			if (ssl->sec.validateCert == NULL) {
				ssl->err = SSL_ALERT_BAD_CERTIFICATE;
				return SSL_ERROR;
			}
		}
/*
		Call the user validation function with the entire cert chain.  The user
		will proabably want to drill down to the last cert to make sure it
		has been properly validated by a CA on this side.

		Need to return from user validation space with knowledge
		that this is an ANONYMOUS connection.
*/
		if ((anonCheck = matrixX509UserValidator(ssl->hsPool, ssl->sec.cert, 
				ssl->sec.validateCert, ssl->sec.validateCertArg)) < 0) {
			ssl->err = SSL_ALERT_BAD_CERTIFICATE;
			return SSL_ERROR;
		}
/*
		Set the flag that is checked by the matrixSslGetAnonStatus API
*/
		if (anonCheck == SSL_ALLOW_ANON_CONNECTION) {
			ssl->sec.anon = 1;
		} else {
			ssl->sec.anon = 0;
		}

/*
		Either a client or server could have been processing the cert as part of
		the authentication process.  If server, we move to the client key
		exchange state.
*/
		if (ssl->flags & SSL_FLAGS_SERVER) {
			ssl->hsState = SSL_HS_CLIENT_KEY_EXCHANGE;
		} else {
			ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
		}
		break;

	case SSL_HS_SERVER_HELLO_DONE: 
		if (hsLen != 0) {
			ssl->err = SSL_ALERT_BAD_CERTIFICATE;
			matrixStrDebugMsg("Can't validate certificate\n", NULL);
			return SSL_ERROR;
		}
		ssl->hsState = SSL_HS_FINISHED;
		rc = SSL_PROCESS_DATA;
		break;

	case SSL_HS_CERTIFICATE_REQUEST: 
		if (hsLen < 4) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid Certificate Request message\n", NULL);
			return SSL_ERROR;
		}
/*
		We only have RSA_SIGN types.  Make sure server can accept them
*/
		certMatch = 0;
		certTypeLen = *c++;
		if (end - c < certTypeLen) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid Certificate Request message\n", NULL);
			return SSL_ERROR;
		}
		while (certTypeLen-- > 0) {
			if (*c++ == RSA_SIGN) {
				certMatch = 1;
			}
		}
		if (certMatch == 0) {
			ssl->err = SSL_ALERT_UNSUPPORTED_CERTIFICATE;
			matrixStrDebugMsg("Can only support RSA_SIGN cert authentication\n",
				NULL);
			return SSL_ERROR;
		}
		certChainLen = *c << 8; c++;
		certChainLen |= *c; c++;
        if (end - c < certChainLen) {
			ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
			matrixStrDebugMsg("Invalid Certificate Request message\n", NULL);
			return SSL_ERROR;
		}
/*
		Check the passed in DNs against our cert issuer to see if they match.
		Only supporting a single cert on the client side.
*/
		ssl->sec.certMatch = 0;
		while (certChainLen > 0) {
			certLen = *c << 8; c++;
			certLen |= *c; c++;
			if (end - c < certLen) {
				ssl->err = SSL_ALERT_ILLEGAL_PARAMETER;
				matrixStrDebugMsg("Invalid CertificateRequest message\n", NULL);
				return SSL_ERROR;
			}
			c += certLen;
			certChainLen -= (2 + certLen);
		}
		ssl->hsState = SSL_HS_SERVER_HELLO_DONE;
		break;
#endif /* USE_CLIENT_SIDE_SSL */

	case SSL_HS_SERVER_KEY_EXCHANGE:
		ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
		return SSL_ERROR;

	default:
		ssl->err = SSL_ALERT_UNEXPECTED_MESSAGE;
		return SSL_ERROR;
	}
/*
	if we've got more data in the record, the sender has packed
	multiple handshake messages in one record.  Parse the next one.
*/
	if (c < end) {
		goto parseHandshake;
	}
	return rc;
}