Example #1
0
File: tls.c Project: B-Rich/NUL
/*
	Free a tlsExtenstion_t structure and any extensions that have been loaded
*/
void matrixSslDeleteHelloExtension(tlsExtension_t *extension)
{
	tlsExtension_t	*next, *ext;
	
	if (extension == NULL) {
		return;
	}
	ext = extension;
/*
	Free first one
*/
	if (ext->extData) {
		psFree(ext->extData);
	}
	next = ext->next;
	psFree(ext);
/*
	Free others
*/
	while (next) {
		ext = next;
		next = ext->next;
		if (ext->extData) {
			psFree(ext->extData);
		}
		psFree(ext);
	}
	
	return; 
}
Example #2
0
/*
	Free private key and cert and zero memory allocated by matrixSslReadKeys.
*/
void matrixRsaFreeKeys(sslKeys_t *keys)
{
	sslLocalCert_t	*current, *next;
	int32			i = 0;

	if (keys) {
		current = &keys->cert;
		while (current) {
			if (current->certBin) {
				memset(current->certBin, 0x0, current->certLen);
				psFree(current->certBin);
			}
			if (current->privKey) {
				matrixRsaFreeKey(current->privKey);
			}
			next = current->next;
			if (i++ > 0) {
				psFree(current);
			}
			current = next;
		}
#ifdef USE_CLIENT_SIDE_SSL
		if (keys->caCerts) {
			matrixX509FreeCert(keys->caCerts);
		}
#endif /* USE_CLIENT_SIDE_SSL */
		psFree(keys);
	}
}
Example #3
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);
}
Example #4
0
int *glitch_one_detector_simple(
  actData *mydat,        ///< Data vector to filter.  Modified and returned.
  int n,                 ///< Length of the input data vector mydat.
  bool do_smooth,        ///< Whether to replace the entire data vector with its smoothed value.
  bool apply_glitch,     ///< Whether to replace data exceeding the cut threshold with its smoothed value.
  bool do_cuts,          ///< Whether to build the cutvec of data failing the cut threshhold test.
  actData nsig,          ///< The cut threshold is this factor times the median abs deviation of smooths.
  actData t_glitch,      ///< The width (Gaussian sigma) of the glitch time
  actData t_smooth,      ///< The width (Gaussian sigma) of the smoothing time
  actData dt,            ///< Time between data samples.
  int filt_type)         ///< Select filter type (currently only Gaussian filters are implemented).
{
  // If we have both set to true, we don't know what to put in mydat
#ifdef HAVE_PSERR
  if(do_smooth && apply_glitch)
    psError(MB_ERR_BAD_VALUE, true, 
            "Cannot both smooth and deglitch (=not smooth) data in glitch_one_detector\n");
#endif

  actComplex *tmpfft=act_fftw_malloc(sizeof(actComplex)*n);
  actData *tmpvec=psAlloc(n*sizeof(actData));
  actData *tmpclean=psAlloc(n*sizeof(actData));
  actData *filtvec=calculate_glitch_filterC(t_glitch,t_smooth,dt,n,1);
  int *cutvec=psAlloc(n*sizeof(int));
      
  act_fftw_plan p_forward;
  act_fftw_plan p_back;
#if !defined(MB_SKIP_OMP)
#pragma omp critical
#endif
  {
    p_forward =act_fftw_plan_dft_r2c_1d(n,tmpvec,tmpfft,FFTW_ESTIMATE);  
    p_back    =act_fftw_plan_dft_c2r_1d(n,tmpfft,tmpvec,FFTW_ESTIMATE);  
  }
  glitch_one_detector(mydat,filtvec, tmpfft,tmpvec,tmpclean,cutvec,n, p_forward,  p_back,do_smooth,
                      apply_glitch, do_cuts,nsig);

      
#if !defined(MB_SKIP_OMP)
#pragma omp critical
#endif
  {
    act_fftw_destroy_plan(p_forward);
    act_fftw_destroy_plan(p_back);
  }
  psFree(tmpvec);
  psFree(tmpclean);
  psFree(filtvec);
  act_fftw_free(tmpfft);
  
  if (do_cuts)
    return cutvec;
  else {
    psFree(cutvec);
    return NULL;
  }
}
Example #5
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;
}
Example #6
0
void matrixSslDeleteSessionId(sslSessionId_t *sess)
{
	if (sess == NULL) {
		return;
	}
#ifdef USE_STATELESS_SESSION_TICKETS
	if (sess->sessionTicket) {
		psFree(sess->sessionTicket);
	}
#endif
	memset(sess, 0x0, sizeof(sslSessionId_t));
	psFree(sess);
}
Example #7
0
/*
	This will free the struct and any key material that was loaded via:
		matrixSslLoadRsaKeys
		matrixSslLoadDhParams
		matrixSslLoadPsk	
*/
void matrixSslDeleteKeys(sslKeys_t *keys)
{
	
	if (keys == NULL) {
		return;
	}
#ifdef USE_SERVER_SIDE_SSL	
	if (keys->cert) {
		psX509FreeCert(keys->cert);
	}
	
	if (keys->privKey) {
		psFreePubKey(keys->privKey);
	}
#endif /* USE_SERVER_SIDE_SSL */
	
#ifdef USE_CLIENT_SIDE_SSL
	if (keys->CAcerts) {
		psX509FreeCert(keys->CAcerts);
	}
#endif /* USE_CLIENT_SIDE_SSL */



	psFree(keys);
}
Example #8
0
/*
	In-memory version of matrixX509ReadPubKey.
	This function was written strictly for clarity in the PeerSec crypto API
	subset.  It extracts only the public key from a certificate file for use
	in the lower level encrypt/decrypt RSA routines.
*/
int32 matrixX509ParsePubKey(psPool_t *pool, unsigned char *certBuf,
							int32 certLen, sslRsaKey_t **key)
{
	sslRsaKey_t		*lkey;
	sslRsaCert_t	*certStruct;
	int32			err;

	if (matrixX509ParseCert(pool, certBuf, certLen, &certStruct) < 0) {
		matrixX509FreeCert(certStruct);
		return -1;
	}
	lkey = *key = psMalloc(pool, sizeof(sslRsaKey_t));
	memset(lkey, 0x0, sizeof(sslRsaKey_t));

	if ((err = _mp_init_multi(pool, &lkey->e, &lkey->N, NULL,
			NULL, NULL,	NULL, NULL,	NULL)) != MP_OKAY) {
		matrixX509FreeCert(certStruct);
		psFree(lkey);
		return err;
	}
	mp_copy(&certStruct->publicKey.e, &lkey->e);
	mp_copy(&certStruct->publicKey.N, &lkey->N);

	mp_shrink(&lkey->e);
	mp_shrink(&lkey->N);

	lkey->size = certStruct->publicKey.size;

	matrixX509FreeCert(certStruct);

	return 0;
}
Example #9
0
File: corelib.c Project: B-Rich/NUL
void psFreeList(psList_t *list)
{
	psList_t	*next, *current;

	if (list == NULL) {
		return;
	}
	current = list;
	while (current) {
		next = current->next;
		if (current->item) {
			psFree(current->item);
		}
		psFree(current);
		current = next;
	}	
}
Example #10
0
/*
	Allows for semi-colon delimited list of certificates for cert chaining.
	Also allows multiple certificiates in a single file.
	
	HOWERVER, in both cases the first in the list must be the identifying
	cert of the application. Each subsequent cert is the parent of the previous
*/
int32 readCertChain(psPool_t *pool, const char *certFiles,
					sslLocalCert_t *lkeys)
{
	sslLocalCert_t	*currCert;
	unsigned char	*certBin, *tmp;
	sslChainLen_t	chain;
	int32			certLen, i;

	if (certFiles == NULL) {
		return 0;
	}

	if (matrixX509ReadCert(pool, certFiles, &certBin, &certLen, &chain) < 0) {
		matrixStrDebugMsg("Error reading cert file %s\n", (char*)certFiles);
		return -1;
	}
/*
	The first cert is allocated in the keys struct.  All others in
	linked list are allocated here.
*/
	i = 0;
	tmp = certBin;
	while (chain[i] != 0) {
		if (i == 0) {
			currCert = lkeys;
		} else {
			currCert->next = psMalloc(pool, sizeof(sslLocalCert_t));
			if (currCert->next == NULL) {
				psFree(tmp);
				return -8; /* SSL_MEM_ERROR */
			}
			memset(currCert->next, 0x0, sizeof(sslLocalCert_t));
			currCert = currCert->next;
		}
		currCert->certBin = psMalloc(pool, chain[i]);
		memcpy(currCert->certBin, certBin, chain[i]);
		currCert->certLen = chain[i];
		certBin += chain[i]; certLen -= chain[i];
		i++;
	}
	psFree(tmp);
	sslAssert(certLen == 0);
	return 0;
}
Example #11
0
void filter_whole_tod(mbTOD *tod, const actData *filt, actData **to_filt_in)
{

#if 1  //use this to avoid problems below wherein it seems that some stuff is incompatible with also using fft_all_data with MKL ffts
  if (to_filt_in==NULL) {
    apply_real_filter_to_data(tod,filt);
#pragma omp parallel for shared(tod) default(none)
    for (int i=0;i<tod->ndet;i++)
      for (int j=0;j<tod->ndata;j++)
	tod->data[i][j]*=tod->ndata;
    return;
  }
#endif

  actData **to_filt;    // The list of vectors to filter.
  if (to_filt_in==NULL)
    to_filt=tod->data;
  else
    to_filt=to_filt_in;
  

#pragma omp parallel shared(tod,to_filt,filt) default (none)
  {
    int n=tod->ndata;
    actData *myfilt=(actData *)psAlloc(n*sizeof(actData));
    memcpy(myfilt,filt,sizeof(actData)*n);
    actComplex *tmpfft=(actComplex *)act_fftw_malloc((n/2+1)*sizeof(actComplex));
    
    act_fftw_plan p_forward;
    act_fftw_plan p_back;
#pragma omp critical
    {
      p_forward =act_fftw_plan_dft_r2c_1d(n,to_filt[0],tmpfft,FFTW_ESTIMATE);  
      p_back    =act_fftw_plan_dft_c2r_1d(n,tmpfft,to_filt[0],FFTW_ESTIMATE);  
    }
    
#pragma omp for
    for (int i=0; i<tod->ndet; i++) {
      filter_one_tod(to_filt[i],filt,tmpfft,p_forward,p_back,n);
    }
#pragma omp critical
    {
      act_fftw_destroy_plan(p_forward);
      act_fftw_destroy_plan(p_back);
    }
    act_fftw_free(tmpfft);
    psFree(myfilt);
#if 0
    actData nn=n;
#pragma omp for
    for (int i=0;i<tod->ndet;i++)
      for (int j=0;j<n;j++)
	tod->data[i][j]/=nn;
#endif
  }
}
Example #12
0
/*
 *	Generates all key material.
 */
int32 sslDeriveKeys(ssl_t *ssl)
{
	sslMd5Context_t		md5Ctx;
	sslSha1Context_t	sha1Ctx;
	unsigned char		buf[SSL_MD5_HASH_SIZE + SSL_SHA1_HASH_SIZE];
	unsigned char		*tmp;
	int32				i;

/*
	If this session is resumed, we want to reuse the master secret to 
	regenerate the key block with the new random values.
*/
	if (ssl->flags & SSL_FLAGS_RESUMED) {
		goto skipPremaster;
	}
/*
	master_secret =
		MD5(pre_master_secret + SHA('A' + pre_master_secret +
			ClientHello.random + ServerHello.random)) +
		MD5(pre_master_secret + SHA('BB' + pre_master_secret +
			ClientHello.random + ServerHello.random)) +
		MD5(pre_master_secret + SHA('CCC' + pre_master_secret +
			ClientHello.random + ServerHello.random));
*/
	tmp = ssl->sec.masterSecret;
	for (i = 0; i < 3; i++) {
		matrixSha1Init(&sha1Ctx);
		matrixSha1Update(&sha1Ctx, salt[i], i + 1);
		matrixSha1Update(&sha1Ctx, ssl->sec.premaster, ssl->sec.premasterSize);
		matrixSha1Update(&sha1Ctx, ssl->sec.clientRandom, SSL_HS_RANDOM_SIZE);
		matrixSha1Update(&sha1Ctx, ssl->sec.serverRandom, SSL_HS_RANDOM_SIZE);
		matrixSha1Final(&sha1Ctx, buf);
		
		matrixMd5Init(&md5Ctx);
		matrixMd5Update(&md5Ctx, ssl->sec.premaster, ssl->sec.premasterSize);
		matrixMd5Update(&md5Ctx, buf, SSL_SHA1_HASH_SIZE);
		matrixMd5Final(&md5Ctx, tmp);
		tmp += SSL_MD5_HASH_SIZE;
	}
	memset(buf, 0x0, SSL_MD5_HASH_SIZE + SSL_SHA1_HASH_SIZE);
/*
	premaster is now allocated for DH reasons.  Can free here
*/
	psFree(ssl->sec.premaster);
	ssl->sec.premaster = NULL;
	ssl->sec.premasterSize = 0;

skipPremaster:
	if (createKeyBlock(ssl, ssl->sec.clientRandom, ssl->sec.serverRandom, 
			ssl->sec.masterSecret, SSL_HS_MASTER_SIZE) < 0) {
		matrixStrDebugMsg("Unable to create key block\n", NULL);
		return -1;
	}
	
	return SSL_HS_MASTER_SIZE;
}
Example #13
0
static void closeClientList()
{
	int		i;
	/* Free any leftover clients */
	for (i = 0; i < tableSize && clientTable[i].ssl != NULL; i++) {
		matrixSslDeleteSession(clientTable[i].ssl);
	}
	psFree(clientTable, NULL);
	tableSize = 0;
}
Example #14
0
void psFreePubKey(psPubKey_t *key)
{
	if (key == NULL) {
		return;
	}
	if (key->type == PS_RSA) {
#ifdef USE_RSA
		psRsaFreeKey((psRsaKey_t*)key->key);
#else
		psFree(key->key);
#endif		
	} else {
/*
		If type not found, assume an empty key type
*/
		psFree(key->key);
	}
	psFree(key);
}
Example #15
0
/*
 *	Free an RSA key.  mp_clear will zero the memory of each element and free it.
 */
void matrixRsaFreeKey(sslRsaKey_t *key)
{
	mp_clear(&(key->N));
	mp_clear(&(key->e));
	mp_clear(&(key->d));
	mp_clear(&(key->p));
	mp_clear(&(key->q));
	mp_clear(&(key->dP));
	mp_clear(&(key->dQ));
	mp_clear(&(key->qP));
	psFree(key);
}
Example #16
0
/*
	This function was written strictly for clarity in the PeerSec crypto API
	product.  It extracts only the public key from a certificate file for use
	in the lower level encrypt/decrypt RSA routines
*/
int32 matrixX509ReadPubKey(psPool_t *pool, const char *certFile,
						   sslRsaKey_t **key)
{
	unsigned char	*certBuf;
	sslChainLen_t	chain;
	int32			certBufLen;

	certBuf = NULL;
	if (matrixX509ReadCert(pool, certFile, &certBuf, &certBufLen, &chain) < 0) {
		matrixStrDebugMsg("Unable to read certificate file %s\n",
			(char*)certFile);
		if (certBuf) psFree(certBuf);
		return -1;
	}
	if (matrixX509ParsePubKey(pool, certBuf, certBufLen, key) < 0) {
		psFree(certBuf);
		return -1;
	}
	psFree(certBuf);
	return 0;
}
Example #17
0
/*!
 * Smooth a whole TOD on time scale t_smooth.  If to_filt_in is non-NULL, smooth that and store
 * the result into the TOD.
 * \param tod        The TOD to filter.
 * \param t_smooth   The smoothing time (sigma of a Gaussian), in units of tod->dt (presumably: seconds).
 * \param to_filt_in The data set to filter in place of the TOD.  If not NULL, it must be of length
 *                   tod->ndet each entry having length tod->ndata.
 */
void smooth_tod(mbTOD *tod, actData t_smooth, actData **to_filt_in)
{
  //assert(tod->dt!=NULL);
  //actData dt=(tod->dt[tod->ndata-1]-tod->dt[0])/((actData)tod->ndata);
  assert(tod->deltat>0);
  actData *filt=calculate_glitch_filterC(0.0, t_smooth,tod->deltat,tod->ndata, 1);
  for (int i=0; i<tod->ndata; i++)
    filt[i]/=tod->ndata;

  filter_whole_tod(tod,filt,to_filt_in);
  psFree(filt);
  
}
Example #18
0
File: osdep.c Project: texane/bano
/*
    Memory info:
    Caller must free 'buf' parameter on success
    Callers do not need to free buf on function failure
*/
int32 psGetFileBuf(psPool_t *pool, const char *fileName, unsigned char **buf,
                int32 *bufLen)
{
	DWORD	dwAttributes;
	HANDLE	hFile;
	int32	size;
	DWORD	tmp = 0;

	*bufLen = 0;
	*buf = NULL;

	dwAttributes = GetFileAttributesA(fileName);
	if (dwAttributes != 0xFFFFFFFF && dwAttributes & FILE_ATTRIBUTE_DIRECTORY) {
		psTraceStrCore("Unable to find %s\n", (char*)fileName);
        return PS_PLATFORM_FAIL;
	}

	if ((hFile = CreateFileA(fileName, GENERIC_READ,
			FILE_SHARE_READ && FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
		psTraceStrCore("Unable to open %s\n", (char*)fileName);
        return PS_PLATFORM_FAIL;
	}
	
/*
 *	 Get the file size.
 */
	size = GetFileSize(hFile, NULL);

	*buf = psMalloc(pool, size + 1);
	if (*buf == NULL) {
		CloseHandle(hFile);
		return PS_MEM_FAIL;
	}
	memset(*buf, 0x0, size + 1);
	
	while (*bufLen < size) { 
		if (ReadFile(hFile, *buf + *bufLen,
				(size-*bufLen > 512 ? 512 : size-*bufLen), &tmp, NULL)
				== FALSE) {
			psFree(*buf);
			psTraceStrCore("Unable to read %s\n", (char*)fileName);
			CloseHandle(hFile);
			return PS_PLATFORM_FAIL;
		}
		*bufLen += (int32)tmp;
	}

	CloseHandle(hFile);
	return PS_SUCCESS;
}
Example #19
0
/*
	Free helper
*/
void psFreeDNStruct(DNattributes_t *dn)
{
	if (dn->country)		psFree(dn->country);
	if (dn->state)			psFree(dn->state);
	if (dn->locality)		psFree(dn->locality);
	if (dn->organization)	psFree(dn->organization);
	if (dn->orgUnit)		psFree(dn->orgUnit);
	if (dn->commonName)		psFree(dn->commonName);
}
Example #20
0
/*
	Allocate a new psPubKey_t and memset empty 
*/
psPubKey_t * psNewPubKey(psPool_t *pool) {

	psPubKey_t *ret;

	ret = psMalloc(pool, sizeof(psPubKey_t));

	if (ret == NULL) {
		psError("Memory allocation error in psNewPubKey\n");
		return NULL;
	}
	memset(ret, 0x0, sizeof(psPubKey_t));
	ret->key = psMalloc(pool, sizeof(pubKeyUnion_t));
	if (ret->key == NULL) {
		psFree(ret);
		psError("Memory allocation error in psNewPubKey\n");
		return NULL;
	}
	memset(ret->key, 0x0, sizeof(pubKeyUnion_t));
	return ret;
}
Example #21
0
/* If the required size is known, grow the buffer here so the caller doesn't
	have to go through the REQUEST_RECV logic of matrixSslReceivedData

	The return value MAY be larger than the requested size if the inbuf
	is already larger than what was requested.
*/
int32 matrixSslGetReadbufOfSize(ssl_t *ssl, int32 size, unsigned char **buf)
{
	unsigned char *p;

	if (!ssl || !buf) {
		return PS_ARG_FAIL;
	}
	psAssert(ssl && ssl->insize > 0 && ssl->inbuf != NULL);

	if ((ssl->insize - ssl->inlen) >= size) {
		/* Already enough room in current buffer */
		return matrixSslGetReadbuf(ssl, buf);
	}

	/* Going to have to grow... but do we have to realloc to save data? */
	if (ssl->inlen == 0) {
		/* buffer is empty anyway so can free before alloc and help keep high
			water mark down */
		psFree(ssl->inbuf, ssl->bufferPool);
		ssl->inbuf = NULL;
		if ((ssl->inbuf = psMalloc(ssl->bufferPool, size)) == NULL) {
			ssl->insize = 0;
			return PS_MEM_FAIL;
		}
		ssl->insize = size;
		*buf = ssl->inbuf;
		return ssl->insize;
	} else {
		/* realloc with: total size = current size + requested size */
		if ((p = psRealloc(ssl->inbuf, ssl->inlen + size, ssl->bufferPool))
				== NULL) {
			ssl->inbuf = NULL; ssl->insize = 0; ssl->inlen = 0;
			return PS_MEM_FAIL;
		}
		ssl->inbuf = p;
		ssl->insize = ssl->inlen + size;
		*buf = ssl->inbuf + ssl->inlen;
		return size;
	}
	return PS_FAILURE; /* can't hit */
}
Example #22
0
/*
    Public GCM encrypt function.  This will just perform the encryption.  The
    tag should be fetched with psAesGetGCMTag
 */
void psAesEncryptGCM(psAesGcm_t *ctx, const unsigned char *pt, unsigned char *ct, uint32_t len)
{
    unsigned long long ciphertext_len;
    unsigned char *resultEncryption;

    resultEncryption = psMalloc(NULL, len + sizeof(ctx->Tag));

    /* libsodium will put the (cipher text and the tag) in the result, */
    crypto_aead_aes256gcm_encrypt_afternm(resultEncryption, &ciphertext_len,
        (const unsigned char *) pt, (unsigned long long) len,
        (const unsigned char *) ctx->Aad, (unsigned long long) ctx->AadLen,
        NULL, (const unsigned char *) ctx->IV,
        (crypto_aead_aes256gcm_state *) &(ctx->libSodiumCtx));

    /* Copy the authentication tag in context to be able to retrieve it later */
    memcpy(ctx->Tag, (resultEncryption + len), sizeof(ctx->Tag));

    /* Copy the ciphertext in destination */
    memcpy(ct, resultEncryption, len);

    psFree(resultEncryption, NULL);
}
Example #23
0
/*
    Must be called on session returned from matrixSslGetSessionId
*/
void matrixSslFreeSessionId(sslSessionId_t *sessionId)
{
    if (sessionId != NULL) {
        psFree(sessionId);
    }
}
Example #24
0
/*
	User must call after all calls to matrixX509ParseCert
	(we violate the coding standard a bit here for clarity)
*/
void matrixX509FreeCert(sslRsaCert_t *cert)
{
	sslRsaCert_t	*curr, *next;

	curr = cert;
	while (curr) {
		psFreeDNStruct(&curr->issuer);
		psFreeDNStruct(&curr->subject);
		if (curr->serialNumber)			psFree(curr->serialNumber);
		if (curr->notBefore)			psFree(curr->notBefore);
		if (curr->notAfter)				psFree(curr->notAfter);
		if (curr->publicKey.N.dp)		mp_clear(&(curr->publicKey.N));
		if (curr->publicKey.e.dp)		mp_clear(&(curr->publicKey.e));
		if (curr->signature)			psFree(curr->signature);
		if (curr->uniqueUserId)			psFree(curr->uniqueUserId);
		if (curr->uniqueSubjectId)		psFree(curr->uniqueSubjectId);
		if (curr->extensions.san.dns)	psFree(curr->extensions.san.dns);
		if (curr->extensions.san.uri)	psFree(curr->extensions.san.uri);
		if (curr->extensions.san.email)	psFree(curr->extensions.san.email);
#ifdef USE_FULL_CERT_PARSE
		if (curr->extensions.sk.id)		psFree(curr->extensions.sk.id);
		if (curr->extensions.ak.keyId)	psFree(curr->extensions.ak.keyId);
		if (curr->extensions.ak.serialNum)
						psFree(curr->extensions.ak.serialNum);
		if (curr->extensions.ak.attribs.commonName)
						psFree(curr->extensions.ak.attribs.commonName);
		if (curr->extensions.ak.attribs.country)
						psFree(curr->extensions.ak.attribs.country);
		if (curr->extensions.ak.attribs.state)
						psFree(curr->extensions.ak.attribs.state);
		if (curr->extensions.ak.attribs.locality)
						psFree(curr->extensions.ak.attribs.locality);
		if (curr->extensions.ak.attribs.organization)
						psFree(curr->extensions.ak.attribs.organization);
		if (curr->extensions.ak.attribs.orgUnit)
						psFree(curr->extensions.ak.attribs.orgUnit);
#endif /* SSL_FULL_CERT_PARSE */
		next = curr->next;
		psFree(curr);
		curr = next;
	}
}	
Example #25
0
/*
 *	Public API to return a binary buffer from a cert.  Suitable to send
 *	over the wire.  Caller must free 'out' if this function returns success (0)
 *	Parse .pem files according to http://www.faqs.org/rfcs/rfc1421.html
 */
int32 matrixX509ReadCert(psPool_t *pool, const char *fileName,
					unsigned char **out, int32 *outLen, sslChainLen_t *chain)
{
	int32			certBufLen, rc, certChainLen, i;
	unsigned char	*oneCert[MAX_CHAIN_LENGTH];
	unsigned char	*certPtr, *tmp;
	char			*certFile, *start, *end, *certBuf;
	const char		sep[] = ";";

/*
	Init chain array and output params
*/
	for (i=0; i < MAX_CHAIN_LENGTH; i++) {
		oneCert[i] = NULL;
		(*chain)[i] = 0;
	}
	*outLen = certChainLen = i = 0;
	rc = -1;

/*
	For PKI product purposes, this routine now accepts a chain of certs.
*/
	if (fileName != NULL) {
		fileName += parseList(pool, fileName, sep, &certFile);
	} else {
		return 0;
	}

	while (certFile != NULL) {
	
		if (i == MAX_CHAIN_LENGTH) {
			matrixIntDebugMsg("Exceeded maximum cert chain length of %d\n",
				MAX_CHAIN_LENGTH);
			psFree(certFile);
			rc = -1;
			goto err;
		}
		if ((rc = psGetFileBin(pool, certFile, (unsigned char**)&certBuf,
				&certBufLen)) < 0) {
			matrixStrDebugMsg("Couldn't open file %s\n", certFile);
			goto err;
		}
		psFree(certFile);
		certPtr = (unsigned char*)certBuf;
		start = end = certBuf;

		while (certBufLen > 0) {
			if (((start = strstr(certBuf, "-----BEGIN")) != NULL) && 
					((start = strstr(certBuf, "CERTIFICATE-----")) != NULL) &&
					(end = strstr(start, "-----END")) != NULL) {
				start += strlen("CERTIFICATE-----");
				(*chain)[i] = (int32)(end - start);
				end += strlen("-----END CERTIFICATE-----");
				while (*end == '\r' || *end == '\n' || *end == '\t' || *end == ' ') {
					end++;
				}
			} else {
				psFree(certPtr);
				rc = -1;
				goto err;
			}
			oneCert[i] = psMalloc(pool, (*chain)[i]);
			certBufLen -= (int32)(end - certBuf);
			certBuf = end;
			memset(oneCert[i], '\0', (*chain)[i]);

			if (ps_base64_decode((unsigned char*)start, (*chain)[i], oneCert[i],
					&(*chain)[i]) != 0) {
				psFree(certPtr);
				matrixStrDebugMsg("Unable to base64 decode certificate\n", NULL);
				rc = -1;
				goto err;
			}
			certChainLen += (*chain)[i];
			i++;
			if (i == MAX_CHAIN_LENGTH) { 
				matrixIntDebugMsg("Exceeded maximum cert chain length of %d\n", 
					MAX_CHAIN_LENGTH); 
				psFree(certPtr); 
				rc = -1; 
				goto err; 
			} 
		}
		psFree(certPtr);
/*
		Check for more files
*/
		fileName += parseList(pool, fileName, sep, &certFile);
	}

	*outLen = certChainLen;
/*
	Don't bother stringing them together if only one was passed in
*/
	if (i == 1) {
		sslAssert(certChainLen == (*chain)[0]);
		*out = oneCert[0];
		return 0;
	} else {
		*out = tmp = psMalloc(pool, certChainLen);
		for (i=0; i < MAX_CHAIN_LENGTH; i++) {
			if (oneCert[i]) {
				memcpy(tmp, oneCert[i], (*chain)[i]);
				tmp += (*chain)[i];
			}
		}
		rc = 0;
	}

err:
	for (i=0; i < MAX_CHAIN_LENGTH; i++) {
		if (oneCert[i]) psFree(oneCert[i]);
	}
	return rc;
}
Example #26
0
/*
	Preferred version for commercial users who make use of memory pools.

	This use of the sslKeys_t param implies this is for use in the MatrixSSL
	product (input to matrixSslNewSession).  However, we didn't want to
	expose this API at the matrixSsl.h level due to the pool parameter. This
	is strictly an API that commerical users will have access to
*/
int32 matrixRsaReadKeysEx(psPool_t *pool, sslKeys_t **keys,
				const char *certFile, const char *privFile,
				const char *privPass, const char *trustedCAFiles)
{
	sslKeys_t		*lkeys;
	unsigned char	*privKeyMem;
	int32			rc, privKeyMemLen;
#ifdef USE_CLIENT_SIDE_SSL
	sslRsaCert_t	*currCert, *prevCert = NULL;
	unsigned char	*caCert, *caStream;
	sslChainLen_t	chain;
	int32			caCertLen, first, i;
#endif /* USE_CLIENT_SIDE_SSL */

	*keys = lkeys = psMalloc(pool, sizeof(sslKeys_t));
	if (lkeys == NULL) {
		return -8; /* SSL_MEM_ERROR */
	}
	memset(lkeys, 0x0, sizeof(sslKeys_t));
/*
	Load certificate files.  Any additional certificate files should chain
	to the root CA held on the other side.
*/
	rc = readCertChain(pool, certFile, &lkeys->cert);
	if (rc < 0 ) {
		matrixRsaFreeKeys(lkeys);
		return rc;
	}
/*
	The first cert in certFile must be associated with the provided
	private key. 
*/
	if (privFile) {
		rc = matrixRsaReadPrivKey(pool, privFile, privPass, &privKeyMem,
			&privKeyMemLen);
		if (rc < 0) {
			matrixStrDebugMsg("Error reading private key file: %s\n",
				(char*)privFile);
			matrixRsaFreeKeys(lkeys);
			return rc;
		}
		rc = matrixRsaParsePrivKey(pool, privKeyMem, privKeyMemLen,
			&lkeys->cert.privKey);
		if (rc < 0) {
			matrixStrDebugMsg("Error parsing private key file: %s\n",
				(char*)privFile);
			psFree(privKeyMem);
			matrixRsaFreeKeys(lkeys);
			return rc;
		}
		psFree(privKeyMem);
	}

#ifdef USE_CLIENT_SIDE_SSL
/*
	Now deal with Certificate Authorities
*/
	if (trustedCAFiles != NULL) {
		if (matrixX509ReadCert(pool, trustedCAFiles, &caCert, &caCertLen,
				&chain) < 0 || caCert == NULL) {
			matrixStrDebugMsg("Error reading CA cert files %s\n",
				(char*)trustedCAFiles);
			matrixRsaFreeKeys(lkeys);
			return -1;
		}

		caStream = caCert;
		i = first = 0;
		while (chain[i] != 0) {
/*
			Don't allow one bad cert to ruin the whole bunch if possible
*/
			if (matrixX509ParseCert(pool, caStream, chain[i], &currCert) < 0) {
				matrixX509FreeCert(currCert);
				matrixStrDebugMsg("Error parsing CA cert %s\n",
					(char*)trustedCAFiles);
				caStream += chain[i]; caCertLen -= chain[i];
				i++;
				continue;
			}
		
			if (first == 0) {
				lkeys->caCerts = currCert;
			} else {
				prevCert->next = currCert;
			}
			first++;
			prevCert = currCert;
			currCert = NULL;
			caStream += chain[i]; caCertLen -= chain[i];
			i++;
		}
		sslAssert(caCertLen == 0);
		psFree(caCert);
	}
/*
	Check to see that if a set of CAs were passed in at least
	one ended up being valid.
*/
	if (trustedCAFiles != NULL && lkeys->caCerts == NULL) {
		matrixStrDebugMsg("No valid CA certs in %s\n",
			(char*)trustedCAFiles);
		matrixRsaFreeKeys(lkeys);
		return -1;
	}
#endif /* USE_CLIENT_SIDE_SSL */
	return 0; 
}
Example #27
0
/*
	Calls a user defined callback to allow for manual validation of the
	certificate.
*/
int32 matrixX509UserValidator(psPool_t *pool, sslRsaCert_t *subjectCert,
			int32 (*certValidator)(sslCertInfo_t *t, void *arg), void *arg)
{
	sslCertInfo_t	*cert, *current, *next;
	int32			rc;

	if (certValidator == NULL) {
		return 0;
	}
/*
	Pass the entire certificate chain to the user callback.
*/
	current = cert = psMalloc(pool, sizeof(sslCertInfo_t));
	if (current == NULL) {
		return -8; /* SSL_MEM_ERROR */
	}
	memset(cert, 0x0, sizeof(sslCertInfo_t));
	while (subjectCert) {
		
		current->issuer.commonName = subjectCert->issuer.commonName;
		current->issuer.country = subjectCert->issuer.country;
		current->issuer.locality = subjectCert->issuer.locality;
		current->issuer.organization = subjectCert->issuer.organization;
		current->issuer.orgUnit = subjectCert->issuer.orgUnit;
		current->issuer.state = subjectCert->issuer.state;

		current->subject.commonName = subjectCert->subject.commonName;
		current->subject.country = subjectCert->subject.country;
		current->subject.locality = subjectCert->subject.locality;
		current->subject.organization = subjectCert->subject.organization;
		current->subject.orgUnit = subjectCert->subject.orgUnit;
		current->subject.state = subjectCert->subject.state;

		current->serialNumber = subjectCert->serialNumber;
		current->serialNumberLen = subjectCert->serialNumberLen;
		current->verified = subjectCert->valid;
		current->notBefore = subjectCert->notBefore;
		current->notAfter = subjectCert->notAfter;

		current->subjectAltName.dns = (char*)subjectCert->extensions.san.dns;
		current->subjectAltName.uri = (char*)subjectCert->extensions.san.uri;
		current->subjectAltName.email = (char*)subjectCert->extensions.san.email;
	
		if (subjectCert->certAlgorithm == OID_RSA_MD5 ||
				subjectCert->certAlgorithm == OID_RSA_MD2) {
			current->sigHashLen = SSL_MD5_HASH_SIZE;
		} else if (subjectCert->certAlgorithm == OID_RSA_SHA1) {
			current->sigHashLen = SSL_SHA1_HASH_SIZE;
		}
		current->sigHash = (char*)subjectCert->sigHash;
		if (subjectCert->next) {
			next = psMalloc(pool, sizeof(sslCertInfo_t));
			if (next == NULL) {
				while (cert) {
					next = cert->next;
					psFree(cert);
					cert = next;
				}
				return -8; /* SSL_MEM_ERROR */
			}
			memset(next, 0x0, sizeof(sslCertInfo_t));
			current->next = next;
			current = next;
		}
		subjectCert = subjectCert->next;
	}
/*
	The user callback
*/
	rc = certValidator(cert, arg);
/*
	Free the chain
*/
	while (cert) {
		next = cert->next;
		psFree(cert);
		cert = next;
	}
	return rc;
}
Example #28
0
/*
	Implementations of this specification MUST be prepared to receive
	the following standard attribute types in issuer names:
	country, organization, organizational-unit, distinguished name qualifier,
	state or province name, and common name 
*/
int32 getDNAttributes(psPool_t *pool, unsigned char **pp, int32 len, 
						   DNattributes_t *attribs)
{
	sslSha1Context_t	hash;
	unsigned char		*p = *pp;
	unsigned char		*dnEnd, *dnStart;
	int32				llen, setlen, arcLen, id, stringType;
	char				*stringOut;

	dnStart = p;
	if (getSequence(&p, len, &llen) < 0) {
		return -1;
	}
	dnEnd = p + llen;

	matrixSha1Init(&hash);
	while (p < dnEnd) {
		if (getSet(&p, (int32)(dnEnd - p), &setlen) < 0) {
			return -1;
		}
		if (getSequence(&p, (int32)(dnEnd - p), &llen) < 0) {
			return -1;
		}
		if (dnEnd <= p || (*(p++) != ASN_OID) ||
				asnParseLength(&p, (int32)(dnEnd - p), &arcLen) < 0 || 
				(dnEnd - p) < arcLen) {
			return -1;
		}
/*
		id-at   OBJECT IDENTIFIER       ::=     {joint-iso-ccitt(2) ds(5) 4}
		id-at-commonName		OBJECT IDENTIFIER		::=		{id-at 3}
		id-at-countryName		OBJECT IDENTIFIER		::=		{id-at 6}
		id-at-localityName		OBJECT IDENTIFIER		::=		{id-at 7}
		id-at-stateOrProvinceName		OBJECT IDENTIFIER	::=	{id-at 8}
		id-at-organizationName			OBJECT IDENTIFIER	::=	{id-at 10}
		id-at-organizationalUnitName	OBJECT IDENTIFIER	::=	{id-at 11}
*/
		*pp = p;
/*
		FUTURE: Currently skipping OIDs not of type {joint-iso-ccitt(2) ds(5) 4}
		However, we could be dealing with an OID we MUST support per RFC.
		domainComponent is one such example.
*/
		if (dnEnd - p < 2) {
			return -1;
		}
		if ((*p++ != 85) || (*p++ != 4) ) {
			p = *pp;
/*
			Move past the OID and string type, get data size, and skip it.
			NOTE: Have had problems parsing older certs in this area.
*/
			if (dnEnd - p < arcLen + 1) {
				return -1;
			}
			p += arcLen + 1;
			if (asnParseLength(&p, (int32)(dnEnd - p), &llen) < 0 || 
					dnEnd - p < llen) {
				return -1;
			}
			p = p + llen;
			continue;
		}
/*
		Next are the id of the attribute type and the ASN string type
*/
		if (arcLen != 3 || dnEnd - p < 2) {
			return -1;
		}
		id = (int32)*p++;
/*
		Done with OID parsing
*/
		stringType = (int32)*p++;

		asnParseLength(&p, (int32)(dnEnd - p), &llen);
		if (dnEnd - p < llen) {
			return -1;
		}
		switch (stringType) {
			case ASN_PRINTABLESTRING:
			case ASN_UTF8STRING:
			case ASN_IA5STRING:
			case ASN_T61STRING:
			case ASN_BMPSTRING:
				stringOut = psMalloc(pool, llen + 1);
				if (stringOut == NULL) {
					return -8; /* SSL_MEM_ERROR */
				}
				memcpy(stringOut, p, llen);
				stringOut[llen] = '\0';
				p = p + llen;
				break;
			default:
				matrixStrDebugMsg("Parsing untested DN attrib type\n", NULL);
				return -1;
		}

		switch (id) {
			case ATTRIB_COUNTRY_NAME:
				if (attribs->country) {
					psFree(attribs->country);
				}
				attribs->country = stringOut;
				break;
			case ATTRIB_STATE_PROVINCE:
				if (attribs->state) {
					psFree(attribs->state);
				}
				attribs->state = stringOut;
				break;
			case ATTRIB_LOCALITY:
				if (attribs->locality) {
					psFree(attribs->locality);
				}
				attribs->locality = stringOut;
				break;
			case ATTRIB_ORGANIZATION:
				if (attribs->organization) {
					psFree(attribs->organization);
				}
				attribs->organization = stringOut;
				break;
			case ATTRIB_ORG_UNIT:
				if (attribs->orgUnit) {
					psFree(attribs->orgUnit);
				}
				attribs->orgUnit = stringOut;
				break;
			case ATTRIB_COMMON_NAME:
				if (attribs->commonName) {
					psFree(attribs->commonName);
				}
				attribs->commonName = stringOut;
				break;
/*
			Not a MUST support
*/
			default:
				psFree(stringOut);
				stringOut = NULL;
				break;
		}
/*
		Hash up the DN.  Nice for validation later
*/
		if (stringOut != NULL) {
			matrixSha1Update(&hash, (unsigned char*)stringOut, llen);
		}
	}
	matrixSha1Final(&hash, (unsigned char*)attribs->hash);
	*pp = p;
	return 0;
}
Example #29
0
int main(int argc, char **argv)
{
	int32			id;
	sslConn_t		*svrConn, *clnConn;
#ifdef ENABLE_PERF_TIMING
	int32			perfIter;
	uint32			clnTime, svrTime;
#endif /* ENABLE_PERF_TIMING */
		
	if (matrixSslOpen() < 0) {
		fprintf(stderr, "matrixSslOpen failed, exiting...");
	}

	svrConn = psMalloc(PEERSEC_NO_POOL, sizeof(sslConn_t));
	clnConn = psMalloc(PEERSEC_NO_POOL, sizeof(sslConn_t));
	memset(svrConn, 0, sizeof(sslConn_t));
	memset(clnConn, 0, sizeof(sslConn_t));
	
	for (id = 0; ciphers[id].cipherId > 0; id++) {
		matrixSslInitSessionId(clientSessionId);
		_psTraceStr("Testing %s suite\n", ciphers[id].name);
/*
		Standard Handshake
*/
		_psTrace("	Standard handshake test\n");
#ifdef ENABLE_PERF_TIMING
/*
		Each matrixSsl call in the handshake is wrapped by a timer.  The 
		data exchange phase is not being included in the time
*/
		clnTime = svrTime = 0;
		for (perfIter = 0; perfIter < CONN_ITER; perfIter++) {
#endif /* ENABLE_PERF_TIMING */		
		if (initializeHandshake(clnConn, svrConn, ciphers[id],
				&clientSessionId) < 0) {
			_psTrace("		FAILED: initializing Standard handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(clnConn, svrConn) < 0) {
			_psTrace("		FAILED: Standard handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Standard handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}
#ifdef ENABLE_PERF_TIMING
		clnTime += clnConn->runningTime;
		svrTime += svrConn->runningTime;
		/* Have to reset conn for full handshake... except last time through */
		if (perfIter + 1 != CONN_ITER) {
			matrixSslDeleteSession(clnConn->ssl);
			matrixSslDeleteSession(svrConn->ssl);
			matrixSslInitSessionId(clientSessionId);
		}
		} /* iteration loop close */
		_psTraceInt("CLIENT:  %d " TIME_UNITS, (int32)clnTime/CONN_ITER);
		_psTraceInt("SERVER:  %d " TIME_UNITS, (int32)svrTime/CONN_ITER);
//		_psTrace("Press any key to continue tests");
		_psTrace("\n==========\n");
//		getchar();
#endif /* ENABLE_PERF_TIMING */
		
#ifdef SSL_REHANDSHAKES_ENABLED		
/*
		 Re-Handshake (full handshake over existing connection)
*/		
		_psTrace("	Re-handshake test (client-initiated)\n");		
		if (initializeReHandshake(clnConn, svrConn, ciphers[id].cipherId) < 0) {
			_psTrace("		FAILED: initializing Re-handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(clnConn, svrConn) < 0) {
			_psTrace("		FAILED: Re-handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Re-handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}	
#else
		_psTrace("	Re-handshake tests are disabled (ENABLE_SECURE_REHANDSHAKES)\n");
#endif
				
/*
		Resumed handshake (fast handshake over new connection)
*/				
		_psTrace("	Resumed handshake test (new connection)\n");
#ifdef ENABLE_PERF_TIMING
		clnTime = svrTime = 0;
		for (perfIter = 0; perfIter < CONN_ITER; perfIter++) {
#endif /* ENABLE_PERF_TIMING */			
		if (initializeResumedHandshake(clnConn, svrConn,
				ciphers[id]) < 0) {
			_psTrace("		FAILED: initializing Resumed handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(clnConn, svrConn) < 0) {
			_psTrace("		FAILED: Resumed handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Resumed handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}
#ifdef ENABLE_PERF_TIMING
		clnTime += clnConn->runningTime;
		svrTime += svrConn->runningTime;
		/* Have to reset conn for full handshake */
		} /* iteration loop */
		_psTraceInt("CLIENT:  %d " TIME_UNITS, (int32)clnTime/CONN_ITER);
		_psTraceInt("SERVER:  %d " TIME_UNITS, (int32)svrTime/CONN_ITER);
		_psTrace("Press any key to continue tests");
		_psTrace("\n==========\n");
//		getchar();
#endif /* ENABLE_PERF_TIMING */		
		
#ifdef SSL_REHANDSHAKES_ENABLED		
/*
		 Re-handshake initiated by server (full handshake over existing conn)
*/			
		_psTrace("	Re-handshake test (server initiated)\n");
		if (initializeServerInitiatedReHandshake(clnConn, svrConn,
									   ciphers[id].cipherId) < 0) {
			_psTrace("		FAILED: initializing Re-handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(svrConn, clnConn) < 0) {
			_psTrace("		FAILED: Re-handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Re-handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}	
	
/*
		Resumed re-handshake (fast handshake over existing connection)
*/				
		_psTrace("	Resumed Re-handshake test (client initiated)\n");
		if (initializeResumedReHandshake(clnConn, svrConn,
				 ciphers[id].cipherId) < 0) {
				_psTrace("		FAILED: initializing Resumed Re-handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(clnConn, svrConn) < 0) {
			_psTrace("		FAILED: Resumed Re-handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Resumed Re-handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}
		
/*
		 Resumed re-handshake initiated by server (fast handshake over conn)
*/		
		_psTrace("	Resumed Re-handshake test (server initiated)\n");
		if (initializeServerInitiatedResumedReHandshake(clnConn, svrConn,
									   ciphers[id].cipherId) < 0) {
				_psTrace("		FAILED: initializing Resumed Re-handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(svrConn, clnConn) < 0) {
			_psTrace("		FAILED: Resumed Re-handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Resumed Re-handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}		
/*
		Re-handshaking with "upgraded" parameters
*/
		_psTrace("	Change cert callback Re-handshake test\n");
		if (initializeUpgradeCertCbackReHandshake(clnConn, svrConn,
									   ciphers[id].cipherId) < 0) {
				_psTrace("		FAILED: init upgrade certCback Re-handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(clnConn, svrConn) < 0) {
			_psTrace("		FAILED: Upgrade cert callback Re-handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Upgrade cert callback Re-handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}		
/*
		Upgraded keys
*/
		_psTrace("	Change keys Re-handshake test\n");
		if (initializeUpgradeKeysReHandshake(clnConn, svrConn,
									   ciphers[id].cipherId) < 0) {
				_psTrace("		FAILED: init upgrade keys Re-handshake\n");
			goto LBL_FREE;
		}
		if (performHandshake(clnConn, svrConn) < 0) {
			_psTrace("		FAILED: Upgrade keys Re-handshake\n");
			goto LBL_FREE;
		} else {
			testTrace("		PASSED: Upgrade keys Re-handshake");
			if (exchangeAppData(clnConn, svrConn) < 0) {
				_psTrace(" but FAILED to exchange application data\n");
			} else {
				testTrace("\n");
			}
		}
/*
		Change cipher spec test.  Changing to a hardcoded RSA suite so this
		will not work on suites that don't have RSA material loaded
*/
		if (ciphers[id].rsa == 1) {
			_psTrace("	Change cipher suite Re-handshake test\n");
			if (initializeChangeCipherReHandshake(clnConn, svrConn,
									   ciphers[id].cipherId) < 0) {
					_psTrace("		FAILED: init change cipher Re-handshake\n");
				goto LBL_FREE;
			}
			if (performHandshake(clnConn, svrConn) < 0) {
				_psTrace("		FAILED: Change cipher suite Re-handshake\n");
				goto LBL_FREE;
			} else {
				testTrace("		PASSED: Change cipher suite Re-handshake");
				if (exchangeAppData(clnConn, svrConn) < 0) {
					_psTrace(" but FAILED to exchange application data\n");
				} else {
					testTrace("\n");
				}
			}
		}
#endif /* !SSL_REHANDSHAKES_ENABLED */


LBL_FREE:
		freeSessionAndConnection(svrConn);
		freeSessionAndConnection(clnConn);
	}
	psFree(svrConn);
	psFree(clnConn);
	matrixSslClose();

#ifdef WIN32
	_psTrace("Press any key to close");
	getchar();
#endif

	return PS_SUCCESS;	
}
Example #30
0
int main(int argc, char **argv)
{
	psPool_t		*pool, *misc;
	psDhParams_t	dhParams;
	psDhKey_t		dhKeyPriv, dhKeyPub;
	uint16_t		pLen, gLen;
	unsigned char	*p, *g;
	psTime_t		start, end;
	uint16_t		iter, i = 0;
	unsigned char	out[512];
	uint16_t		outLen = sizeof(out);

	pool = misc = NULL;
	if (psCryptoOpen(PSCRYPTO_CONFIG) < PS_SUCCESS) {
		_psTrace("Failed to initialize library:  psCryptoOpen failed\n");
		return -1;
	}
	_psTraceStr("STARTING DHPERF\n", NULL);

	while (keys[i].key != NULL) {
		_psTraceStr("Test %s...\n", keys[i].name);
		pkcs3ParseDhParamBin(misc, (unsigned char*)keys[i].key,	keys[i].len,
			&dhParams);

		iter = 0;

#ifdef DO_GEN_INTS
		psGetTime(&start, NULL);
		while (iter < keys[i].iter) {
			if (psDhGenKeyInts(pool, dhParams.size, &dhParams.p, &dhParams.g,
					&dhKeyPriv, NULL) < 0) {
				_psTrace("	FAILED OPERATION\n");
			}

			psDhClearKey(&dhKeyPriv);
			iter++;
		}
		psGetTime(&end, NULL);
		_psTraceInt(TIME_UNITS " genInts\n", psDiffMsecs(start, end, NULL));
#endif /* DO_GEN_INTS */

#ifdef DO_GEN_SECRET
		psDhExportParameters(misc, &dhParams, &p, &pLen, &g, &gLen);
		if (psDhGenKeyInts(misc, dhParams.size, &dhParams.p, &dhParams.g,
				&dhKeyPriv, NULL) < 0) {
			_psTrace("	FAILED OPERATION\n");
		}
		if (psDhGenKeyInts(misc, dhParams.size, &dhParams.p, &dhParams.g,
				&dhKeyPub, NULL) < 0) {
			_psTrace("	FAILED OPERATION\n");
		}
		iter = 0;
		outLen = sizeof(out);
		psGetTime(&start, NULL);
		while (iter < keys[i].iter) {
			if (psDhGenSharedSecret(pool, &dhKeyPriv, &dhKeyPub, p, pLen,
					out, &outLen, NULL) < 0) {
				_psTrace("	FAILED OPERATION\n");
			}

			iter++;
		}
		psGetTime(&end, NULL);
		psDhClearKey(&dhKeyPriv);
		psDhClearKey(&dhKeyPub);
		_psTraceInt(TIME_UNITS " genSecret\n", psDiffMsecs(start, end, NULL));
#endif /* DO_GEN_SECRET */

		psFree(p, misc);
		psFree(g, misc);
		pkcs3ClearDhParams(&dhParams);
		i++;
	}

#ifdef WIN32
	_psTrace("Press any key to close");
	getchar();
#endif
	_psTraceStr("FINISHED DHPERF\n", NULL);
	psCryptoClose();
	return 0;
}