bzrtp.c 48.8 KB
Newer Older
johan's avatar
johan committed
1 2 3 4
/**
 @file bzrtp.c

 @brief Public entry points to the ZRTP implementation
5

johan's avatar
johan committed
6 7
 @author Johan Pascal

8
 @copyright Copyright (C) 2017 Belledonne Communications, Grenoble, France
9

johan's avatar
johan committed
10 11 12 13
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.
14

johan's avatar
johan committed
15 16 17 18
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
19

johan's avatar
johan committed
20 21
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
22
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
johan's avatar
johan committed
23 24 25 26 27 28 29
 */
#include <string.h>
#include <stdlib.h>

#include "bzrtp/bzrtp.h"

#include "typedef.h"
30
#include "bctoolbox/crypto.h"
johan's avatar
johan committed
31 32
#include "cryptoUtils.h"
#include "zidCache.h"
johan's avatar
johan committed
33
#include "packetParser.h"
34
#include "stateMachine.h"
johan's avatar
johan committed
35

johan's avatar
johan committed
36
#define BZRTP_ERROR_INVALIDCHANNELCONTEXT 0x8001
johan's avatar
johan committed
37

38
/* local functions prototypes */
39
static int bzrtp_initChannelContext(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, uint32_t selfSSRC, uint8_t isMain);
40 41 42
static void bzrtp_destroyChannelContext(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext);
static bzrtpChannelContext_t *getChannelContext(bzrtpContext_t *zrtpContext, uint32_t selfSSRC);
static uint8_t copyCryptoTypes(uint8_t destination[7], uint8_t source[7], uint8_t size);
johan's avatar
johan committed
43

johan's avatar
johan committed
44
/*
45
 * Create context structure and initialise it
johan's avatar
johan committed
46
 *
johan's avatar
johan committed
47
 * @return The ZRTP engine context data
48
 *
johan's avatar
johan committed
49
*/
50
bzrtpContext_t *bzrtp_createBzrtpContext(void) {
johan's avatar
johan committed
51 52 53 54 55 56
	int i;
	/*** create and intialise the context structure ***/
	bzrtpContext_t *context = malloc(sizeof(bzrtpContext_t));
	memset(context, 0, sizeof(bzrtpContext_t));

	/* start the random number generator */
jehan's avatar
jehan committed
57
	context->RNGContext = bctbx_rng_context_new(); /* TODO: give a seed for the RNG? */
johan's avatar
johan committed
58
	/* set the DHM context to NULL, it will be created if needed when creating a DHPart packet */
59 60
	context->keyAgreementContext = NULL;
	context->keyAgreementAlgo = ZRTP_UNSET_ALGO;
johan's avatar
johan committed
61

johan's avatar
johan committed
62 63 64
	/* set flags */
	context->isSecure = 0; /* start unsecure */
	context->peerSupportMultiChannel = 0; /* peer does not support Multichannel by default */
65
	context->isInitialised = 0; /* will be set by bzrtp_initBzrtpContext */
johan's avatar
johan committed
66

johan's avatar
johan committed
67
	/* set to NULL all callbacks pointer */
68
	context->zrtpCallbacks.bzrtp_statusMessage = NULL;
69 70 71
	context->zrtpCallbacks.bzrtp_sendData = NULL;
	context->zrtpCallbacks.bzrtp_srtpSecretsAvailable = NULL;
	context->zrtpCallbacks.bzrtp_startSrtpSession = NULL;
72
	context->zrtpCallbacks.bzrtp_contextReadyForExportedKeys = NULL;
73

74

johan's avatar
johan committed
75 76 77 78

	for (i=1; i<ZRTP_MAX_CHANNEL_NUMBER; i++) {
		context->channelContext[i] = NULL;
	}
johan's avatar
johan committed
79 80 81

	/* get the list of crypto algorithms provided by the crypto module */
	/* this list may then be updated according to users settings */
82 83 84 85 86
	context->hc = bzrtpUtils_getAvailableCryptoTypes(ZRTP_HASH_TYPE, context->supportedHash);
	context->cc = bzrtpUtils_getAvailableCryptoTypes(ZRTP_CIPHERBLOCK_TYPE, context->supportedCipher);
	context->ac = bzrtpUtils_getAvailableCryptoTypes(ZRTP_AUTHTAG_TYPE, context->supportedAuthTag);
	context->kc = bzrtpUtils_getAvailableCryptoTypes(ZRTP_KEYAGREEMENT_TYPE, context->supportedKeyAgreement);
	context->sc = bzrtpUtils_getAvailableCryptoTypes(ZRTP_SAS_TYPE, context->supportedSas);
johan's avatar
johan committed
87 88

	/* initialise cached secret buffer to null */
johan's avatar
johan committed
89 90 91 92
	context->zidCache = NULL; /* a pointer to the sqlite3 db accessor, can be NULL if running cacheless */
	context->zuid = 0;
	context->peerBzrtpVersion = 0;
	context->selfURI = NULL;
johan's avatar
johan committed
93 94 95 96 97 98 99 100
	context->cachedSecret.rs1 = NULL;
	context->cachedSecret.rs1Length = 0;
	context->cachedSecret.rs2 = NULL;
	context->cachedSecret.rs2Length = 0;
	context->cachedSecret.pbxsecret = NULL;
	context->cachedSecret.pbxsecretLength = 0;
	context->cachedSecret.auxsecret = NULL;
	context->cachedSecret.auxsecretLength = 0;
johan's avatar
johan committed
101
	context->cacheMismatchFlag = 0;
102
	context->peerPVS = 0;
103 104 105 106

	/* initialise transient shared auxiliary secret buffer */
	context->transientAuxSecret = NULL;
	context->transientAuxSecretLength = 0;
107

johan's avatar
johan committed
108 109 110
	/* initialise key buffers */
	context->ZRTPSess = NULL;
	context->ZRTPSessLength = 0;
johan's avatar
johan committed
111 112
	context->exportedKey = NULL;
	context->exportedKeyLength = 0;
johan's avatar
johan committed
113 114 115 116

	return context;
}

johan's avatar
johan committed
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
/**
 * @brief Set the pointer allowing cache access
 *
 * @param[in]	zidCachePointer		Used by internal function to access cache: turn into a sqlite3 pointer if cache is enabled
 *
 * @return 0 or BZRTP_CACHE_SETUP(if cache is populated by this call) on success, error code otherwise
*/
int bzrtp_setZIDCache(bzrtpContext_t *context, void *zidCache, const char *selfURI, const char *peerURI) {
#ifdef ZIDCACHE_ENABLED
	/* is zrtp context valid */
	if (context==NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/* zidCache pointer is actually a pointer to sqlite3 db, store it in context */
	context->zidCache = (sqlite3 *)zidCache;
Johan Pascal's avatar
Johan Pascal committed
133 134 135
	if (context->selfURI != NULL) {
		free(context->selfURI);
	}
johan's avatar
johan committed
136
	context->selfURI = strdup(selfURI);
Johan Pascal's avatar
Johan Pascal committed
137 138 139 140

	if (context->peerURI != NULL) {
		free(context->peerURI);
	}
johan's avatar
johan committed
141 142 143 144 145 146 147 148 149
	context->peerURI = strdup(peerURI);

	/* and init the cache(create needed tables if they don't exist) */
	return bzrtp_initCache(context->zidCache);
#else /* ZIDCACHE_ENABLED */
	return BZRTP_ERROR_CACHEDISABLED;
#endif /* ZIDCACHE_ENABLED */
}

johan's avatar
johan committed
150 151
/**
 * @brief Perform some initialisation which can't be done without some callback functions:
johan's avatar
johan committed
152
 *  This function is called once per session when the first channel is created.
johan's avatar
johan committed
153 154 155
 *  It must be called after the cache access pointer have been set
 *	- Get ZID from cache or generate a random ZID
 *	- Initialise the first channel
156
 *
johan's avatar
johan committed
157
 *	@param[in] 	context		The context to initialise
johan's avatar
johan committed
158 159
 *	@param[in]	selfSSRC	SSRC of the first channel
 * @return 0 on success
johan's avatar
johan committed
160
 */
johan's avatar
johan committed
161
int bzrtp_initBzrtpContext(bzrtpContext_t *context, uint32_t selfSSRC) {
johan's avatar
johan committed
162

johan's avatar
johan committed
163 164 165 166 167 168 169
	/* is zrtp context valid */
	if (context==NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/* initialise self ZID. Randomly generated if no ZID is found in cache or no cache found */
	bzrtp_getSelfZID(context->zidCache, context->selfURI, context->selfZID, context->RNGContext);
170 171 172 173 174
	context->isInitialised = 1;

	/* allocate 1 channel context, set all the others pointers to NULL */
	context->channelContext[0] = (bzrtpChannelContext_t *)malloc(sizeof(bzrtpChannelContext_t));
	memset(context->channelContext[0], 0, sizeof(bzrtpChannelContext_t));
johan's avatar
johan committed
175
	return bzrtp_initChannelContext(context, context->channelContext[0], selfSSRC, 1);
johan's avatar
johan committed
176 177
}

johan's avatar
johan committed
178 179 180 181
/*
 * Free memory of context structure to a channel, if all channels are freed, free the global zrtp context
 * @param[in]	context		Context hosting the channel to be destroyed.(note: the context zrtp context itself is destroyed with the last channel)
 * @param[in]	selfSSRC	The SSRC identifying the channel to be destroyed
182 183
 *
 * @return the number of channel still active in this ZRTP context
184
 *
johan's avatar
johan committed
185
*/
186
int bzrtp_destroyBzrtpContext(bzrtpContext_t *context, uint32_t selfSSRC) {
187 188 189
	int i;
	int validChannelsNumber = 0;

johan's avatar
johan committed
190
	if (context == NULL) {
191
		return 0;
johan's avatar
johan committed
192 193 194 195 196 197 198 199 200 201 202 203 204
	}

	/* Find the channel to be destroyed, destroy it and check if we have anymore valid channels */
	for (i=0; i<ZRTP_MAX_CHANNEL_NUMBER; i++) {
		if (context->channelContext[i] != NULL) {
			if (context->channelContext[i]->selfSSRC == selfSSRC) {
				bzrtp_destroyChannelContext(context, context->channelContext[i]);
				context->channelContext[i] = NULL;
			} else {
				validChannelsNumber++;
			}
		}
	}
johan's avatar
johan committed
205

johan's avatar
johan committed
206
	if (validChannelsNumber>0) {
207
		return validChannelsNumber; /* we have more valid channels, keep the zrtp context */
johan's avatar
johan committed
208
	}
johan's avatar
johan committed
209

johan's avatar
johan committed
210 211

	/* We have no more channel, destroy the zrtp context */
212 213 214 215 216 217 218 219 220 221
	/* key agreement context shall already been destroyed after s0 computation, but just in case */
	if (context->keyAgreementContext != NULL) {
		if (context->keyAgreementAlgo == ZRTP_KEYAGREEMENT_X255 || context->keyAgreementAlgo == ZRTP_KEYAGREEMENT_X448) {
			bctbx_DestroyECDHContext((bctbx_ECDHContext_t *)context->keyAgreementContext);
		}
		if (context->keyAgreementAlgo == ZRTP_KEYAGREEMENT_DH2k || context->keyAgreementAlgo == ZRTP_KEYAGREEMENT_DH3k) {
			bctbx_DestroyDHMContext((bctbx_DHMContext_t *)context->keyAgreementContext);
		}
		context->keyAgreementContext = NULL;
		context->keyAgreementAlgo = ZRTP_UNSET_ALGO;
johan's avatar
johan committed
222
	}
johan's avatar
johan committed
223

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
	/* Destroy keys and secrets */
	/* rs1, rs2, pbxsecret and auxsecret shall already been destroyed, just in case */
	if (context->cachedSecret.rs1!=NULL) {
		bzrtp_DestroyKey(context->cachedSecret.rs1, context->cachedSecret.rs1Length, context->RNGContext);
		free(context->cachedSecret.rs1);
		context->cachedSecret.rs1 = NULL;
	}
	if (context->cachedSecret.rs2!=NULL) {
		bzrtp_DestroyKey(context->cachedSecret.rs2, context->cachedSecret.rs2Length, context->RNGContext);
		free(context->cachedSecret.rs2);
		context->cachedSecret.rs2 = NULL;
	}
	if (context->cachedSecret.auxsecret!=NULL) {
		bzrtp_DestroyKey(context->cachedSecret.auxsecret, context->cachedSecret.auxsecretLength, context->RNGContext);
		free(context->cachedSecret.auxsecret);
		context->cachedSecret.auxsecret = NULL;
	}
	if (context->cachedSecret.pbxsecret!=NULL) {
		bzrtp_DestroyKey(context->cachedSecret.pbxsecret, context->cachedSecret.pbxsecretLength, context->RNGContext);
		free(context->cachedSecret.pbxsecret);
		context->cachedSecret.pbxsecret = NULL;
	}

	if (context->ZRTPSess!=NULL) {
		bzrtp_DestroyKey(context->ZRTPSess, context->ZRTPSessLength, context->RNGContext);
		free(context->ZRTPSess);
		context->ZRTPSess=NULL;
	}
johan's avatar
johan committed
252

johan's avatar
johan committed
253 254 255 256 257 258 259 260
	if (context->exportedKey!=NULL) {
		bzrtp_DestroyKey(context->exportedKey, context->exportedKeyLength, context->RNGContext);
		free(context->exportedKey);
		context->ZRTPSess=NULL;
	}

	free(context->selfURI);
	free(context->peerURI);
261

262 263 264 265 266 267 268
	/* transient shared auxiliary secret */
	if (context->transientAuxSecret != NULL) {
		bzrtp_DestroyKey(context->transientAuxSecret, context->transientAuxSecretLength, context->RNGContext);
		free(context->transientAuxSecret);
		context->transientAuxSecret=NULL;
	}

johan's avatar
johan committed
269
	/* destroy the RNG context at the end because it may be needed to destroy some keys */
jehan's avatar
jehan committed
270
	bctbx_rng_context_free(context->RNGContext);
johan's avatar
johan committed
271
	context->RNGContext = NULL;
johan's avatar
johan committed
272
	free(context);
273
	return 0;
johan's avatar
johan committed
274 275
}

276 277 278 279 280 281 282
/*
 * @brief Allocate a function pointer to the callback function identified by his id
 * @param[in/out]	context				The zrtp context to set the callback function
 * @param[in] 		cbs 				A structure containing all the callbacks to supply.
 *
 * @return 0 on success
*/
Simon Morlat's avatar
Simon Morlat committed
283
int bzrtp_setCallbacks(bzrtpContext_t *context, const bzrtpCallbacks_t *cbs) {
johan's avatar
johan committed
284 285 286 287 288
	/* is zrtp context valid */
	if (context==NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

Simon Morlat's avatar
Simon Morlat committed
289
	context->zrtpCallbacks=*cbs;
johan's avatar
johan committed
290 291
	return 0;
}
johan's avatar
johan committed
292

293 294 295 296 297 298 299 300
/**
 * @brief Add a channel to an existing context, this can be done only if the first channel has concluded a DH key agreement
 *
 * @param[in/out]	zrtpContext	The zrtp context who will get the additionnal channel. Must be in secure state.
 * @param[in]		selfSSRC	The SSRC given to the channel context
 *
 * @return 0 on succes, error code otherwise
 */
johan's avatar
johan committed
301
int bzrtp_addChannel(bzrtpContext_t *zrtpContext, uint32_t selfSSRC) {
302 303 304
	bzrtpChannelContext_t *zrtpChannelContext = NULL;
	int i=0;

johan's avatar
johan committed
305 306 307 308 309
	/* is zrtp context valid */
	if (zrtpContext==NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

310 311
	/* context must be initialised(selfZID available) to enable the creation of an additional channel */
	if (zrtpContext->isInitialised == 0) {
johan's avatar
johan committed
312 313 314 315 316 317 318 319 320
		return BZRTP_ERROR_CONTEXTNOTREADY;
	}

	/* get the first free channel context from ZRTP context and create a channel context */
	while(i<ZRTP_MAX_CHANNEL_NUMBER && zrtpChannelContext==NULL) {
		if (zrtpContext->channelContext[i] == NULL) {
			int retval;
			zrtpChannelContext = (bzrtpChannelContext_t *)malloc(sizeof(bzrtpChannelContext_t));
			memset(zrtpChannelContext, 0, sizeof(bzrtpChannelContext_t));
321
			retval = bzrtp_initChannelContext(zrtpContext, zrtpChannelContext, selfSSRC, 0);
johan's avatar
johan committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
			if (retval != 0) {
				free(zrtpChannelContext);
				return retval;
			}
		} else {
			i++;
		}
	}

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_UNABLETOADDCHANNEL;
	}

	/* attach the created channel to the ZRTP context */
	zrtpContext->channelContext[i] = zrtpChannelContext;

	return 0;

}
341 342 343 344 345 346 347 348 349 350 351

/*
 * @brief Start the state machine of the specified channel
 *
 * @param[in/out]	zrtpContext			The ZRTP context hosting the channel to be started
 * @param[in]		selfSSRC			The SSRC identifying the channel to be started(will start sending Hello packets and listening for some)
 *
 * @return			0 on succes, error code otherwise
 */

int bzrtp_startChannelEngine(bzrtpContext_t *zrtpContext, uint32_t selfSSRC) {
352
	bzrtpEvent_t initEvent;
353 354 355 356 357

	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
358 359 360 361 362 363
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/* is this channel already started? */
	if (zrtpChannelContext->stateMachine != NULL) {
		return BZRTP_ERROR_CHANNELALREADYSTARTED;
364 365
	}

366 367 368 369 370 371 372 373 374 375 376 377 378
	/* if this is an additional channel(not channel 0), we must be sure that channel 0 is already secured */
	if (zrtpChannelContext->isMainChannel == 0) {
		/* is ZRTP context able to add a channel (means channel 0 has already performed the secrets generation) */
		if (zrtpContext->isSecure == 0) {
			return BZRTP_ERROR_CONTEXTNOTREADY;
		}

		/* check the peer support Multichannel(shall be set in the first Hello message received) */
		if (zrtpContext->peerSupportMultiChannel == 0) {
			return BZRTP_ERROR_MULTICHANNELNOTSUPPORTEDBYPEER;
		}
	}

379 380 381 382 383 384 385 386 387 388 389 390 391
	/* set the timer reference to 0 to force a message to be sent at first timer tick */
	zrtpContext->timeReference = 0;

	/* start the engine by setting the state to init and calling it */
	zrtpChannelContext->stateMachine = state_discovery_init;

	/* create an INIT event to call the init state function which will create a hello packet and start sending it */
	initEvent.eventType = BZRTP_EVENT_INIT;
	initEvent.bzrtpPacketString = NULL;
	initEvent.bzrtpPacketStringLength = 0;
	initEvent.zrtpContext = zrtpContext;
	initEvent.zrtpChannelContext = zrtpChannelContext;

johan's avatar
johan committed
392
	return zrtpChannelContext->stateMachine(initEvent);
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
}

/*
 * @brief Send the current time to a specified channel, it will check if it has to trig some timer
 *
 * @param[in/out]	zrtpContext			The ZRTP context hosting the channel
 * @param[in]		selfSSRC			The SSRC identifying the channel
 * @param[in]		timeReference		The current time in ms
 *
 * @return			0 on succes, error code otherwise
 */
int bzrtp_iterate(bzrtpContext_t *zrtpContext, uint32_t selfSSRC, uint64_t timeReference) {
	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/* update the context time reference used when arming timers */
	zrtpContext->timeReference = timeReference;

	if (zrtpChannelContext->timer.status == BZRTP_TIMER_ON) {
		if (zrtpChannelContext->timer.firingTime<=timeReference) { /* we must trig the timer */
417
			bzrtpEvent_t timerEvent;
418

419 420 421 422 423 424
			zrtpChannelContext->timer.firingCount++;

			/* create a timer event */
			timerEvent.eventType = BZRTP_EVENT_TIMER;
			timerEvent.bzrtpPacketString = NULL;
			timerEvent.bzrtpPacketStringLength = 0;
425
			timerEvent.bzrtpPacket = NULL;
426 427 428 429
			timerEvent.zrtpContext = zrtpContext;
			timerEvent.zrtpChannelContext = zrtpChannelContext;

			/* send it to the state machine*/
430 431 432
			if (zrtpChannelContext->stateMachine != NULL) {
				return zrtpChannelContext->stateMachine(timerEvent);
			}
433 434 435 436 437 438 439 440 441 442 443 444 445 446
		}
	}

	return 0;
}

/*
 * @brief Set the client data pointer in a channel context
 * This pointer is returned to the client by the callbacks function, used to store associated contexts (RTP session)
 * @param[in/out]	zrtpContext		The ZRTP context we're dealing with
 * @param[in]		selfSSRC		The SSRC identifying the channel to be linked to the client Data
 * @param[in]		clientData		The clientData pointer, casted to a (void *)
 *
 * @return 0 on success
447
 *
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
*/
int bzrtp_setClientData(bzrtpContext_t *zrtpContext, uint32_t selfSSRC, void *clientData) {
	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	zrtpChannelContext->clientData = clientData;

	return 0;
}

/*
 * @brief Process a received message
 *
 * @param[in/out]	zrtpContext				The ZRTP context we're dealing with
 * @param[in]		selfSSRC				The SSRC identifying the channel receiving the message
 * @param[in]		zrtpPacketString		The packet received
 * @param[in]		zrtpPacketStringLength	Length of the packet in bytes
 *
 * @return 	0 on success, errorcode otherwise
 */
int bzrtp_processMessage(bzrtpContext_t *zrtpContext, uint32_t selfSSRC, uint8_t *zrtpPacketString, uint16_t zrtpPacketStringLength) {
473 474 475 476
	int retval;
	bzrtpPacket_t *zrtpPacket;
	bzrtpEvent_t event;

477 478 479 480 481 482 483
	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

484 485 486 487 488
	/* check the context is initialised (we may receive packets before initialisation is complete i.e. between channel initialisation and channel start) */
	if (zrtpChannelContext->stateMachine == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT; /* drop the message */
	}

johan's avatar
johan committed
489
	/* first check the packet */
490
	zrtpPacket = bzrtp_packetCheck(zrtpPacketString, zrtpPacketStringLength, zrtpChannelContext->peerSequenceNumber, &retval);
johan's avatar
johan committed
491 492 493 494 495 496
	if (retval != 0) {
		/*TODO: check the returned error code and do something or silent drop? */
		return retval;
	}

	/* TODO: Intercept error and ping zrtp packets */
johan's avatar
johan committed
497 498
	/* if we have a ping packet, just answer with a ping ACK and do not forward to the state machine */
	if (zrtpPacket->messageType == MSGTYPE_PING) {
499 500
		bzrtpPacket_t *pingAckPacket = NULL;

johan's avatar
johan committed
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
		bzrtp_packetParser(zrtpContext, zrtpChannelContext, zrtpPacketString, zrtpPacketStringLength, zrtpPacket);
		/* store ping packet in the channel context as packet creator will need it to create the pingACK */
		zrtpChannelContext->pingPacket = zrtpPacket;
		/* create the pingAck packet */
		pingAckPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_PINGACK, &retval);
		if (retval == 0) {
			retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, pingAckPacket, zrtpChannelContext->selfSequenceNumber);
			if (retval==0 && zrtpContext->zrtpCallbacks.bzrtp_sendData!=NULL) { /* send the packet */
				zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, pingAckPacket->packetString, pingAckPacket->messageLength+ZRTP_PACKET_OVERHEAD);
				zrtpChannelContext->selfSequenceNumber++;
			}
		}

		/* free packets and reset channel context storage */
		bzrtp_freeZrtpPacket(zrtpPacket);
		bzrtp_freeZrtpPacket(pingAckPacket);
		zrtpChannelContext->pingPacket = NULL;
518

johan's avatar
johan committed
519 520
		return retval;
	}
johan's avatar
johan committed
521

522 523 524 525
	/* build a packet event of it and send it to the state machine */
	event.eventType = BZRTP_EVENT_MESSAGE;
	event.bzrtpPacketString = zrtpPacketString;
	event.bzrtpPacketStringLength = zrtpPacketStringLength;
johan's avatar
johan committed
526
	event.bzrtpPacket = zrtpPacket;
527 528 529
	event.zrtpContext = zrtpContext;
	event.zrtpChannelContext = zrtpChannelContext;

johan's avatar
johan committed
530
	return zrtpChannelContext->stateMachine(event);
531 532
}

johan's avatar
johan committed
533 534 535 536 537 538 539 540
/*
 * @brief Called by user when the SAS has been verified
 * update the cache(if any) to set the previously verified flag
 *
 * @param[in/out]	zrtpContext				The ZRTP context we're dealing with
 */
void bzrtp_SASVerified(bzrtpContext_t *zrtpContext) {
	if (zrtpContext != NULL) {
541
		uint8_t pvsFlag = 1;
542
		const char *colNames[] = {"pvs"};
johan's avatar
johan committed
543 544
		uint8_t *colValues[] = {&pvsFlag};
		size_t colLength[] = {1};
545

546 547 548 549 550
		/* check if we must update the cache(delayed until sas verified in case of cache mismatch) */
		if (zrtpContext->cacheMismatchFlag  == 1) {
			zrtpContext->cacheMismatchFlag  = 0;
			bzrtp_updateCachedSecrets(zrtpContext, zrtpContext->channelContext[0]); /* channel[0] is the only one in DHM mode, so the only one able to have a cache mismatch */
		}
johan's avatar
johan committed
551
		bzrtp_cache_write(zrtpContext->zidCache, zrtpContext->zuid, "zrtp", colNames, colValues, colLength, 1);
johan's avatar
johan committed
552 553 554 555 556 557 558 559 560 561 562 563
	}
}

/*
 * @brief Called by user when the SAS has been set to unverified
 * update the cache(if any) to unset the previously verified flag
 *
 * @param[in/out]	zrtpContext				The ZRTP context we're dealing with
 */
void bzrtp_resetSASVerified(bzrtpContext_t *zrtpContext) {
	if (zrtpContext != NULL) {
		uint8_t pvsFlag = 0;
564
		const char *colNames[] = {"pvs"};
johan's avatar
johan committed
565 566 567
		uint8_t *colValues[] = {&pvsFlag};
		size_t colLength[] = {1};
		bzrtp_cache_write(zrtpContext->zidCache, zrtpContext->zuid, "zrtp", colNames, colValues, colLength, 1);
568 569 570
	}
}

571 572 573 574 575
/* FIXME: Temporary workaround for -Wcast-function-type. */
#if __GNUC__ >= 8
	_Pragma("GCC diagnostic push")
	_Pragma("GCC diagnostic ignored \"-Wcast-function-type\"")
#endif // if __GNUC__ >= 8
johan's avatar
johan committed
576

577
/*
johan's avatar
johan committed
578 579 580
 * @brief  Allow client to compute an exported according to RFC section 4.5.2
 *		Check the context is ready(we already have a master exported key and KDF context)
 * 		and run KDF(master exported key, "Label", KDF_Context, negotiated hash Length)
581
 *
johan's avatar
johan committed
582 583 584 585 586 587 588
 * @param[in]		zrtpContext		The ZRTP context we're dealing with
 * @param[in]		label			Label used in the KDF
 * @param[in]		labelLength		Length of previous buffer
 * @param[out]		derivedKey		Buffer to store the derived key
 * @param[in/out]	derivedKeyLength	Length of previous buffer(updated to fit actual length of data produced if too long)
 *
 * @return 0 on succes, error code otherwise
589
 */
johan's avatar
johan committed
590 591 592
int bzrtp_exportKey(bzrtpContext_t *zrtpContext, char *label, size_t labelLength, uint8_t *derivedKey, size_t *derivedKeyLength) {
	/* check we have s0 or exportedKey and KDFContext in channel[0] - export keys is available only on channel 0 completion - see RFC 4.5.2 */
	bzrtpChannelContext_t *zrtpChannelContext = zrtpContext->channelContext[0];
593

594
	if (zrtpContext->peerBzrtpVersion == 10000) { /* keep compatibility with older implementation of bzrtp */
johan's avatar
johan committed
595 596
		/* before version 1.1.0 (turned into an int MMmmpp -> 010100) exported keys wrongly derives from given label and s0 direclty instead of
		deriving one Exported Key from S0 and then as many as needed from the exported key as specified in the RFC section 4.5.2 */
597 598 599
		if (zrtpChannelContext->s0 == NULL || zrtpChannelContext->KDFContext == NULL) {
			return BZRTP_ERROR_INVALIDCONTEXT;
		}
johan's avatar
johan committed
600 601 602 603 604 605 606 607

		/* We derive a maximum of hashLength bytes */
		if (*derivedKeyLength > zrtpChannelContext->hashLength) {
			*derivedKeyLength = zrtpChannelContext->hashLength;
		}

		bzrtp_keyDerivationFunction(zrtpChannelContext->s0, zrtpChannelContext->hashLength, (uint8_t *)label, labelLength, zrtpChannelContext->KDFContext, zrtpChannelContext->KDFContextLength, *derivedKeyLength, (void (*)(uint8_t *, uint8_t,  uint8_t *, uint32_t,  uint8_t,  uint8_t *))zrtpChannelContext->hmacFunction, derivedKey);

608
	} else { /* peer either use version 1.1 of BZRTP or another library, just stick to the RFC to create the export key */
johan's avatar
johan committed
609 610 611 612 613 614 615 616 617
		if ((zrtpChannelContext->s0 == NULL && zrtpContext->exportedKey) || zrtpChannelContext->KDFContext == NULL) {
			return BZRTP_ERROR_INVALIDCONTEXT;
		}

		/* if we didn't already computed the master exported key, do it now */
		if (zrtpContext->exportedKey == NULL) {
			zrtpContext->exportedKeyLength = zrtpChannelContext->hashLength;
			zrtpContext->exportedKey = (uint8_t *)malloc(zrtpContext->exportedKeyLength*sizeof(uint8_t));
			bzrtp_keyDerivationFunction(zrtpChannelContext->s0, zrtpChannelContext->hashLength, (uint8_t *)"Exported key", 12, zrtpChannelContext->KDFContext, zrtpChannelContext->KDFContextLength, zrtpContext->exportedKeyLength, (void (*)(uint8_t *, uint8_t,  uint8_t *, uint32_t,  uint8_t,  uint8_t *))zrtpChannelContext->hmacFunction, zrtpContext->exportedKey);
618
		}
619

johan's avatar
johan committed
620 621 622
		/* We derive a maximum of hashLength bytes */
		if (*derivedKeyLength > zrtpChannelContext->hashLength) {
			*derivedKeyLength = zrtpChannelContext->hashLength;
623
		}
johan's avatar
johan committed
624 625 626

		bzrtp_keyDerivationFunction(zrtpContext->exportedKey, zrtpChannelContext->hashLength, (uint8_t *)label, labelLength, zrtpChannelContext->KDFContext, zrtpChannelContext->KDFContextLength, *derivedKeyLength, (void (*)(uint8_t *, uint8_t,  uint8_t *, uint32_t,  uint8_t,  uint8_t *))zrtpChannelContext->hmacFunction, derivedKey);

johan's avatar
johan committed
627
	}
johan's avatar
johan committed
628
	return 0;
johan's avatar
johan committed
629 630
}

631 632 633 634
#if __GNUC__ >= 8
	_Pragma("GCC diagnostic pop")
#endif // if __GNUC__ >= 8

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
/*
 * @brief Reset the retransmission timer of a given channel.
 * Packets will be sent again if appropriate:
 *  - when in responder role, zrtp engine only answer to packets sent by the initiator.
 *  - if we are still in discovery phase, Hello or Commit packets will be resent.
 *
 * @param[in/out]	zrtpContext				The ZRTP context we're dealing with
 * @param[in]		selfSSRC				The SSRC identifying the channel to reset
 *
 * return 0 on success, error code otherwise
 */

int bzrtp_resetRetransmissionTimer(bzrtpContext_t *zrtpContext, uint32_t selfSSRC) {
	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}
	/* reset timer only when not in secure mode yet and for initiator(engine start as initiator so if we call this function in discovery phase, it will reset the timer */
johan's avatar
johan committed
655
	if ((zrtpChannelContext->isSecure == 0) && (zrtpChannelContext->role == BZRTP_ROLE_INITIATOR)) {
656 657 658 659 660 661 662 663 664 665 666 667 668 669
		zrtpChannelContext->timer.status = BZRTP_TIMER_ON;
		zrtpChannelContext->timer.firingTime = 0; /* be sure it will trigger at next call to bzrtp_iterate*/
		zrtpChannelContext->timer.firingCount = -1; /* -1 to count the initial packet and then retransmit the regular number of packets */
		/* reset timerStep to the base value */
		if ((zrtpChannelContext->timer.timerStep % NON_HELLO_BASE_RETRANSMISSION_STEP) == 0) {
			zrtpChannelContext->timer.timerStep = NON_HELLO_BASE_RETRANSMISSION_STEP;
		} else {
			zrtpChannelContext->timer.timerStep = HELLO_BASE_RETRANSMISSION_STEP;
		}
	}

	return 0;
}

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
/**
 * @brief Get the supported crypto types
 *
 * @param[int]		zrtpContext				The ZRTP context we're dealing with
 * @param[in]		algoType				mapped to defines, must be in [ZRTP_HASH_TYPE, ZRTP_CIPHERBLOCK_TYPE, ZRTP_AUTHTAG_TYPE, ZRTP_KEYAGREEMENT_TYPE or ZRTP_SAS_TYPE]
 * @param[out]		supportedTypes			mapped to uint8_t value of the 4 char strings giving the supported types as string according to rfc section 5.1.2 to 5.1.6
 *
 * @return number of supported types, 0 on error
 */
uint8_t bzrtp_getSupportedCryptoTypes(bzrtpContext_t *zrtpContext, uint8_t algoType, uint8_t supportedTypes[7])
{
	if (zrtpContext==NULL) {
		return 0;
	}

	switch(algoType) {
		case ZRTP_HASH_TYPE:
			return copyCryptoTypes(supportedTypes, zrtpContext->supportedHash, zrtpContext->hc);
		case ZRTP_CIPHERBLOCK_TYPE:
			return copyCryptoTypes(supportedTypes, zrtpContext->supportedCipher, zrtpContext->cc);
		case ZRTP_AUTHTAG_TYPE:
			return copyCryptoTypes(supportedTypes, zrtpContext->supportedAuthTag, zrtpContext->ac);
		case ZRTP_KEYAGREEMENT_TYPE:
			return copyCryptoTypes(supportedTypes, zrtpContext->supportedKeyAgreement, zrtpContext->kc);
		case ZRTP_SAS_TYPE:
			return copyCryptoTypes(supportedTypes, zrtpContext->supportedSas, zrtpContext->sc);
		default:
			return 0;
	}
}

/**
 * @brief set the supported crypto types
 *
 * @param[int/out]	zrtpContext				The ZRTP context we're dealing with
 * @param[in]		algoType				mapped to defines, must be in [ZRTP_HASH_TYPE, ZRTP_CIPHERBLOCK_TYPE, ZRTP_AUTHTAG_TYPE, ZRTP_KEYAGREEMENT_TYPE or ZRTP_SAS_TYPE]
 * @param[in]		supportedTypes			mapped to uint8_t value of the 4 char strings giving the supported types as string according to rfc section 5.1.2 to 5.1.6
 * @param[in]		supportedTypesCount		number of supported crypto types
 */
void bzrtp_setSupportedCryptoTypes(bzrtpContext_t *zrtpContext, uint8_t algoType, uint8_t supportedTypes[7], uint8_t supportedTypesCount)
{
	uint8_t implementedTypes[7];
	uint8_t implementedTypesCount;

	if (zrtpContext==NULL) {
		return;
	}

718
	implementedTypesCount = bzrtpUtils_getAvailableCryptoTypes(algoType, implementedTypes);
719 720 721 722

	switch(algoType) {
		case ZRTP_HASH_TYPE:
			zrtpContext->hc = selectCommonAlgo(supportedTypes, supportedTypesCount, implementedTypes, implementedTypesCount, zrtpContext->supportedHash);
Ghislain MARY's avatar
Ghislain MARY committed
723
			bzrtp_addMandatoryCryptoTypesIfNeeded(algoType, zrtpContext->supportedHash, &zrtpContext->hc);
724 725 726
			break;
		case ZRTP_CIPHERBLOCK_TYPE:
			zrtpContext->cc = selectCommonAlgo(supportedTypes, supportedTypesCount, implementedTypes, implementedTypesCount, zrtpContext->supportedCipher);
Ghislain MARY's avatar
Ghislain MARY committed
727
			bzrtp_addMandatoryCryptoTypesIfNeeded(algoType, zrtpContext->supportedCipher, &zrtpContext->cc);
728 729 730
			break;
		case ZRTP_AUTHTAG_TYPE:
			zrtpContext->ac = selectCommonAlgo(supportedTypes, supportedTypesCount, implementedTypes, implementedTypesCount, zrtpContext->supportedAuthTag);
Ghislain MARY's avatar
Ghislain MARY committed
731
			bzrtp_addMandatoryCryptoTypesIfNeeded(algoType, zrtpContext->supportedAuthTag, &zrtpContext->ac);
732 733 734
			break;
		case ZRTP_KEYAGREEMENT_TYPE:
			zrtpContext->kc = selectCommonAlgo(supportedTypes, supportedTypesCount, implementedTypes, implementedTypesCount, zrtpContext->supportedKeyAgreement);
Ghislain MARY's avatar
Ghislain MARY committed
735
			bzrtp_addMandatoryCryptoTypesIfNeeded(algoType, zrtpContext->supportedKeyAgreement, &zrtpContext->kc);
736 737 738
			break;
		case ZRTP_SAS_TYPE:
			zrtpContext->sc = selectCommonAlgo(supportedTypes, supportedTypesCount, implementedTypes, implementedTypesCount, zrtpContext->supportedSas);
Ghislain MARY's avatar
Ghislain MARY committed
739
			bzrtp_addMandatoryCryptoTypesIfNeeded(algoType, zrtpContext->supportedSas, &zrtpContext->sc);
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
			break;
	}
}

/**
 * @brief Set the peer hello hash given by signaling to a ZRTP channel
 *
 * @param[in/out]	zrtpContext						The ZRTP context we're dealing with
 * @param[in]		selfSSRC						The SSRC identifying the channel
 * @param[out]		peerHelloHashHexString			A NULL terminated string containing the hexadecimal form of the hash received in signaling,
 * 													may contain ZRTP version as header.
 * @param[in]		peerHelloHashHexStringLength	Length of hash string (shall be at least 64 as the hash is a SHA256 so 32 bytes,
 * 													more if it contains the version header)
 *
 * @return 	0 on success, errorcode otherwise
 */
int bzrtp_setPeerHelloHash(bzrtpContext_t *zrtpContext, uint32_t selfSSRC, uint8_t *peerHelloHashHexString, size_t peerHelloHashHexStringLength) {
757
	size_t i=0;
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
	uint8_t *hexHashString = NULL;
	size_t hexHashStringLength = peerHelloHashHexStringLength;
	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/* parse the given peerHelloHash, it may formatted <version> <hexa string hash> or just <hexa string hash> */
	/* just ignore anything(we do not care about version number) before a ' ' if found */
	while (hexHashString==NULL && i<peerHelloHashHexStringLength) {
		if (strncmp((const char *)(peerHelloHashHexString+i), " ", 1) == 0) {
			hexHashString = peerHelloHashHexString+i+1;
			hexHashStringLength -= (i+1);
		}
		i++;
	}
	if (hexHashString == NULL) { /* there were no ' ' in the input string so it shall be the hex hash only without version number */
		hexHashString = peerHelloHashHexString;
	}

	/* allocate memory to store the hash, length will be hexa string length/2 - check it wasn't already allocated */
	if (zrtpChannelContext->peerHelloHash) {
		free(zrtpChannelContext->peerHelloHash);
	}
	zrtpChannelContext->peerHelloHash = (uint8_t *)malloc(hexHashStringLength/2*sizeof(uint8_t));

	/* convert to uint8 the hex string */
	bzrtp_strToUint8(zrtpChannelContext->peerHelloHash, hexHashString, hexHashStringLength);

	/* Do we already have the peer Hello packet, if yes, check it match the hash */
	if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] != NULL) {
		uint8_t computedPeerHelloHash[32];
		/* compute hash using implicit hash function: SHA256, skip packet header in the packetString buffer as the hash must be computed on message only */
jehan's avatar
jehan committed
793
		bctbx_sha256(zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH,
794 795 796 797 798 799
			zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength,
			32,
			computedPeerHelloHash);

		/* check they are the same */
		if (memcmp(computedPeerHelloHash, zrtpChannelContext->peerHelloHash, 32)!=0) {
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
			/* a session already started on this channel but with a wrong Hello we must reset and restart it */
			/* note: caller may decide to abort the ZRTP session */
			/* reset state Machine */
			zrtpChannelContext->stateMachine = NULL;

			/* set timer off */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

			/* destroy and free the key buffers */
			bzrtp_DestroyKey(zrtpChannelContext->s0, zrtpChannelContext->hashLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->KDFContext, zrtpChannelContext->KDFContextLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->mackeyi, zrtpChannelContext->hashLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->mackeyr, zrtpChannelContext->hashLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->zrtpkeyi, zrtpChannelContext->cipherKeyLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->zrtpkeyr, zrtpChannelContext->cipherKeyLength, zrtpContext->RNGContext);

			free(zrtpChannelContext->s0);
			free(zrtpChannelContext->KDFContext);
			free(zrtpChannelContext->mackeyi);
			free(zrtpChannelContext->mackeyr);
			free(zrtpChannelContext->zrtpkeyi);
			free(zrtpChannelContext->zrtpkeyr);

			zrtpChannelContext->s0=NULL;
			zrtpChannelContext->KDFContext=NULL;
			zrtpChannelContext->mackeyi=NULL;
			zrtpChannelContext->mackeyr=NULL;
			zrtpChannelContext->zrtpkeyi=NULL;
			zrtpChannelContext->zrtpkeyr=NULL;

			/* free the allocated buffers but not our self Hello packet */
			for (i=0; i<PACKET_STORAGE_CAPACITY; i++) {
				if (i!=HELLO_MESSAGE_STORE_ID) {
					bzrtp_freeZrtpPacket(zrtpChannelContext->selfPackets[i]);
					zrtpChannelContext->selfPackets[i] = NULL;
				}
				bzrtp_freeZrtpPacket(zrtpChannelContext->peerPackets[i]);
				zrtpChannelContext->peerPackets[i] = NULL;
			}

			/* destroy and free the srtp and sas struture */
			bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.selfSrtpKey, zrtpChannelContext->srtpSecrets.selfSrtpKeyLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.selfSrtpSalt, zrtpChannelContext->srtpSecrets.selfSrtpSaltLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.peerSrtpKey, zrtpChannelContext->srtpSecrets.peerSrtpKeyLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.peerSrtpSalt, zrtpChannelContext->srtpSecrets.peerSrtpSaltLength, zrtpContext->RNGContext);
			bzrtp_DestroyKey((uint8_t *)zrtpChannelContext->srtpSecrets.sas, zrtpChannelContext->srtpSecrets.sasLength, zrtpContext->RNGContext);

			free(zrtpChannelContext->srtpSecrets.selfSrtpKey);
			free(zrtpChannelContext->srtpSecrets.selfSrtpSalt);
			free(zrtpChannelContext->srtpSecrets.peerSrtpKey);
			free(zrtpChannelContext->srtpSecrets.peerSrtpSalt);
			free(zrtpChannelContext->srtpSecrets.sas);

			/* re-initialise srtpSecrets structure */
			zrtpChannelContext->srtpSecrets.selfSrtpKey = NULL;
			zrtpChannelContext->srtpSecrets.selfSrtpSalt = NULL;
			zrtpChannelContext->srtpSecrets.peerSrtpKey = NULL;
			zrtpChannelContext->srtpSecrets.peerSrtpSalt = NULL;
			zrtpChannelContext->srtpSecrets.selfSrtpKeyLength = 0;
			zrtpChannelContext->srtpSecrets.selfSrtpSaltLength = 0;
			zrtpChannelContext->srtpSecrets.peerSrtpKeyLength = 0;
			zrtpChannelContext->srtpSecrets.peerSrtpSaltLength = 0;
			zrtpChannelContext->srtpSecrets.cipherAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->srtpSecrets.cipherKeyLength = 0;
			zrtpChannelContext->srtpSecrets.authTagAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->srtpSecrets.sas = NULL;
			zrtpChannelContext->srtpSecrets.sasLength = 0;
867 868 869 870
			zrtpChannelContext->srtpSecrets.hashAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->srtpSecrets.keyAgreementAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->srtpSecrets.sasAlgo = ZRTP_UNSET_ALGO;

871 872 873 874 875 876 877 878

			/* reset choosen algo and their functions */
			zrtpChannelContext->hashAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->cipherAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->authTagAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->keyAgreementAlgo = ZRTP_UNSET_ALGO;
			zrtpChannelContext->sasAlgo = ZRTP_UNSET_ALGO;

Ghislain MARY's avatar
Ghislain MARY committed
879
			bzrtp_updateCryptoFunctionPointers(zrtpChannelContext);
880 881 882 883

			/* restart channel */
			bzrtp_startChannelEngine(zrtpContext, selfSSRC);

884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
			return BZRTP_ERROR_HELLOHASH_MISMATCH;
		}
	}
	return 0;
}

/**
 * @brief Get the self hello hash from ZRTP channel
 *
 * @param[in/out]	zrtpContext			The ZRTP context we're dealing with
 * @param[in]		selfSSRC			The SSRC identifying the channel
 * @param[out]		output				A NULL terminated string containing the hexadecimal form of the hash received in signaling,
 * 										contain ZRTP version as header. Buffer must be allocated by caller.
 * @param[in]		outputLength		Length of output buffer, shall be at least 70 : 5 chars for version, 64 for the hash itself, SHA256), NULL termination
 *
 * @return 	0 on success, errorcode otherwise
 */
int bzrtp_getSelfHelloHash(bzrtpContext_t *zrtpContext, uint32_t selfSSRC, uint8_t *output, size_t outputLength) {
	uint8_t helloHash[32];
	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/* check we have the Hello packet in context */
	if (zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID] == NULL) {
		return BZRTP_ERROR_CONTEXTNOTREADY;
	}

	/* check output length : version length +' '+64 hex hash + null termination */
	if (outputLength < strlen(ZRTP_VERSION)+1+64+1) {
		return BZRTP_ERROR_OUTPUTBUFFER_LENGTH;
	}

	/* compute hash using implicit hash function: SHA256, skip packet header in the packetString buffer as the hash must be computed on message only */
jehan's avatar
jehan committed
921
	bctbx_sha256(zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH,
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
			zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength,
			32,
			helloHash);

	/* add version header */
	strcpy((char *)output, ZRTP_VERSION);
	output[strlen(ZRTP_VERSION)]=' ';

	/* convert hash to hex string and set it in the output buffer */
	bzrtp_int8ToStr(output+strlen(ZRTP_VERSION)+1, helloHash, 32);

	/* add NULL termination */
	output[strlen(ZRTP_VERSION)+1+64]='\0';

	return 0;
}

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
/**
 * @brief Set Auxiliary Secret for this channel(shall be used only on primary audio channel)
 *   The given auxSecret is appended to any aux secret found in ZIDcache
 *   This function must be called before reception of peerHello packet
 *
 * @param[in]		zrtpContext	The ZRTP context we're dealing with
 * @param[in]		auxSecret	A buffer holding the auxiliary shared secret to use (see RFC 6189 section 4.3)
 * @param[in]		auxSecretLength	lenght of the previous buffer
 *
 * @return 0 on success, error code otherwise
 */
BZRTP_EXPORT int bzrtp_setAuxiliarySharedSecret(bzrtpContext_t *zrtpContext, const uint8_t *auxSecret, size_t auxSecretLength) {
	if (zrtpContext == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	if (zrtpContext->channelContext[0] && zrtpContext->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] != NULL) {
		return BZRTP_ERROR_CONTEXTNOTREADY;
	}

	/* allocate memory to store the secret - check it wasn't already allocated */
	if (zrtpContext->transientAuxSecret) {
		free(zrtpContext->transientAuxSecret);
	}
	zrtpContext->transientAuxSecret = (uint8_t *)malloc(auxSecretLength*sizeof(uint8_t));

	/* copy the aux secret and length */
	memcpy(zrtpContext->transientAuxSecret, auxSecret, auxSecretLength);
	zrtpContext->transientAuxSecretLength = auxSecretLength;

	return 0;
}
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003

/**
 * @brief Get the channel status
 *
 * @param[in]		zrtpContext			The ZRTP context we're dealing with
 * @param[in]		selfSSRC			The SSRC identifying the channel
 *
 * @return	BZRTP_CHANNEL_NOTFOUND 		no channel matching this SSRC doesn't exists in the zrtp context
 * 			BZRTP_CHANNEL_INITIALISED	channel initialised but not started
 * 			BZRTP_CHANNEL_ONGOING		ZRTP key exchange in ongoing
 *			BZRTP_CHANNEL_SECURE		Channel is secure
 *			BZRTP_CHANNEL_ERROR			An error occured on this channel
 */
int bzrtp_getChannelStatus(bzrtpContext_t *zrtpContext, uint32_t selfSSRC) {

	/* get channel context */
	bzrtpChannelContext_t *zrtpChannelContext = getChannelContext(zrtpContext, selfSSRC);

	if (zrtpChannelContext == NULL) {
		return BZRTP_CHANNEL_NOTFOUND;
	}

	if (zrtpChannelContext->stateMachine == NULL) {
		return BZRTP_CHANNEL_INITIALISED;
	}

	if (zrtpChannelContext->isSecure == 1) {
		return BZRTP_CHANNEL_SECURE;
	}

	return BZRTP_CHANNEL_ONGOING;
}

johan's avatar
johan committed
1004
/* Local functions implementation */
1005 1006 1007 1008 1009 1010 1011 1012 1013

/**
 * @brief Look in the given ZRTP context for a channel referenced with given SSRC
 *
 * @param[in]	zrtpContext	The zrtp context which shall contain the channel context we are looking for
 * @param[in]	selfSSRC	The SSRC identifying the channel context
 *
 * @return 		a pointer to the channel context, NULL if the context is invalid or channel not found
 */
1014
static bzrtpChannelContext_t *getChannelContext(bzrtpContext_t *zrtpContext, uint32_t selfSSRC) {
1015 1016
	int i;

1017 1018 1019
	if (zrtpContext==NULL) {
		return NULL;
	}
1020

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
	for (i=0; i<ZRTP_MAX_CHANNEL_NUMBER; i++) {
		if (zrtpContext->channelContext[i]!=NULL) {
			if (zrtpContext->channelContext[i]->selfSSRC == selfSSRC) {
				return zrtpContext->channelContext[i];
			}
		}
	}

	return NULL; /* found no channel with this SSRC */
}
johan's avatar
johan committed
1031
/**
1032
 * @brief Initialise the context of a channel and create and store the Hello packet
johan's avatar
johan committed
1033
 * Initialise some vectors
1034
 *
johan's avatar
johan committed
1035 1036 1037
 * @param[in] 		zrtpContext			The zrtpContext hosting this channel, needed to acces the RNG
 * @param[out]		zrtpChanneContext	The channel context to be initialised
 * @param[in]		selfSSRC			The SSRC allocated to this channel
1038
 * @param[in]		isMain				This channel is channel 0 or an additional channel
johan's avatar
johan committed
1039 1040 1041
 *
 * @return	0 on success, error code otherwise
 */
1042
static int bzrtp_initChannelContext(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, uint32_t selfSSRC, uint8_t isMain) {
johan's avatar
johan committed
1043
	int i;
1044 1045 1046
	int retval;
	bzrtpPacket_t *helloPacket;

johan's avatar
johan committed
1047 1048 1049 1050
	if (zrtpChannelContext == NULL) {
		return BZRTP_ERROR_INVALIDCHANNELCONTEXT;
	}

1051 1052
	zrtpChannelContext->clientData = NULL;

johan's avatar
johan committed
1053 1054 1055
	/* the state machine is not started at the creation of the channel but on explicit call to the start function */
	zrtpChannelContext->stateMachine = NULL;

1056 1057
	/* timer is off */
	zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
1058
	zrtpChannelContext->timer.timerStep = HELLO_BASE_RETRANSMISSION_STEP; /* we must initialise the timeStep just in case the resettimer function is called between init and start */
1059

johan's avatar
johan committed
1060 1061
	zrtpChannelContext->selfSSRC = selfSSRC;

1062 1063
	/* flags */
	zrtpChannelContext->isSecure = 0;
1064
	zrtpChannelContext->isMainChannel = isMain;
1065

johan's avatar
johan committed
1066
	/* initialise as initiator, switch to responder later if needed */
johan's avatar
johan committed
1067
	zrtpChannelContext->role = BZRTP_ROLE_INITIATOR;
johan's avatar
johan committed
1068 1069

	/* create H0 (32 bytes random) and derive using implicit Hash(SHA256) H1,H2,H3 */
jehan's avatar
jehan committed
1070 1071 1072 1073
	bctbx_rng_get(zrtpContext->RNGContext, zrtpChannelContext->selfH[0], 32);
	bctbx_sha256(zrtpChannelContext->selfH[0], 32, 32, zrtpChannelContext->selfH[1]);
	bctbx_sha256(zrtpChannelContext->selfH[1], 32, 32, zrtpChannelContext->selfH[2]);
	bctbx_sha256(zrtpChannelContext->selfH[2], 32, 32, zrtpChannelContext->selfH[3]);
johan's avatar
johan committed
1074 1075 1076 1077 1078 1079

	/* initialisation of packet storage */
	for (i=0; i<PACKET_STORAGE_CAPACITY; i++) {
		zrtpChannelContext->selfPackets[i] = NULL;
		zrtpChannelContext->peerPackets[i] = NULL;
	}
1080
	zrtpChannelContext->peerHelloHash = NULL;
johan's avatar
johan committed
1081 1082

	/* initialise the self Sequence number to a random and peer to 0 */
jehan's avatar
jehan committed
1083
	bctbx_rng_get(zrtpContext->RNGContext, (uint8_t *)&(zrtpChannelContext->selfSequenceNumber), 2);
johan's avatar
johan committed
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	zrtpChannelContext->selfSequenceNumber &= 0x0FFF; /* first 4 bits to zero in order to avoid reaching FFFF and turning back to 0 */
	zrtpChannelContext->selfSequenceNumber++; /* be sure it is not initialised to 0 */
	zrtpChannelContext->peerSequenceNumber = 0;

	/* reset choosen algo and their functions */
	zrtpChannelContext->hashAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->cipherAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->authTagAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->keyAgreementAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->sasAlgo = ZRTP_UNSET_ALGO;

Ghislain MARY's avatar
Ghislain MARY committed
1095
	bzrtp_updateCryptoFunctionPointers(zrtpChannelContext);
johan's avatar
johan committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

	/* initialise key buffers */
	zrtpChannelContext->s0 = NULL;
	zrtpChannelContext->KDFContext = NULL;
	zrtpChannelContext->KDFContextLength = 0;
	zrtpChannelContext->mackeyi = NULL;
	zrtpChannelContext->mackeyr = NULL;
	zrtpChannelContext->zrtpkeyi = NULL;
	zrtpChannelContext->zrtpkeyr = NULL;

johan's avatar
johan committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
	/* initialise srtpSecrets structure */
	zrtpChannelContext->srtpSecrets.selfSrtpKey = NULL;
	zrtpChannelContext->srtpSecrets.selfSrtpSalt = NULL;
	zrtpChannelContext->srtpSecrets.peerSrtpKey = NULL;
	zrtpChannelContext->srtpSecrets.peerSrtpSalt = NULL;
	zrtpChannelContext->srtpSecrets.selfSrtpKeyLength = 0;
	zrtpChannelContext->srtpSecrets.selfSrtpSaltLength = 0;
	zrtpChannelContext->srtpSecrets.peerSrtpKeyLength = 0;
	zrtpChannelContext->srtpSecrets.peerSrtpSaltLength = 0;
	zrtpChannelContext->srtpSecrets.cipherAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->srtpSecrets.cipherKeyLength = 0;
	zrtpChannelContext->srtpSecrets.authTagAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->srtpSecrets.sas = NULL;
1119
	zrtpChannelContext->srtpSecrets.sasLength = 0;
1120 1121 1122
	zrtpChannelContext->srtpSecrets.hashAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->srtpSecrets.keyAgreementAlgo = ZRTP_UNSET_ALGO;
	zrtpChannelContext->srtpSecrets.sasAlgo = ZRTP_UNSET_ALGO;
johan's avatar
johan committed
1123
	zrtpChannelContext->srtpSecrets.cacheMismatch = 0;
1124
	zrtpChannelContext->srtpSecrets.auxSecretMismatch = 1; /* default is mismatch, explicitely set it to zero if we have a match */
johan's avatar
johan committed
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
	/* create the Hello packet and store it */
	helloPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_HELLO, &retval);
	if (retval != 0) {
		return retval;
	}
	/* build the packet string and store the packet */
	if (bzrtp_packetBuild(zrtpContext, zrtpChannelContext, helloPacket, zrtpChannelContext->selfSequenceNumber) ==0) {
		zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID] = helloPacket;
	} else {
		bzrtp_freeZrtpPacket(helloPacket);
		return retval;
	}

johan's avatar
johan committed
1139 1140 1141 1142 1143 1144
	return 0;
}

/**
 * @brief Destroy the context of a channel
 * Free allocated buffers, destroy keys
1145
 *
johan's avatar
johan committed
1146 1147
 * @param[in] 		zrtpContext			The zrtpContext hosting this channel, needed to acces the RNG
 * @param[in] 		zrtpChannelContext	The channel context to be destroyed
johan's avatar
johan committed
1148
 */
1149
static void bzrtp_destroyChannelContext(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext) {
johan's avatar
johan committed
1150 1151 1152 1153 1154 1155 1156
	int i;

	/* check there is something to be freed */
	if (zrtpChannelContext == NULL) {
		return;
	}

1157 1158 1159 1160 1161 1162
	/* reset state Machine */
	zrtpChannelContext->stateMachine = NULL;

	/* set timer off */
	zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

johan's avatar
johan committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
	/* destroy and free the key buffers */
	bzrtp_DestroyKey(zrtpChannelContext->s0, zrtpChannelContext->hashLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->KDFContext, zrtpChannelContext->KDFContextLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->mackeyi, zrtpChannelContext->hashLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->mackeyr, zrtpChannelContext->hashLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->zrtpkeyi, zrtpChannelContext->cipherKeyLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->zrtpkeyr, zrtpChannelContext->cipherKeyLength, zrtpContext->RNGContext);

	free(zrtpChannelContext->s0);
	free(zrtpChannelContext->KDFContext);
	free(zrtpChannelContext->mackeyi);
	free(zrtpChannelContext->mackeyr);
	free(zrtpChannelContext->zrtpkeyi);
	free(zrtpChannelContext->zrtpkeyr);

	zrtpChannelContext->s0=NULL;
	zrtpChannelContext->KDFContext=NULL;
	zrtpChannelContext->mackeyi=NULL;
	zrtpChannelContext->mackeyr=NULL;
	zrtpChannelContext->zrtpkeyi=NULL;
	zrtpChannelContext->zrtpkeyr=NULL;

	/* free the allocated buffers */
	for (i=0; i<PACKET_STORAGE_CAPACITY; i++) {
1187 1188
		bzrtp_freeZrtpPacket(zrtpChannelContext->selfPackets[i]);
		bzrtp_freeZrtpPacket(zrtpChannelContext->peerPackets[i]);
johan's avatar
johan committed
1189 1190 1191
		zrtpChannelContext->selfPackets[i] = NULL;
		zrtpChannelContext->peerPackets[i] = NULL;
	}
1192 1193
	free(zrtpChannelContext->peerHelloHash);
	zrtpChannelContext->peerHelloHash = NULL;
johan's avatar
johan committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206

	/* destroy and free the srtp and sas struture */
	bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.selfSrtpKey, zrtpChannelContext->srtpSecrets.selfSrtpKeyLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.selfSrtpSalt, zrtpChannelContext->srtpSecrets.selfSrtpSaltLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.peerSrtpKey, zrtpChannelContext->srtpSecrets.peerSrtpKeyLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey(zrtpChannelContext->srtpSecrets.peerSrtpSalt, zrtpChannelContext->srtpSecrets.peerSrtpSaltLength, zrtpContext->RNGContext);
	bzrtp_DestroyKey((uint8_t *)zrtpChannelContext->srtpSecrets.sas, zrtpChannelContext->srtpSecrets.sasLength, zrtpContext->RNGContext);

	free(zrtpChannelContext->srtpSecrets.selfSrtpKey);
	free(zrtpChannelContext->srtpSecrets.selfSrtpSalt);
	free(zrtpChannelContext->srtpSecrets.peerSrtpKey);
	free(zrtpChannelContext->srtpSecrets.peerSrtpSalt);
	free(zrtpChannelContext->srtpSecrets.sas);
1207 1208 1209

	/* free the channel context */
	free(zrtpChannelContext);
johan's avatar
johan committed
1210
}
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

static uint8_t copyCryptoTypes(uint8_t destination[7], uint8_t source[7], uint8_t size)
{
	int i;

	for (i=0; i<size; i++) {
		destination[i] = source[i];
	}
	return size;
}