Exemplo n.º 1
0
/*
	Add a pre-shared key and ID to the static table in the first NULL spot
*/
int32 matrixSslLoadPsk(sslKeys_t *keys, unsigned char *key, uint32 keyLen,
				unsigned char *id, uint32 idLen)
{
	psPsk_t		*psk, *list;

	if (keys == NULL || key == NULL || id == NULL) {
		return PS_ARG_FAIL;
	}
	if (keyLen > SSL_PSK_MAX_KEY_SIZE) {
		psTraceIntInfo("Can't add PSK.  Key too large: %d\n", keyLen);
		return PS_ARG_FAIL;
	}

	if (idLen > SSL_PSK_MAX_ID_SIZE) {
		psTraceIntInfo("Can't add PSK.  Key ID too large: %d\n", idLen);
		return PS_ARG_FAIL;
	}

	if (keyLen < 1 || idLen < 1) {
		psTraceInfo("Can't add PSK. Both key and identity length must be >0\n");
		return PS_ARG_FAIL;
	}
	
	if ((psk = psMalloc(keys->pool, sizeof(psPsk_t))) == NULL) {
		return PS_MEM_FAIL;
	}
	memset(psk, 0, sizeof(psPsk_t));
	
	if ((psk->pskKey = psMalloc(keys->pool, keyLen)) == NULL) {
		psFree(psk);
		return PS_MEM_FAIL;
	}
	if ((psk->pskId = psMalloc(keys->pool, idLen)) == NULL) {
		psFree(psk->pskKey);
		psFree(psk);
		return PS_MEM_FAIL;
	}
	memcpy(psk->pskKey, key, keyLen);
	psk->pskLen = keyLen;
	
	memcpy(psk->pskId, id, idLen);
	psk->pskIdLen = idLen;
	
	if (keys->pskKeys == NULL) {
		keys->pskKeys = psk;
	} else {
		list = keys->pskKeys;
		while (list->next != NULL) {
			list = list->next;
		}
		list->next = psk;
	}
		
	return 0;
}
Exemplo n.º 2
0
/*
	This public API allows the user to encrypt the plaintext buffer of their
	choice into the internal outbuf that is retrieved when matrixSslGetOutdata
	is called.  This is non-in-situ support and will leave the callers
	plaintext buffer intact

	ptBuf	The plaintext buffer to be converted into an SSL application data
			record.
	len		The length, in bytes, of the ptBuf plaintext data

	Returns < 0 on error, total #bytes in outgoing data buf on success
*/
int32 matrixSslEncodeToOutdata(ssl_t *ssl, unsigned char *ptBuf, uint32 len)
{
	unsigned char	*internalBuf;
	int32			rc, fragLen, recLen, index;

	if (!ssl || !ptBuf) {
		return PS_ARG_FAIL;
	}
	if (ssl->bFlags & BFLAG_CLOSE_AFTER_SENT) {
		return PS_PROTOCOL_FAIL;
	}

#ifdef USE_DTLS
	if (ssl->flags & SSL_FLAGS_DTLS) {
		rc = matrixSslGetEncodedSize(ssl, len);
		if (rc > matrixDtlsGetPmtu()) {
			return PS_LIMIT_FAIL;
		}
	}
#endif

	/* Fragmentation support */
	index = 0;
	while (len > 0) {
		/*	We just call matrixSslGetWritebuf to prepare the buffer */
		if ((rc = matrixSslGetWritebuf(ssl, &internalBuf, len)) < 0) {
			psTraceIntInfo("matrixSslEncodeToOutbuf allocation error: %d\n",
				rc);
			return rc;
		}
		recLen = fragLen = min((uint32)rc, len);
		psAssert(ssl->outsize > 0 && ssl->outbuf != NULL);

		if (ssl->outbuf == NULL ||
				(ssl->outsize - ssl->outlen) < (int32)fragLen) {
			return PS_FAILURE;
		}
		internalBuf = ssl->outbuf + ssl->outlen;

		rc = matrixSslEncode(ssl, internalBuf, (ssl->outsize - ssl->outlen),
			ptBuf + index, (uint32*)&fragLen);
		if (rc < 0) {
			psAssert(rc != SSL_FULL);	/* should not happen */
			return PS_FAILURE;
		}
		index += recLen;
		len -= recLen;
#ifdef USE_MATRIXSSL_STATS
		matrixsslUpdateStat(ssl, APP_DATA_SENT_STAT, fragLen);
#endif
		ssl->outlen += fragLen;
	}
	return ssl->outlen;
}
Exemplo n.º 3
0
void matrixSslPrintHSDetails(ssl_t *ssl)
{
	if (ssl->hsState == SSL_HS_DONE) {
		psTraceInfo("\n");
		if (ssl->minVer == SSL3_MIN_VER) {
			psTraceInfo("SSL 3.0 ");
		} else if (ssl->minVer == TLS_MIN_VER) {
			psTraceInfo("TLS 1.0 ");
		} else if (ssl->minVer == TLS_1_1_MIN_VER) {
			psTraceInfo("TLS 1.1 ");
		} else if (ssl->minVer == TLS_1_2_MIN_VER) {
			psTraceInfo("TLS 1.2 ");
		}
		psTraceInfo("connection established: ");
		switch (ssl->cipher->ident) {
			case SSL_RSA_WITH_NULL_MD5:
				psTraceInfo("SSL_RSA_WITH_NULL_MD5\n");
				break;
			case SSL_RSA_WITH_NULL_SHA:
				psTraceInfo("SSL_RSA_WITH_NULL_SHA\n");
				break;
			case SSL_RSA_WITH_RC4_128_MD5:
				psTraceInfo("SSL_RSA_WITH_RC4_128_MD5\n");
				break;
			case SSL_RSA_WITH_RC4_128_SHA:
				psTraceInfo("SSL_RSA_WITH_RC4_128_SHA\n");
				break;
			case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
				psTraceInfo("SSL_RSA_WITH_3DES_EDE_CBC_SHA\n");
				break;
			case TLS_RSA_WITH_AES_128_CBC_SHA:
				psTraceInfo("TLS_RSA_WITH_AES_128_CBC_SHA\n");
				break;
			case TLS_RSA_WITH_AES_256_CBC_SHA:
				psTraceInfo("TLS_RSA_WITH_AES_256_CBC_SHA\n");
				break;
			default:
				psTraceIntInfo("!!!! DEFINE ME %d !!!!\n", ssl->cipher->ident);
		}
		//psTraceBytes("	Master Secret", ssl->sec.masterSecret,
		//	SSL_HS_MASTER_SIZE);
	}
	return;
}
Exemplo n.º 4
0
/*
	Called after key load if CRL location is expected to be embedded in the CA.
	The user callback will be invoked with the URL and the responsibility of
	the callback is to fetch the CRL and load it to the CA with matrixSslLoadCRL

	The numLoaded parameter indicates how many successful CRLs were loaded
	if there are multiple CA files being processed here.

	Return codes:
	< 0 - Error loading a CRL.  numLoaded indicates if some success
	0 - No errors encountered.  numLoaded could be 0 if no CRLs found
*/
int32 matrixSslGetCRL(sslKeys_t	*keys, int32 (*crlCb)(psPool_t *pool,
			psX509Cert_t *CA, int append, char *url, uint32 urlLen),
			int32 *numLoaded)
{
	psX509Cert_t		*CA;
	x509GeneralName_t	*gn;
	unsigned char		*crlURI;
	int32				rc, crlURILen;

	if (keys->CAcerts == NULL || crlCb == NULL) {
		return PS_ARG_FAIL;
	}
	CA = keys->CAcerts;

	*numLoaded = rc = 0;
	while (CA) {
		if (CA->extensions.bc.cA > 0 && CA->extensions.crlDist != NULL) {
			gn = CA->extensions.crlDist;
			while (gn) {
				if (gn->id == 6) { /* Only pass on URI types */
					crlURI = gn->data;
					crlURILen = gn->dataLen;
					/* Invoke user callback to go fetch and load the CRL.
						Do not use the append flag.  The specification says
						that multiple names must be mechanims to access the
						same CRL. */
					if (crlCb(keys->pool, CA, 0, (char*)crlURI,
							crlURILen) < 0) {
						rc = -1;
					}
					(*numLoaded)++; /* Callback successfully loaded this CRL */
				} else {
					psTraceIntInfo("Unsupported CRL distro point format %d\n",
						gn->id);
				}
				gn = gn->next;
			}
		}
		CA = CA->next;
	}
	return rc;
}
Exemplo n.º 5
0
/*
	Get the key from the pre-shared list based on id
*/
int32 matrixSslPskGetKey(ssl_t *ssl, unsigned char *id, uint32 idLen,
		unsigned char **key, uint32 *keyLen)
{
	psPsk_t	*psk;

	*key = NULL;

	psk = ssl->keys->pskKeys;

	if (psk == NULL) {
		psTraceInfo("No pre-shared keys loaded\n");
		return PS_FAILURE;
	}
	
	if (idLen <= 0) {
		psTraceIntInfo("Bad PSK identity length: %d\n", idLen);
		return PS_ARG_FAIL;
	}

/*
	Make sure the length matches as well
*/
	while (psk) {
		if ((uint32)psk->pskIdLen == idLen) {
			if (memcmp(psk->pskId, id, idLen) == 0) {
				*key = psk->pskKey;
				*keyLen = psk->pskLen;
				return PS_SUCCESS;
			}
		}
		psk = psk->next;
	}

	psTraceInfo("Can't find PSK key from id\n");
	return PS_SUCCESS;
}
Exemplo n.º 6
0
/*
	Non-blocking socket event handler
	Wait one time in select for events on any socket
	This will accept new connections, read and write to sockets that are
	connected, and close sockets as required.
 */
static int32 selectLoop(sslKeys_t *keys, SOCKET lfd)
{
	httpConn_t		*cp;
	psTime_t		now;
	DLListEntry		connsTmp;
	DLListEntry		*pList;
	
	fd_set			readfd, writefd;
	struct timeval	timeout;
	SOCKET			fd, maxfd;
	
	unsigned char	*buf;
	int32			rc, len, transferred, val;
	unsigned char	rSanity, wSanity, acceptSanity;
	
	DLListInit(&connsTmp);
	rc = PS_SUCCESS;
	maxfd = INVALID_SOCKET;
	timeout.tv_sec = SELECT_TIME / 1000;
	timeout.tv_usec = (SELECT_TIME % 1000) * 1000;
	FD_ZERO(&readfd);
	FD_ZERO(&writefd);
	
	/* Always set readfd for listening socket */
	FD_SET(lfd, &readfd);
	if (lfd > maxfd) {
		maxfd = lfd;
	}
/*	
	Check timeouts and set readfd and writefd for connections as required.
	We use connsTemp so that removal on error from the active iteration list
		doesn't interfere with list traversal 
 */
	psGetTime(&now);
	while (!DLListIsEmpty(&g_conns)) {
		pList = DLListGetHead(&g_conns);
		cp = DLListGetContainer(pList, httpConn_t, List);
		DLListInsertTail(&connsTmp, &cp->List);
		/*	If timeout != 0 msec ith no new data, close */
		if (cp->timeout && (psDiffMsecs(cp->time, now) > (int32)cp->timeout)) {
			closeConn(cp, PS_TIMEOUT_FAIL);
			continue;	/* Next connection */
		}
		/* Always select for read */
		FD_SET(cp->fd, &readfd);
		/* Select for write if there's pending write data or connection */
		if (matrixSslGetOutdata(cp->ssl, NULL) > 0) {
			FD_SET(cp->fd, &writefd);
		}
		/* Housekeeping for maxsock in select call */
		if (cp->fd > maxfd) {
			maxfd = cp->fd;
		}
	}
	
	/* Use select to check for events on the sockets */
	if ((val = select(maxfd + 1, &readfd, &writefd, NULL, &timeout)) <= 0) {
		/* On error, restore global connections list */
		while (!DLListIsEmpty(&connsTmp)) {
			pList = DLListGetHead(&connsTmp);
			cp = DLListGetContainer(pList, httpConn_t, List);
			DLListInsertTail(&g_conns, &cp->List);
		}
		/* Select timeout */
		if (val == 0) {
			return PS_TIMEOUT_FAIL;
		}
		/* Woke due to interrupt */
		if (SOCKET_ERRNO == EINTR) {
			return PS_TIMEOUT_FAIL;
		}
		/* Should attempt to handle more errnos, such as EBADF */
		return PS_PLATFORM_FAIL;
	}
	
	/* Check listener for new incoming socket connections */
	if (FD_ISSET(lfd, &readfd)) {
		for (acceptSanity = 0; acceptSanity < ACCEPT_QUEUE; acceptSanity++) {
			fd = accept(lfd, NULL, NULL);
			if (fd == INVALID_SOCKET) {
				break;	/* Nothing more to accept; next listener */
			}
			setSocketOptions(fd);
			cp = malloc(sizeof(httpConn_t));
			if ((rc = matrixSslNewServerSession(&cp->ssl, keys, certCb)) < 0) {
				close(fd); fd = INVALID_SOCKET;
				continue;
			}
			cp->fd = fd;
			fd = INVALID_SOCKET;
			cp->timeout = SSL_TIMEOUT;
			psGetTime(&cp->time);
			cp->parsebuf = NULL;
			cp->parsebuflen = 0;
			DLListInsertTail(&connsTmp, &cp->List);
			/* Fake that there is read data available, no harm if there isn't */
			FD_SET(cp->fd, &readfd);
/*			_psTraceInt("=== New Client %d ===\n", cp->fd); */
		}
	}
	
	/* Check each connection for read/write activity */
	while (!DLListIsEmpty(&connsTmp)) {
		pList = DLListGetHead(&connsTmp);
		cp = DLListGetContainer(pList, httpConn_t, List);
		DLListInsertTail(&g_conns, &cp->List);
		
		rSanity = wSanity = 0;
/*
		See if there's pending data to send on this connection
		We could use FD_ISSET, but this is more reliable for the current
			state of data to send.
 */
WRITE_MORE:
		if ((len = matrixSslGetOutdata(cp->ssl, &buf)) > 0) {
			/* Could get a EWOULDBLOCK since we don't check FD_ISSET */
			transferred = send(cp->fd, buf, len, MSG_DONTWAIT);
			if (transferred <= 0) {
#ifdef WIN32
				if (SOCKET_ERRNO != EWOULDBLOCK &&
					SOCKET_ERRNO != WSAEWOULDBLOCK) {

#else
				if (SOCKET_ERRNO != EWOULDBLOCK) {
#endif
					closeConn(cp, PS_PLATFORM_FAIL);
					continue;	/* Next connection */
				}
			} else {
				/* Indicate that we've written > 0 bytes of data */
				if ((rc = matrixSslSentData(cp->ssl, transferred)) < 0) {
					closeConn(cp, PS_ARG_FAIL);
					continue;	/* Next connection */
				}
				if (rc == MATRIXSSL_REQUEST_CLOSE) {
					closeConn(cp, MATRIXSSL_REQUEST_CLOSE);
					continue;	/* Next connection */
				} else if (rc == MATRIXSSL_HANDSHAKE_COMPLETE) {
					/* If the protocol is server initiated, send data here */
#ifdef ENABLE_FALSE_START					
					/* OR this could be a Chrome browser using 
						FALSE_START and the application data is already
						waiting in our inbuf for processing */
					if ((rc = matrixSslReceivedData(cp->ssl, 0,
								&buf, (uint32*)&len)) < 0) {
							closeConn(cp, 0);
							continue;	/* Next connection */
					}
					if (rc > 0) { /* There was leftover data */
						goto PROCESS_MORE;
					}
#endif /* ENABLE_FALSE_START  */
					
				}
				/* Update activity time */
				psGetTime(&cp->time);
				/* Try to send again if more data to send */
				if (rc == MATRIXSSL_REQUEST_SEND || transferred < len) {
					if (wSanity++ < GOTO_SANITY) goto WRITE_MORE;
				}
			}
		} else if (len < 0) {
			closeConn(cp, PS_ARG_FAIL);
			continue;	/* Next connection */
		}
		
/*
		Check the file descriptor returned from select to see if the connection
		has data to be read
 */
		if (FD_ISSET(cp->fd, &readfd)) {
READ_MORE:
			/* Get the ssl buffer and how much data it can accept */
			/* Note 0 is a return failure, unlike with matrixSslGetOutdata */
			if ((len = matrixSslGetReadbuf(cp->ssl, &buf)) <= 0) {
				closeConn(cp, PS_ARG_FAIL);
				continue;	/* Next connection */
			}
			if ((transferred = recv(cp->fd, buf, len, MSG_DONTWAIT)) < 0) {
				/* We could get EWOULDBLOCK despite the FD_ISSET on goto  */
#ifdef WIN32
				if (SOCKET_ERRNO != EWOULDBLOCK &&
					SOCKET_ERRNO != WSAEWOULDBLOCK) {

#else
				if (SOCKET_ERRNO != EWOULDBLOCK) {
#endif
					closeConn(cp, PS_PLATFORM_FAIL);
				}
				continue;	/* Next connection */
			}
			/* If EOF, remote socket closed. This is semi-normal closure.
			   Officially, we should close on closure alert. */
			if (transferred == 0) {
/*				psTraceIntInfo("Closing connection %d on EOF\n", cp->fd); */
				closeConn(cp, 0);
				continue;	/* Next connection */
			}
/*
			Notify SSL state machine that we've received more data into the
			ssl buffer retreived with matrixSslGetReadbuf.
 */
			if ((rc = matrixSslReceivedData(cp->ssl, (int32)transferred, &buf, 
											(uint32*)&len)) < 0) {
				closeConn(cp, 0);
				continue;	/* Next connection */
			}
			/* Update activity time */
			psGetTime(&cp->time);
			
PROCESS_MORE:
			/* Process any incoming plaintext application data */
			switch (rc) {
				case MATRIXSSL_HANDSHAKE_COMPLETE:
					/* If the protocol is server initiated, send data here */
					goto READ_MORE;
				case MATRIXSSL_APP_DATA:
					/* Remember, must handle if len == 0! */
					if ((rc = httpBasicParse(cp, buf, len)) < 0) {
						_psTrace("Couldn't parse HTTP data.  Closing conn.\n");
						closeConn(cp, PS_PROTOCOL_FAIL);
						continue; /* Next connection */
					}
					if (rc == HTTPS_COMPLETE) {
						if (httpWriteResponse(cp->ssl) < 0) {
							closeConn(cp, PS_PROTOCOL_FAIL);
							continue; /* Next connection */
						}
						/* For HTTP, we assume no pipelined requests, so we 
						 close after parsing a single HTTP request */
						/* Ignore return of closure alert, it's optional */
						matrixSslEncodeClosureAlert(cp->ssl);
						rc = matrixSslProcessedData(cp->ssl, &buf, (uint32*)&len);
						if (rc > 0) {
							/* Additional data is available, but we ignore it */
							_psTrace("HTTP data parsing not supported, ignoring.\n");
							closeConn(cp, PS_SUCCESS);
							continue; /* Next connection */
						} else if (rc < 0) {
							closeConn(cp, PS_PROTOCOL_FAIL);
							continue; /* Next connection */
						}
						/* rc == 0, write out our response and closure alert */
						goto WRITE_MORE;
					}
					/* We processed a partial HTTP message */
					if ((rc = matrixSslProcessedData(cp->ssl, &buf, (uint32*)&len)) == 0) {
						goto READ_MORE;
					}
					goto PROCESS_MORE;
				case MATRIXSSL_REQUEST_SEND:
					/* Prevent us from reading again after the write,
					 although that wouldn't be the end of the world */
					FD_CLR(cp->fd, &readfd);
					if (wSanity++ < GOTO_SANITY) goto WRITE_MORE;
					break;
				case MATRIXSSL_REQUEST_RECV:
					if (rSanity++ < GOTO_SANITY) goto READ_MORE; 
					break;
				case MATRIXSSL_RECEIVED_ALERT:
					/* The first byte of the buffer is the level */
					/* The second byte is the description */
					if (*buf == SSL_ALERT_LEVEL_FATAL) {
						psTraceIntInfo("Fatal alert: %d, closing connection.\n", 
									*(buf + 1));
						closeConn(cp, PS_PROTOCOL_FAIL);
						continue; /* Next connection */
					}
					/* Closure alert is normal (and best) way to close */
					if (*(buf + 1) == SSL_ALERT_CLOSE_NOTIFY) {
						closeConn(cp, PS_SUCCESS);
						continue; /* Next connection */
					}
					psTraceIntInfo("Warning alert: %d\n", *(buf + 1));
					if ((rc = matrixSslProcessedData(cp->ssl, &buf, (uint32*)&len)) == 0) {
						/* No more data in buffer. Might as well read for more. */
						goto READ_MORE;
					}
					goto PROCESS_MORE;

				default:
					/* If rc <= 0 we fall here */
					closeConn(cp, PS_PROTOCOL_FAIL);
					continue; /* Next connection */
			}
			/* Always try to read more if we processed some data */
			if (rSanity++ < GOTO_SANITY) goto READ_MORE;
		} /*  readfd handling */
	}	/* connection loop */
	return PS_SUCCESS;
}

/******************************************************************************/
/*
	Create an HTTP response and encode it to the SSL buffer
 */
#define	TEST_SIZE	16000
static int32 httpWriteResponse(ssl_t *cp)
{
	unsigned char	*buf;
	int32			available;
	
	if ((available = matrixSslGetWritebuf(cp, &buf, 
							strlen((char *)g_httpResponseHdr) + 1)) < 0) {
		return PS_MEM_FAIL;
	}
	strncpy((char *)buf, (char *)g_httpResponseHdr, available);
	if (matrixSslEncodeWritebuf(cp, strlen((char *)buf)) < 0) {
		return PS_MEM_FAIL;
	}
	return MATRIXSSL_REQUEST_SEND;
}

/******************************************************************************/
/*
	Main non-blocking SSL server
	Initialize MatrixSSL and sockets layer, and loop on select
 */
int32 main(int32 argc, char **argv)
{
	sslKeys_t		*keys;
	SOCKET			lfd;
	int32			err, rc;
#ifdef WIN32
	WSADATA			wsaData;
	WSAStartup(MAKEWORD(1, 1), &wsaData);
#endif


	keys = NULL;
	DLListInit(&g_conns);
	g_exitFlag = 0;
	lfd = INVALID_SOCKET;
	
#ifdef POSIX
	if (sighandlers() < 0) {
		return PS_PLATFORM_FAIL;
	}
#endif	/* POSIX */
	if ((rc = matrixSslOpen()) < 0) {
		_psTrace("MatrixSSL library init failure.  Exiting\n");
		return rc;
	}
	if (matrixSslNewKeys(&keys) < 0) {
		_psTrace("MatrixSSL library key init failure.  Exiting\n");
		return -1;
	}

#ifdef USE_HEADER_KEYS
/*
	In-memory based keys
*/
	if ((rc = matrixSslLoadRsaKeysMem(keys, certSrvBuf, sizeof(certSrvBuf),
				   privkeySrvBuf, sizeof(privkeySrvBuf), NULL, 0)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#else /* USE_HEADER_KEYS */
/*
	File based keys
*/
	if ((rc = matrixSslLoadRsaKeys(keys, certSrvFile, privkeySrvFile, NULL,
			NULL)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif /* USE_HEADER_KEYS */


	/* Create the listening socket that will accept incoming connections */
	if ((lfd = socketListen(HTTPS_PORT, &err)) == INVALID_SOCKET) {
		_psTraceInt("Can't listen on port %d\n", HTTPS_PORT);
		goto L_EXIT;
	}

	/* Main select loop to handle sockets events */
	while (!g_exitFlag) {
		selectLoop(keys, lfd);
	}

L_EXIT:
	if (lfd != INVALID_SOCKET) close(lfd);
	if (keys) matrixSslDeleteKeys(keys);
	matrixSslClose();
	
	return 0;
}
Exemplo n.º 7
0
/*
	Generate the key block as follows.  '+' indicates concatination.  
	key_block =
		MD5(master_secret + SHA(`A' + master_secret +
			ServerHello.random + ClientHello.random)) +
		MD5(master_secret + SHA(`BB' + master_secret +
			ServerHello.random + ClientHello.random)) +
		MD5(master_secret + SHA(`CCC' + master_secret +
			ServerHello.random + ClientHello.random)) + 
		[...];
*/
static int32 createKeyBlock(ssl_t *ssl, unsigned char *clientRandom,
						  unsigned char *serverRandom,
						  unsigned char *masterSecret, uint32 secretLen)
{
	psDigestContext_t	md5Ctx, sha1Ctx;
	unsigned char		buf[MD5_HASH_SIZE + SHA1_HASH_SIZE];
	unsigned char		*tmp;
	int32				ret = 0;
	uint32				i, keyIter, reqKeyLen;

/*
	We must generate enough key material to fill the various keys
*/
	reqKeyLen = 2 * ssl->cipher->macSize + 
				2 * ssl->cipher->keySize + 
				2 * ssl->cipher->ivSize;
/*
	Find the right number of iterations to make the requested length key block
*/
	keyIter = 1;
	while (MD5_HASH_SIZE * keyIter < reqKeyLen) {
		keyIter++;
	}
	if (keyIter > sizeof(salt)/sizeof(char*)) {
		psTraceIntInfo("Error: Not enough salt for key length %d\n", reqKeyLen);
		return PS_FAILURE;
	}

	tmp = ssl->sec.keyBlock;
	for (i = 0; i < keyIter; i++) {
		psSha1Init(&sha1Ctx);
		psSha1Update(&sha1Ctx, salt[i], i + 1);
		psSha1Update(&sha1Ctx, masterSecret, secretLen);
		psSha1Update(&sha1Ctx, serverRandom, SSL_HS_RANDOM_SIZE);
		psSha1Update(&sha1Ctx, clientRandom, SSL_HS_RANDOM_SIZE);
		psSha1Final(&sha1Ctx, buf);
		
		psMd5Init(&md5Ctx);
		psMd5Update(&md5Ctx, masterSecret, secretLen);
		psMd5Update(&md5Ctx, buf, SHA1_HASH_SIZE);
		psMd5Final(&md5Ctx, tmp);
		tmp += MD5_HASH_SIZE;
		ret += MD5_HASH_SIZE;
	}
	memset(buf, 0x0, MD5_HASH_SIZE + SHA1_HASH_SIZE);
/*
	Client and server use different read/write values, with the Client 
	write value being the server read value.
*/
	if (ssl->flags & SSL_FLAGS_SERVER) {
		ssl->sec.rMACptr = ssl->sec.keyBlock;
		ssl->sec.wMACptr = ssl->sec.rMACptr + ssl->cipher->macSize;
		ssl->sec.rKeyptr = ssl->sec.wMACptr + ssl->cipher->macSize;
		ssl->sec.wKeyptr = ssl->sec.rKeyptr + ssl->cipher->keySize;
		ssl->sec.rIVptr = ssl->sec.wKeyptr + ssl->cipher->keySize;
		ssl->sec.wIVptr = ssl->sec.rIVptr + ssl->cipher->ivSize;
	} else {
		ssl->sec.wMACptr = ssl->sec.keyBlock;
		ssl->sec.rMACptr = ssl->sec.wMACptr + ssl->cipher->macSize;
		ssl->sec.wKeyptr = ssl->sec.rMACptr + ssl->cipher->macSize;
		ssl->sec.rKeyptr = ssl->sec.wKeyptr + ssl->cipher->keySize;
		ssl->sec.wIVptr = ssl->sec.rKeyptr + ssl->cipher->keySize;
		ssl->sec.rIVptr = ssl->sec.wIVptr + ssl->cipher->ivSize;
	}

	return ret;
}
Exemplo n.º 8
0
/*
	Make a secure HTTP request to a defined IP and port
	Connection is made in blocking socket mode
	The connection is considered successful if the SSL/TLS session is
	negotiated successfully, a request is sent, and a HTTP response is received.
 */
static int32 httpsClientConnection(sslKeys_t *keys, sslSessionId_t *sid)
{
	int32			rc, transferred, len, complete;
	ssl_t			*ssl;
	unsigned char	*buf;
	httpConn_t		cp;
	SOCKET			fd;
	
	complete = 0;
	memset(&cp, 0x0, sizeof(httpConn_t));
	fd = socketConnect(HTTPS_IP, HTTPS_PORT, &rc);
	if (fd == INVALID_SOCKET || rc != PS_SUCCESS) {
		_psTraceInt("Connect failed: %d.  Exiting\n", rc);
		return PS_PLATFORM_FAIL;
	}
	
	rc = matrixSslNewClientSession(&ssl, keys, sid, 0, certCb, NULL, NULL);
	if (rc != MATRIXSSL_REQUEST_SEND) {
		_psTraceInt("New Client Session Failed: %d.  Exiting\n", rc);
		close(fd);
		return PS_ARG_FAIL;
	}
WRITE_MORE:
	while ((len = matrixSslGetOutdata(ssl, &buf)) > 0) {
		transferred = send(fd, buf, len, 0);
		if (transferred <= 0) {
			goto L_CLOSE_ERR;
		} else {
			/* Indicate that we've written > 0 bytes of data */
			if ((rc = matrixSslSentData(ssl, transferred)) < 0) {
				goto L_CLOSE_ERR;
			}
			if (rc == MATRIXSSL_REQUEST_CLOSE) {
				closeConn(ssl, fd);
				return MATRIXSSL_SUCCESS;
			} 
			if (rc == MATRIXSSL_HANDSHAKE_COMPLETE) {
				/* If we sent the Finished SSL message, initiate the HTTP req */
				/* (This occurs on a resumption handshake) */
				if (httpWriteRequest(ssl) < 0) {
					goto L_CLOSE_ERR;
				}
				goto WRITE_MORE;
			}
			/* SSL_REQUEST_SEND is handled by loop logic */
		}
	}
READ_MORE:
	if ((len = matrixSslGetReadbuf(ssl, &buf)) <= 0) {
		goto L_CLOSE_ERR;
	}
	if ((transferred = recv(fd, buf, len, 0)) < 0) {
		goto L_CLOSE_ERR;
	}
	/*	If EOF, remote socket closed. But we haven't received the HTTP response 
		so we consider it an error in the case of an HTTP client */
	if (transferred == 0) {
		goto L_CLOSE_ERR;
	}
	if ((rc = matrixSslReceivedData(ssl, (int32)transferred, &buf,
									(uint32*)&len)) < 0) {
		goto L_CLOSE_ERR;
	}
	
PROCESS_MORE:
	switch (rc) {
		case MATRIXSSL_HANDSHAKE_COMPLETE:
#ifdef REHANDSHAKE_TEST
/*
			Test rehandshake capabilities of server.  If a successful
			session resmption rehandshake occurs, this client will be last to
			send handshake data and MATRIXSSL_HANDSHAKE_COMPLETE will hit on
			the WRITE_MORE handler and httpWriteRequest will occur there.
			
			NOTE: If the server doesn't support session resumption it is
			possible to fall into an endless rehandshake loop
*/
			if (matrixSslEncodeRehandshake(ssl, NULL, NULL, 0, 0) < 0) {
				goto L_CLOSE_ERR;
			}
#else		
			/* We got the Finished SSL message, initiate the HTTP req */
			if (httpWriteRequest(ssl) < 0) {
				goto L_CLOSE_ERR;
			}
#endif
			goto WRITE_MORE;
		case MATRIXSSL_APP_DATA:
			if ((rc = httpBasicParse(&cp, buf, len)) < 0) {
				closeConn(ssl, fd);
				if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
				cp.parsebuflen = 0;
				return MATRIXSSL_ERROR;
			}
			if (rc == HTTPS_COMPLETE) {
				rc = matrixSslProcessedData(ssl, &buf, (uint32*)&len);
				closeConn(ssl, fd);
				if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
				cp.parsebuflen = 0;
				if (rc < 0) {
					return MATRIXSSL_ERROR;
				} else {
					if (rc > 0) {
						_psTrace("HTTP data parsing not supported, ignoring.\n");
					}
					_psTrace("SUCCESS: Received HTTP Response\n");
					return MATRIXSSL_SUCCESS;
				}
			}
			/* We processed a partial HTTP message */
			if ((rc = matrixSslProcessedData(ssl, &buf, (uint32*)&len)) == 0) {
				goto READ_MORE;
			}
			goto PROCESS_MORE;
		case MATRIXSSL_REQUEST_SEND:
			goto WRITE_MORE;
		case MATRIXSSL_REQUEST_RECV:
			goto READ_MORE;
		case MATRIXSSL_RECEIVED_ALERT:
			/* The first byte of the buffer is the level */
			/* The second byte is the description */
			if (*buf == SSL_ALERT_LEVEL_FATAL) {
				psTraceIntInfo("Fatal alert: %d, closing connection.\n", 
							*(buf + 1));
				goto L_CLOSE_ERR;
			}
			/* Closure alert is normal (and best) way to close */
			if (*(buf + 1) == SSL_ALERT_CLOSE_NOTIFY) {
				closeConn(ssl, fd);
				if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
				cp.parsebuflen = 0;
				return MATRIXSSL_SUCCESS;
			}
			psTraceIntInfo("Warning alert: %d\n", *(buf + 1));
			if ((rc = matrixSslProcessedData(ssl, &buf, (uint32*)&len)) == 0) {
				/* No more data in buffer. Might as well read for more. */
				goto READ_MORE;
			}
			goto PROCESS_MORE;
		default:
			/* If rc <= 0 we fall here */
			goto L_CLOSE_ERR;
	}
	
L_CLOSE_ERR:
	_psTrace("FAIL: No HTTP Response\n");
	matrixSslDeleteSession(ssl);
	close(fd);
	if (cp.parsebuf) free(cp.parsebuf); cp.parsebuf = NULL;
	cp.parsebuflen = 0;
	return MATRIXSSL_ERROR;
}
Exemplo n.º 9
0
/*
	Caller has received data from the network and is notifying the SSL layer
 */
int32 matrixSslReceivedData(ssl_t *ssl, uint32 bytes, unsigned char **ptbuf,
							uint32 *ptlen)
{
	unsigned char	*buf, *prevBuf;
	int32			rc, decodeRet, size, sanity, decodeErr;
	uint32			processed, start, len, reqLen;
	unsigned char	alertLevel, alertDesc;
	unsigned char	*p;

	if (!ssl || !ptbuf || !ptlen) {
		return PS_ARG_FAIL;
	}

	psAssert(ssl->outsize > 0 && ssl->outbuf != NULL);
	psAssert(ssl->insize > 0 && ssl->inbuf != NULL);
	*ptbuf = NULL;
	*ptlen = 0;
	ssl->inlen += bytes;
	if (ssl->inlen == 0) {
		return PS_SUCCESS; /* Nothing to do.  Basically a poll */
	}
	/* This is outside the loop b/c we may want to parse within inbuf later */
	buf = ssl->inbuf;
DECODE_MORE:
	/* Parameterized sanity check to avoid infinite loops */
	if (matrixSslHandshakeIsComplete(ssl)) {
		/* Minimum possible record size once negotiated */
		sanity = ssl->inlen / (SSL3_HEADER_LEN + MD5_HASH_SIZE);
	} else {
		/* Even with an SSLv2 hello, the sanity check will let 1 pass through */
		sanity = ssl->inlen / (SSL3_HEADER_LEN + SSL3_HANDSHAKE_HEADER_LEN);
	}
	if (sanity-- < 0) {
		return PS_PROTOCOL_FAIL;	/* We've tried to decode too many times */
	}
	len = ssl->inlen;
	size = ssl->insize - (buf - ssl->inbuf);
	prevBuf = buf;
	decodeRet = matrixSslDecode(ssl, &buf, &len, size, &start, &reqLen,
						 &decodeErr, &alertLevel, &alertDesc);

/*
	Convenience for the cases that expect buf to have moved
		- calculate the number of encoded bytes that were decoded
*/
	processed = buf - prevBuf;
	rc = PS_PROTOCOL_FAIL;
	switch (decodeRet) {

	case MATRIXSSL_SUCCESS:

		ssl->inlen -= processed;
		if (ssl->inlen > 0) {
			psAssert(buf > ssl->inbuf);
/*
			Pack ssl->inbuf so there is immediate maximum room for potential
			outgoing data that needs to be written
*/
			memmove(ssl->inbuf, buf, ssl->inlen);
			buf = ssl->inbuf;
			goto DECODE_MORE;	/* More data in buffer to process */
		}
/*
		In this case, we've parsed a finished message and no additional data is
		available to parse. We let the client know the handshake is complete,
		which can be used as a trigger to begin for example a HTTP request.
*/
		if (!(ssl->bFlags & BFLAG_HS_COMPLETE)) {
			if (matrixSslHandshakeIsComplete(ssl)) {
				ssl->bFlags |= BFLAG_HS_COMPLETE;
#ifdef USE_CLIENT_SIDE_SSL
				matrixSslGetSessionId(ssl, ssl->sid);
#endif /* USE_CLIENT_SIDE_SSL */
				rc = MATRIXSSL_HANDSHAKE_COMPLETE;
			} else {
				rc = MATRIXSSL_REQUEST_RECV; /* Need to recv more handshake data */
			}
		} else {
#ifdef USE_DTLS
			rc = MATRIXSSL_REQUEST_RECV; /* Got FINISHED without CCS */
#else
			/* This is an error - we shouldn't get here */
#endif
		}
		break;

#ifdef USE_DTLS
	case DTLS_RETRANSMIT:
		/* Only request a resend if last record in buffer */
		ssl->inlen -= processed;
		if (ssl->inlen > 0) {
			psAssert(buf > ssl->inbuf);
/*
			Pack ssl->inbuf so there is immediate maximum room for potential
			outgoing data that needs to be written
*/
			memmove(ssl->inbuf, buf, ssl->inlen);
			buf = ssl->inbuf;
			goto DECODE_MORE;	/* More data in buffer to process */
		}

		/* Flight will be rebuilt when matrixDtlsGetOutdata is called while
		outbuf is empty.  This is the return case where we are actually
		seeing a repeat handshake message so we know something was lost in
		flight. */
		return MATRIXSSL_REQUEST_SEND;
#endif

	case SSL_SEND_RESPONSE:
#ifdef ENABLE_FALSE_START
		/*
			If FALSE START is supported, there may be APPLICATION_DATA directly
			following the FINISHED message, even though we haven't sent our
			CHANGE_CIPHER_SPEC or FINISHED message. This is signalled by buf
			having been moved forward, and our response being put directly into
			ssl->outbuf, rather than in buf (ssl->inbuf). Return a REQUEST_SEND
			so that the data in outbuf is flushed before the remaining data in
			ssl->inbuf is parsed.
		 */
		if ((ssl->flags & SSL_FLAGS_FALSE_START) && buf != prevBuf) {
			ssl->inlen -= processed;
			psAssert(ssl->inlen > 0);
			psAssert((uint32)ssl->inlen == start);
			psAssert(buf > ssl->inbuf);
			memmove(ssl->inbuf, buf, ssl->inlen);	/* Pack ssl->inbuf */
			buf = ssl->inbuf;
			return MATRIXSSL_REQUEST_SEND;
		}
#endif
		/*
			This must be handshake data (or alert) or we'd be in PROCESS_DATA
			so there is no way there is anything left inside inbuf to process.
			...so processed isn't valid because the output params are outbuf
			related and we simply reset inlen
		*/
		ssl->inlen = 0;

		/* If alert, close connection after sending */
		if (alertDesc != SSL_ALERT_NONE) {
			ssl->bFlags |= BFLAG_CLOSE_AFTER_SENT;
		}
		psAssert(prevBuf == buf);
		psAssert(ssl->insize >= (int32)len);
		psAssert(start == 0);
		psAssert(buf == ssl->inbuf);
		if (ssl->outlen > 0) {
			/* If data's in outbuf, append inbuf.  This is a corner case that
				can happen if application data is queued but then incoming data
				is processed and discovered to be a re-handshake request.
				matrixSslDecode will have constructed the response flight but
				we don't want to forget about the app data we haven't sent */
			if (ssl->outlen + (int32)len > ssl->outsize) {
				if ((p = psRealloc(ssl->outbuf, ssl->outlen + len,
						ssl->bufferPool)) == NULL) {
					return PS_MEM_FAIL;
				}
				ssl->outbuf = p;
				ssl->outsize = ssl->outlen + len;
			}
			memcpy(ssl->outbuf + ssl->outlen, ssl->inbuf, len);
			ssl->outlen += len;
		} else { /* otherwise, swap inbuf and outbuf */
			buf = ssl->outbuf; ssl->outbuf = ssl->inbuf; ssl->inbuf = buf;
			ssl->outlen = len;
			len = ssl->outsize; ssl->outsize = ssl->insize; ssl->insize = len;
			buf = ssl->inbuf;
			len = ssl->outlen;
		}
		rc = MATRIXSSL_REQUEST_SEND;	/* We queued data to send out */
		break;

	case MATRIXSSL_ERROR:
		if (decodeErr >= 0) {
			//printf("THIS SHOULD BE A NEGATIVE VALUE?\n");
		}
		return decodeErr; /* Will be a negative value */

	case SSL_ALERT:
		if (alertLevel == SSL_ALERT_LEVEL_FATAL) {
			psTraceIntInfo("Received FATAL alert %d.\n", alertDesc);
		} else {
			/* Closure notify is the normal case */
			if (alertDesc == SSL_ALERT_CLOSE_NOTIFY) {
				psTraceInfo("Normal SSL closure alert\n");
			} else {
				psTraceIntInfo("Received WARNING alert %d\n", alertDesc);
			}
		}
		/* Let caller access the 2 data bytes (severity and description) */
#ifdef USE_TLS_1_1
		/* Been ignoring the explicit IV up to this final return point. */
		if ((ssl->flags & SSL_FLAGS_READ_SECURE) &&
				(ssl->flags & SSL_FLAGS_TLS_1_1) &&	(ssl->enBlockSize > 1)) {
			prevBuf += ssl->enBlockSize;
		}
#endif /* USE_TLS_1_1 */
		psAssert(len == 2);
		*ptbuf = prevBuf;
		*ptlen = len;
		ssl->inlen -= processed;
		return MATRIXSSL_RECEIVED_ALERT;

	case SSL_PARTIAL:
		if (reqLen > SSL_MAX_BUF_SIZE) {
			return PS_MEM_FAIL;
		}
		if (reqLen > (uint32)ssl->insize) {
			if ((p = psRealloc(ssl->inbuf, reqLen, ssl->bufferPool)) == NULL) {
				return PS_MEM_FAIL;
			}
			ssl->inbuf = p;
			ssl->insize = reqLen;
			buf = ssl->inbuf;
			/* Don't need to change inlen */
		}


		rc = MATRIXSSL_REQUEST_RECV;	/* Expecting more data */
		break;

	/* We've got outgoing data that's larger than our buffer */
	case SSL_FULL:
		if (reqLen > SSL_MAX_BUF_SIZE) {
			return PS_MEM_FAIL;
		}
		/* We balk if we get a large handshake message */
		if (reqLen > SSL_MAX_PLAINTEXT_LEN &&
				!matrixSslHandshakeIsComplete(ssl)) {
			if (reqLen > SSL_MAX_PLAINTEXT_LEN) {
				return PS_MEM_FAIL;
			}
		}
		/*
			Can't envision any possible case where there is remaining data
			in inbuf to process and are getting SSL_FULL.
		*/
		ssl->inlen = 0;

		/* Grow inbuf */
		if (reqLen > (uint32)ssl->insize) {
			len = ssl->inbuf - buf;
			if ((p = psRealloc(ssl->inbuf, reqLen, ssl->bufferPool)) == NULL) {
				return PS_MEM_FAIL;
			}
			ssl->inbuf = p;
			ssl->insize = reqLen;
			buf = ssl->inbuf + len;
			/* Note we leave inlen untouched here */
		} else {
			psTraceInfo("Encoding error. Possible wrong flight messagSize\n");
			return PS_PROTOCOL_FAIL;	/* error in our encoding */
		}
		goto DECODE_MORE;

	case SSL_PROCESS_DATA:
/*
		Possible we received a finished message and app data in the same
		flight. In this case, the caller is not notified that the handshake
		is complete, but rather is notified that there is application data to
		process.
 */
		if (!(ssl->bFlags & BFLAG_HS_COMPLETE) &&
			matrixSslHandshakeIsComplete(ssl)) {
			ssl->bFlags |= BFLAG_HS_COMPLETE;
#ifdef USE_CLIENT_SIDE_SSL
			matrixSslGetSessionId(ssl, ssl->sid);
#endif /* USE_CLIENT_SIDE_SSL */
		}
/*
		 .	prevbuf points to start of unencrypted data
		 .	buf points to start of any remaining unencrypted data
		 .	start is length of remaining encrypted data yet to decode
		 .	len is length of unencrypted data ready for user processing
 */
		ssl->inlen -= processed;
		psAssert((uint32)ssl->inlen == start);

		/* Call user plaintext data handler */
#ifdef USE_TLS_1_1
		/* Been ignoring the explicit IV up to this final return point. */
		/* NOTE: This test has been on enBlockSize for a very long time but
			it looks like it should be on deBlockSize since this a decryption.
			Changed and added an assert to see if these ever don't match */
		psAssert(ssl->enBlockSize == ssl->deBlockSize);
		if ((ssl->flags & SSL_FLAGS_READ_SECURE) &&
				(ssl->flags & SSL_FLAGS_TLS_1_1) &&	(ssl->deBlockSize > 1)) {
			len -= ssl->deBlockSize;
			prevBuf += ssl->deBlockSize;
		}
		/* END enBlockSize to deBlockSize change */
#endif /* USE_TLS_1_1 */
		*ptbuf = prevBuf;
		*ptlen = len;
#ifdef USE_DTLS
/*
		This flag is used in conjuction with flightDone in the buffer
		management API set to determine whether we are still in a handshake
		state for attempting flight resends. If we are getting app data we
		know for certain we are out of the hs states. Testing HandshakeComplete
		is not enough because you never know if the other side got FINISHED.
*/
		if (ssl->flags & SSL_FLAGS_DTLS) {
			ssl->appDataExch = 1;
		}
#endif
#ifdef USE_ZLIB_COMPRESSION
		if (ssl->compression > 0) {
			return MATRIXSSL_APP_DATA_COMPRESSED;
		}
#endif
		return MATRIXSSL_APP_DATA;
	} /* switch decodeRet */

	if (ssl->inlen > 0 && (buf != ssl->inbuf)) {
		psAssert(0);
	}
/*
	Shrink inbuf to default size once inlen < default size, and we aren't
	expecting any more data in the buffer. If SSL_PARTIAL, don't shrink the
	buffer, since we expect to fill it up shortly.
*/
	if (decodeRet != SSL_PARTIAL) {
		revertToDefaultBufsize(ssl, SSL_INBUF);
	}

	return rc;
}
Exemplo n.º 10
0
/*
	Non-blocking socket event handler
	Wait one time in select for events on any socket
	This will accept new connections, read and write to sockets that are
	connected, and close sockets as required.
 */
static int32 selectLoop(sslKeys_t *keys, SOCKET lfd)
{
	httpConn_t		*cp;
	psTime_t		now;
	DLListEntry		connsTmp;
	DLListEntry		*pList;
	
	fd_set			readfd, writefd;
	struct timeval	timeout;
	SOCKET			fd, maxfd;
	
	unsigned char	*buf;
	int32			rc, len, transferred, val;
	unsigned char	rSanity, wSanity, acceptSanity;
	
	sslSessOpts_t	options;
	
	DLListInit(&connsTmp);
	rc = PS_SUCCESS;
	maxfd = INVALID_SOCKET;
	timeout.tv_sec = SELECT_TIME / 1000;
	timeout.tv_usec = (SELECT_TIME % 1000) * 1000;
	FD_ZERO(&readfd);
	FD_ZERO(&writefd);
	
	/* Always set readfd for listening socket */
	FD_SET(lfd, &readfd);
	if (lfd > maxfd) {
		maxfd = lfd;
	}
/*	
	Check timeouts and set readfd and writefd for connections as required.
	We use connsTemp so that removal on error from the active iteration list
		doesn't interfere with list traversal 
 */
	psGetTime(&now, NULL);
	while (!DLListIsEmpty(&g_conns)) {
		pList = DLListGetHead(&g_conns);
		cp = DLListGetContainer(pList, httpConn_t, List);
		DLListInsertTail(&connsTmp, &cp->List);
		/*	If timeout != 0 msec ith no new data, close */
		if (cp->timeout && (psDiffMsecs(cp->time, now, NULL) >
				(int32)cp->timeout)) {
			closeConn(cp, PS_TIMEOUT_FAIL);
			continue;	/* Next connection */
		}
		/* Always select for read */
		FD_SET(cp->fd, &readfd);
		/* Select for write if there's pending write data or connection */
		if (matrixSslGetOutdata(cp->ssl, NULL) > 0) {
			FD_SET(cp->fd, &writefd);
		}
		/* Housekeeping for maxsock in select call */
		if (cp->fd > maxfd) {
			maxfd = cp->fd;
		}
	}
	
	/* Use select to check for events on the sockets */
	if ((val = select(maxfd + 1, &readfd, &writefd, NULL, &timeout)) <= 0) {
		/* On error, restore global connections list */
		while (!DLListIsEmpty(&connsTmp)) {
			pList = DLListGetHead(&connsTmp);
			cp = DLListGetContainer(pList, httpConn_t, List);
			DLListInsertTail(&g_conns, &cp->List);
		}
		/* Select timeout */
		if (val == 0) {
			return PS_TIMEOUT_FAIL;
		}
		/* Woke due to interrupt */
		if (SOCKET_ERRNO == EINTR) {
			return PS_TIMEOUT_FAIL;
		}
		/* Should attempt to handle more errnos, such as EBADF */
		return PS_PLATFORM_FAIL;
	}
	
	/* Check listener for new incoming socket connections */
	if (FD_ISSET(lfd, &readfd)) {
		for (acceptSanity = 0; acceptSanity < ACCEPT_QUEUE; acceptSanity++) {
			fd = accept(lfd, NULL, NULL);
			if (fd == INVALID_SOCKET) {
				break;	/* Nothing more to accept; next listener */
			}
			setSocketOptions(fd);
			cp = malloc(sizeof(httpConn_t));
			memset(cp, 0x0, sizeof(httpConn_t));
			
			memset(&options, 0x0, sizeof(sslSessOpts_t));
			options.versionFlag = g_proto;
			options.userPtr = keys; /* Just a test */
			//options.truncHmac = -1;
			//options.maxFragLen = -1;
			//options.ecFlags |= SSL_OPT_SECP521R1;
			//options.ecFlags |= SSL_OPT_SECP224R1;
			//options.ecFlags |= SSL_OPT_SECP384R1;
			
			
			if ((rc = matrixSslNewServerSession(&cp->ssl, keys, certCb,
					&options)) < 0) {
				close(fd); fd = INVALID_SOCKET;
				continue;
			}
			
#ifdef USE_SERVER_NAME_INDICATION
			/* Register extension callbacks to manage client connection opts */
			matrixSslRegisterSNICallback(cp->ssl, SNI_callback);
#endif
#ifdef USE_ALPN
			matrixSslRegisterALPNCallback(cp->ssl, ALPN_callback);
#endif
			
			cp->fd = fd;
			fd = INVALID_SOCKET;
			cp->timeout = SSL_TIMEOUT;
			psGetTime(&cp->time, NULL);
			cp->parsebuf = NULL;
			cp->parsebuflen = 0;
			DLListInsertTail(&connsTmp, &cp->List);
			/* Fake that there is read data available, no harm if there isn't */
			FD_SET(cp->fd, &readfd);
/*			_psTraceInt("=== New Client %d ===\n", cp->fd); */
		}
	}
	
	/* Check each connection for read/write activity */
	while (!DLListIsEmpty(&connsTmp)) {
		pList = DLListGetHead(&connsTmp);
		cp = DLListGetContainer(pList, httpConn_t, List);
		DLListInsertTail(&g_conns, &cp->List);
		
		rSanity = wSanity = 0;
/*
		See if there's pending data to send on this connection
		We could use FD_ISSET, but this is more reliable for the current
			state of data to send.
 */
WRITE_MORE:
		if ((len = matrixSslGetOutdata(cp->ssl, &buf)) > 0) {
			/* Could get a EWOULDBLOCK since we don't check FD_ISSET */
			transferred = send(cp->fd, buf, len, MSG_DONTWAIT);
			if (transferred <= 0) {
#ifdef WIN32
				if (SOCKET_ERRNO != EWOULDBLOCK &&
					SOCKET_ERRNO != WSAEWOULDBLOCK) {

#else
				if (SOCKET_ERRNO != EWOULDBLOCK) {
#endif
					closeConn(cp, PS_PLATFORM_FAIL);
					continue;	/* Next connection */
				}
			} else {
				/* Indicate that we've written > 0 bytes of data */
				if ((rc = matrixSslSentData(cp->ssl, transferred)) < 0) {
					closeConn(cp, PS_ARG_FAIL);
					continue;	/* Next connection */
				}
				if (rc == MATRIXSSL_REQUEST_CLOSE) {
					closeConn(cp, MATRIXSSL_REQUEST_CLOSE);
					continue;	/* Next connection */
				} else if (rc == MATRIXSSL_HANDSHAKE_COMPLETE) {
					/* If the protocol is server initiated, send data here */
#ifdef ENABLE_FALSE_START					
					/* OR this could be a Chrome browser using 
						FALSE_START and the application data is already
						waiting in our inbuf for processing */
					if ((rc = matrixSslReceivedData(cp->ssl, 0,
								&buf, (uint32*)&len)) < 0) {
							closeConn(cp, 0);
							continue;	/* Next connection */
					}
					if (rc > 0) { /* There was leftover data */
						goto PROCESS_MORE;
					}
#endif /* ENABLE_FALSE_START  */
					
				}
				/* Update activity time */
				psGetTime(&cp->time, NULL);
				/* Try to send again if more data to send */
				if (rc == MATRIXSSL_REQUEST_SEND || transferred < len) {
					if (wSanity++ < GOTO_SANITY) goto WRITE_MORE;
				}
			}
		} else if (len < 0) {
			closeConn(cp, PS_ARG_FAIL);
			continue;	/* Next connection */
		}
		
/*
		Check the file descriptor returned from select to see if the connection
		has data to be read
 */
		if (FD_ISSET(cp->fd, &readfd)) {
READ_MORE:
			/* Get the ssl buffer and how much data it can accept */
			/* Note 0 is a return failure, unlike with matrixSslGetOutdata */
			if ((len = matrixSslGetReadbuf(cp->ssl, &buf)) <= 0) {
				closeConn(cp, PS_ARG_FAIL);
				continue;	/* Next connection */
			}
			if ((transferred = recv(cp->fd, buf, len, MSG_DONTWAIT)) < 0) {
				/* We could get EWOULDBLOCK despite the FD_ISSET on goto  */
#ifdef WIN32
				if (SOCKET_ERRNO != EWOULDBLOCK &&
					SOCKET_ERRNO != WSAEWOULDBLOCK) {

#else
				if (SOCKET_ERRNO != EWOULDBLOCK) {
#endif
					closeConn(cp, PS_PLATFORM_FAIL);
				}
				continue;	/* Next connection */
			}
			
			/* If EOF, remote socket closed. This is semi-normal closure.
			   Officially, we should close on closure alert. */
			if (transferred == 0) {
/*				psTraceIntInfo("Closing connection %d on EOF\n", cp->fd); */
				closeConn(cp, 0);
				continue;	/* Next connection */
			}
/*
			Notify SSL state machine that we've received more data into the
			ssl buffer retreived with matrixSslGetReadbuf.
 */
			if ((rc = matrixSslReceivedData(cp->ssl, (int32)transferred, &buf, 
											(uint32*)&len)) < 0) {
				closeConn(cp, 0);
				continue;	/* Next connection */
			}
			/* Update activity time */
			psGetTime(&cp->time, NULL);
			
PROCESS_MORE:
			/* Process any incoming plaintext application data */
			switch (rc) {
				case MATRIXSSL_HANDSHAKE_COMPLETE:
					/* If the protocol is server initiated, send data here */
					goto READ_MORE;
				case MATRIXSSL_APP_DATA:
				case MATRIXSSL_APP_DATA_COMPRESSED:
					//psTraceBytes("DATA", buf, len);
					/* Remember, must handle if len == 0! */
					if ((rc = httpBasicParse(cp, buf, len, 0)) < 0) {
						_psTrace("Couldn't parse HTTP data.  Closing conn.\n");
						closeConn(cp, PS_PROTOCOL_FAIL);
						continue; /* Next connection */
					}
					if (cp->parsebuf != NULL) {
						/* Test for one of our custom testing messages */
						if (strncmp((const char*)cp->parsebuf,
								"MATRIX_SHUTDOWN", 15) == 0) {
							g_exitFlag = 1;
							matrixSslEncodeClosureAlert(cp->ssl);
							_psTrace("Got MATRIX_SHUTDOWN.  Exiting\n");
							goto WRITE_MORE;
						}
						
					}
					/* reply to /bytes?<byte count> syntax */
					if (len > 11 &&
							strncmp((char *)buf, "GET /bytes?", 11) == 0) {
						cp->bytes_requested = atoi((char *)buf + 11);
						if (cp->bytes_requested <
								strlen((char *)g_httpResponseHdr) ||
								cp->bytes_requested > 1073741824) {
                			cp->bytes_requested =
								strlen((char *)g_httpResponseHdr);
            			}
						cp->bytes_sent = 0;
					}
					if (rc == HTTPS_COMPLETE) {
						if (httpWriteResponse(cp) < 0) {
							closeConn(cp, PS_PROTOCOL_FAIL);
							continue; /* Next connection */
						}
						/* For HTTP, we assume no pipelined requests, so we 
						 close after parsing a single HTTP request */
						/* Ignore return of closure alert, it's optional */
						matrixSslEncodeClosureAlert(cp->ssl);
						rc = matrixSslProcessedData(cp->ssl, &buf, (uint32*)&len);
						if (rc > 0) {
							/* Additional data is available, but we ignore it */
							_psTrace("HTTP data parsing not supported, ignoring.\n");
							closeConn(cp, PS_SUCCESS);
							continue; /* Next connection */
						} else if (rc < 0) {
							closeConn(cp, PS_PROTOCOL_FAIL);
							continue; /* Next connection */
						}
						/* rc == 0, write out our response and closure alert */
						goto WRITE_MORE;
					}
					/* We processed a partial HTTP message */
					if ((rc = matrixSslProcessedData(cp->ssl, &buf, (uint32*)&len)) == 0) {
						goto READ_MORE;
					}
					goto PROCESS_MORE;
				case MATRIXSSL_REQUEST_SEND:
					/* Prevent us from reading again after the write,
					 although that wouldn't be the end of the world */
					FD_CLR(cp->fd, &readfd);
					if (wSanity++ < GOTO_SANITY) goto WRITE_MORE;
					break;
				case MATRIXSSL_REQUEST_RECV:
					if (rSanity++ < GOTO_SANITY) goto READ_MORE; 
					break;
				case MATRIXSSL_RECEIVED_ALERT:
					/* The first byte of the buffer is the level */
					/* The second byte is the description */
					if (*buf == SSL_ALERT_LEVEL_FATAL) {
						psTraceIntInfo("Fatal alert: %d, closing connection.\n", 
									*(buf + 1));
						closeConn(cp, PS_PROTOCOL_FAIL);
						continue; /* Next connection */
					}
					/* Closure alert is normal (and best) way to close */
					if (*(buf + 1) == SSL_ALERT_CLOSE_NOTIFY) {
						closeConn(cp, PS_SUCCESS);
						continue; /* Next connection */
					}
					psTraceIntInfo("Warning alert: %d\n", *(buf + 1));
					if ((rc = matrixSslProcessedData(cp->ssl, &buf, (uint32*)&len)) == 0) {
						/* No more data in buffer. Might as well read for more. */
						goto READ_MORE;
					}
					goto PROCESS_MORE;

				default:
					/* If rc <= 0 we fall here */
					closeConn(cp, PS_PROTOCOL_FAIL);
					continue; /* Next connection */
			}
			/* Always try to read more if we processed some data */
			if (rSanity++ < GOTO_SANITY) goto READ_MORE;
		} /*  readfd handling */
	}	/* connection loop */
	return PS_SUCCESS;
}

/******************************************************************************/
/*
	Create an HTTP response and encode it to the SSL buffer
 */
#define	TEST_SIZE	16000
static int32 httpWriteResponse(httpConn_t *conn)
{
	unsigned char	*buf;
	ssl_t			*cp;
	int32			available, len, rc;

		
	cp = conn->ssl;
	if (conn->bytes_requested) {
		/* The /bytes? syntax */
		while (conn->bytes_sent < conn->bytes_requested) {
			len = conn->bytes_requested - conn->bytes_sent;
			if (len > RESPONSE_REC_LEN) {
				len = RESPONSE_REC_LEN;
    		}
			psAssert(len > 0);
			rc = matrixSslGetWritebuf(cp, &buf, len);
			if (rc < len) {
				len = rc; /* could have been shortened due to max_frag */
			}
			memset(buf, 'J', len);
			if (conn->bytes_sent == 0) {
				/* Overwrite first N bytes with HTTP header the first time */
				strncpy((char *)buf, (char *)g_httpResponseHdr,
					strlen((char*)g_httpResponseHdr));
			}
			if ((rc = matrixSslEncodeWritebuf(cp, len)) < 0) {
				printf("couldn't encode data %d\n", rc);
    		}
			conn->bytes_sent += len;
    	}
		return MATRIXSSL_REQUEST_SEND;
	}

	/* Usual reply */

	if ((available = matrixSslGetWritebuf(cp, &buf, 
			(uint32)strlen((char *)g_httpResponseHdr) + 1)) < 0) {
		return PS_MEM_FAIL;
	}
	strncpy((char *)buf, (char *)g_httpResponseHdr, available);
	//psTraceBytes("Replying", buf, (uint32)strlen((char *)buf));
	if (matrixSslEncodeWritebuf(cp, (uint32)strlen((char *)buf)) < 0) {
		return PS_MEM_FAIL;
	}
	return MATRIXSSL_REQUEST_SEND;
}

/******************************************************************************/
/*
	Main non-blocking SSL server
	Initialize MatrixSSL and sockets layer, and loop on select
 */
int32 main(int32 argc, char **argv)
{
	sslKeys_t		*keys;
	SOCKET			lfd;
	unsigned char	*CAstream;
	int32			err, rc, CAstreamLen;
#ifdef USE_STATELESS_SESSION_TICKETS
	unsigned char	randKey[16];
#endif

#ifdef WIN32
	WSADATA			wsaData;
	WSAStartup(MAKEWORD(1, 1), &wsaData);
#endif


	keys = NULL;
	DLListInit(&g_conns);
	g_exitFlag = 0;
	lfd = INVALID_SOCKET;
	
#ifdef POSIX
	if (sighandlers() < 0) {
		return PS_PLATFORM_FAIL;
	}
#endif	/* POSIX */
	if ((rc = matrixSslOpen()) < 0) {
		_psTrace("MatrixSSL library init failure.  Exiting\n");
		return rc;
	}

	if (matrixSslNewKeys(&keys, NULL) < 0) {
		_psTrace("MatrixSSL library key init failure.  Exiting\n");
		return -1;
	}
	
#ifdef USE_STATELESS_SESSION_TICKETS
	matrixSslSetSessionTicketCallback(keys, sessTicketCb);
	psGetEntropy(randKey, 16, NULL);
	if (matrixSslLoadSessionTicketKeys(keys, randKey,
			sessTicketSymKey, 32, sessTicketMacKey, 32) < 0) {
		_psTrace("Error loading session ticket encryption key\n");
	}
#endif

#ifdef USE_HEADER_KEYS
/*
	In-memory based keys
	Build the CA list first for potential client auth usage
*/
	CAstreamLen = 0;
#ifdef USE_RSA
	CAstreamLen += sizeof(RSACAS);
#ifdef USE_ECC
	CAstreamLen += sizeof(ECDHRSACAS);
#endif
#endif
#ifdef USE_ECC
	CAstreamLen += sizeof(ECCAS);
#endif
	CAstream = psMalloc(NULL, CAstreamLen);
	
	CAstreamLen = 0;
#ifdef USE_RSA
	memcpy(CAstream, RSACAS, sizeof(RSACAS));
	CAstreamLen += sizeof(RSACAS);
#ifdef USE_ECC
	memcpy(CAstream + CAstreamLen, ECDHRSACAS, sizeof(ECDHRSACAS));
	CAstreamLen += sizeof(ECDHRSACAS);
#endif
#endif
#ifdef USE_ECC
	memcpy(CAstream + CAstreamLen, ECCAS,	sizeof(ECCAS));
	CAstreamLen += sizeof(ECCAS);
#endif
		
#ifdef EXAMPLE_RSA_KEYS
	if ((rc = matrixSslLoadRsaKeysMem(keys, RSA1024, sizeof(RSA1024),
			RSA1024KEY, sizeof(RSA1024KEY), CAstream, CAstreamLen)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		psFree(CAstream, NULL);
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif

#ifdef EXAMPLE_ECDH_RSA_KEYS
	if ((rc = matrixSslLoadEcKeysMem(keys, ECDHRSA256, sizeof(ECDHRSA256),
				   ECDHRSA256KEY, sizeof(ECDHRSA256KEY), CAstream,
				   CAstreamLen)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		psFree(CAstream, NULL);
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif

#ifdef EXAMPLE_EC_KEYS
	if ((rc = matrixSslLoadEcKeysMem(keys, EC521, sizeof(EC521),
			EC521KEY, sizeof(EC521KEY), CAstream, CAstreamLen)) < 0) {
//	if ((rc = matrixSslLoadEcKeysMem(keys, EC256, sizeof(EC256),
//			EC256KEY, sizeof(EC256KEY), CAstream, CAstreamLen)) < 0) {
//	if ((rc = matrixSslLoadEcKeysMem(keys, EC192, sizeof(EC192),
//			EC192KEY, sizeof(EC192KEY), CAstream, CAstreamLen)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		psFree(CAstream, NULL);
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif
	
#ifdef REQUIRE_DH_PARAMS
	if (matrixSslLoadDhParamsMem(keys, dhParamBuf1024, sizeof(dhParamBuf1024))
			< 0){
		_psTrace("Unable to load DH parameters\n");
	}
#endif /* DH_PARAMS */

	psFree(CAstream, NULL);
#else /* USE_HEADER_KEYS */
/*
	File based keys
	Build the CA list first for potential client auth usage
*/
	CAstreamLen = 0;
#ifdef USE_RSA
	CAstreamLen += (int32)strlen(rsaCAFile) + 1;
#ifdef USE_ECC
	CAstreamLen += (int32)strlen(ecdhRsaCAFile) + 1;
#endif
#endif
#ifdef USE_ECC
	CAstreamLen += (int32)strlen(ecCAFile) + 1;
#endif		
	CAstream = psMalloc(NULL, CAstreamLen);
	memset(CAstream, 0x0, CAstreamLen);
	
	CAstreamLen = 0;
#ifdef USE_RSA	
	memcpy(CAstream, rsaCAFile,	strlen(rsaCAFile));
	CAstreamLen += strlen(rsaCAFile);
#ifdef USE_ECC
	memcpy(CAstream + CAstreamLen, ";", 1); CAstreamLen++;
	memcpy(CAstream + CAstreamLen, ecdhRsaCAFile,  strlen(ecdhRsaCAFile));
	CAstreamLen += strlen(ecdhRsaCAFile);
#endif
#endif
#ifdef USE_ECC
	if (CAstreamLen > 0) {
		memcpy(CAstream + CAstreamLen, ";", 1); CAstreamLen++;
	}
	memcpy(CAstream + CAstreamLen, ecCAFile,  strlen(ecCAFile));
#endif
	
/* Load Identiy */	
#ifdef EXAMPLE_RSA_KEYS	
	if ((rc = matrixSslLoadRsaKeys(keys, rsaCertFile, rsaPrivkeyFile, NULL,
			(char*)CAstream)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		psFree(CAstream, NULL);
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif	

#ifdef EXAMPLE_ECDH_RSA_KEYS
	if ((rc = matrixSslLoadEcKeys(keys, ecdhRsaCertFile, ecdhRsaPrivkeyFile,
			NULL, (char*)CAstream)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		psFree(CAstream, NULL);
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif

#ifdef EXAMPLE_EC_KEYS
	if ((rc = matrixSslLoadEcKeys(keys, ecCertFile, ecPrivkeyFile, NULL,
			(char*)CAstream)) < 0) {
		_psTrace("No certificate material loaded.  Exiting\n");
		psFree(CAstream, NULL);
		matrixSslDeleteKeys(keys);
		matrixSslClose();
		return rc;
	}
#endif
	
#ifdef REQUIRE_DH_PARAMS
	if (matrixSslLoadDhParams(keys, dhParamFile) < 0){
		_psTrace("Unable to load DH parameters\n");
	}
#endif

	psFree(CAstream, NULL);
#endif /* USE_HEADER_KEYS */

#ifdef USE_PSK_CIPHER_SUITE
	/* The first one supports the 15-byte openssl PSK ID */
	matrixSslLoadPsk(keys, pskTable[0].key, sizeof(pskTable[0].key),
		pskTable[rc].id, 15);
	for (rc = 0; rc < 8; rc++) {   
		matrixSslLoadPsk(keys, pskTable[rc].key, sizeof(pskTable[rc].key),
			pskTable[rc].id, sizeof(pskTable[rc].id));
	}
#endif /* PSK */

	if (argc == 2) {
		switch (atoi(argv[1])) {
		case 0:
			g_proto = SSL_FLAGS_SSLV3;
			break;
		case 1:
			g_proto = SSL_FLAGS_TLS_1_0;
			break;
		case 2:
			g_proto = SSL_FLAGS_TLS_1_1;
			break;
		case 3:
			g_proto = SSL_FLAGS_TLS_1_2;
			break;
		default:
			g_proto = SSL_FLAGS_TLS_1_0;
			break;
		}
	} else {
		g_proto = 0;
	}
	/* Create the listening socket that will accept incoming connections */
	if ((lfd = socketListen(HTTPS_PORT, &err)) == INVALID_SOCKET) {
		_psTraceInt("Can't listen on port %d\n", HTTPS_PORT);
		goto L_EXIT;
	}

	/* Main select loop to handle sockets events */
	while (!g_exitFlag) {
		selectLoop(keys, lfd);
	}

L_EXIT:
	if (lfd != INVALID_SOCKET) close(lfd);
	if (keys) matrixSslDeleteKeys(keys);
	matrixSslClose();
	
	return 0;
}