stateMachine.c 109 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/**
 @file stateMachine.c

 @brief The state machine implementing the ZRTP protocol
 each state is defined as u function pointer and on arrival of a new event
 after sanity checks, the state function is called giving the event as parameter
 
 @author Johan Pascal

 @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France
 
 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.
 
 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.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
24
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 26 27
 */

#include <stdlib.h>
johan's avatar
johan committed
28
#include <string.h>
29 30 31 32
#include "typedef.h"
#include "packetParser.h"
#include "cryptoUtils.h"
#include "zidCache.h"
33
#include <bctoolbox/crypto.h>
34 35 36 37 38
#include "stateMachine.h"


/* Local functions prototypes */
int bzrtp_turnIntoResponder(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, bzrtpPacket_t *zrtpPacket, bzrtpCommitMessage_t *commitMessage);
johan's avatar
johan committed
39
int bzrtp_responseToHelloMessage(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, bzrtpPacket_t *zrtpPacket);
40 41 42
int bzrtp_computeS0DHMMode(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext);
int bzrtp_computeS0MultiStreamMode(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext); 
int bzrtp_deriveKeysFromS0(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext);
johan's avatar
johan committed
43
int bzrtp_deriveSrtpKeysFromS0(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext); 
johan's avatar
johan committed
44
int bzrtp_updateCachedSecrets(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext);
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

/*
 * @brief This is the initial state
 * On first call, we will create the Hello message and start sending it until we receive an helloACK or a hello message from peer
 *
 * Arrives from :
 * 	- This is the initial state
 * Goes to:
 * 	- state_discovery_waitingForHello upon HelloACK reception
 * 	- state_discovery_waitingForHelloAck upon Hello reception
 * Send :
 * 	- Hello until timer's end or transition
 */
int state_discovery_init(bzrtpEvent_t event) {
	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;
62
	int retval;
63 64

	/*** Manage the first call to this function ***/
65 66 67 68 69 70 71 72 73 74
	/* We are supposed to send Hello packet, it shall be already present int the selfPackets(created at channel init) */
	if (event.eventType == BZRTP_EVENT_INIT) {
		if (zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID] == NULL) {
			/* We shall never go through this one because Hello packet shall be created at channel init */
			int retval;
			/* create the Hello packet */
			bzrtpPacket_t *helloPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_HELLO, &retval);
			if (retval != 0) {
				return retval;
			}
75

76 77 78 79 80 81 82 83
			/* build the packet string */
			if (bzrtp_packetBuild(zrtpContext, zrtpChannelContext, helloPacket, zrtpChannelContext->selfSequenceNumber) ==0) {
				zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID] = helloPacket;
			} else {
				bzrtp_freeZrtpPacket(helloPacket);
				return retval;
			}
			/* TODO: Shall add a warning trace here */
84 85 86 87 88 89 90 91 92 93 94 95 96 97
		}

		/* it is the first call to this function, so we must also set the timer for retransmissions */
		zrtpChannelContext->timer.status = BZRTP_TIMER_ON;
		zrtpChannelContext->timer.firingTime = 0; /* we must send a first hello message as soon as possible, to do it at first timer tick, we can't do it now because still in initialisation phase and the RTP session may not be ready to send a message */
		zrtpChannelContext->timer.firingCount = 0;
		zrtpChannelContext->timer.timerStep = HELLO_BASE_RETRANSMISSION_STEP;

		zrtpChannelContext->selfSequenceNumber++;
		return 0;
	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
johan's avatar
johan committed
98
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
		
		/* now check the type of packet received, we're expecting either Hello or HelloACK */
		if ((zrtpPacket->messageType != MSGTYPE_HELLO) && (zrtpPacket->messageType != MSGTYPE_HELLOACK)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* parse the packet */
		retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
		if (retval != 0) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return retval;
		}
		/* packet is valid, set the sequence Number in channel context */
		zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

		/* if we have an Hello packet, we must use it to determine which algo we will agree on */
		if (zrtpPacket->messageType == MSGTYPE_HELLO) {
johan's avatar
johan committed
117
			retval = bzrtp_responseToHelloMessage(zrtpContext, zrtpChannelContext, zrtpPacket);
118 119 120 121
			if (retval != 0) {
				return retval;
			}

johan's avatar
johan committed
122 123 124 125 126
			/* reset the sending Hello timer as peer may have started slowly and lost all our Hello packets */
			zrtpChannelContext->timer.status = BZRTP_TIMER_ON;
			zrtpChannelContext->timer.firingTime = 0;
			zrtpChannelContext->timer.firingCount = 0;
			zrtpChannelContext->timer.timerStep = HELLO_BASE_RETRANSMISSION_STEP;
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
			
			/* set next state (do not call it as we will just be waiting for a HelloACK packet from peer, nothing to do) */
			zrtpChannelContext->stateMachine = state_discovery_waitingForHelloAck;
		}

		/* if we have a HelloACK packet, stop the timer and  set next state to state_discovery_waitingForHello */
		if (zrtpPacket->messageType == MSGTYPE_HELLOACK) {
			/* stop the timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

			/* Hello ACK packet is not stored, free it */
			bzrtp_freeZrtpPacket(zrtpPacket);

			/* set next state (do not call it as we will just be waiting for a Hello packet from peer, nothing to do) */
			zrtpChannelContext->stateMachine = state_discovery_waitingForHello;

			return 0;
		}


	}

	/*** Manage timer event ***/
	if (event.eventType == BZRTP_EVENT_TIMER) {

		/* adjust timer for next time : check we didn't reach the max retransmissions adjust the step(double it until reaching the cap) */
153 154
		if (zrtpChannelContext->timer.firingCount<=HELLO_MAX_RETRANSMISSION_NUMBER) {
			if (2*zrtpChannelContext->timer.timerStep<=HELLO_CAP_RETRANSMISSION_STEP) {
155 156 157 158 159 160 161 162 163 164
				zrtpChannelContext->timer.timerStep *= 2;
			}
			zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + zrtpChannelContext->timer.timerStep;
		} else { /* we have done enough retransmissions, stop it */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
		}

		/* We must resend a Hello packet */
		retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
		if (retval == 0) {
165 166 167 168
			if (zrtpContext->zrtpCallbacks.bzrtp_sendData!=NULL) {
				zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
				zrtpChannelContext->selfSequenceNumber++;
			}
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
		} else {
			return retval;
		}

	}

	return 0;
}

/*
 * @brief Arrives in this state coming from init upon reception on Hello ACK, we are now waiting for the Hello packet from peer
 *
 * Arrives from : 
 *	- state_discovery_init upon HelloACK reception
 * Goes to:
 * 	- state_keyAgreement_sendingCommit upon Hello reception
 * Send :
 * 	- HelloACK on Hello reception
 *
 */
int state_discovery_waitingForHello(bzrtpEvent_t event)  {
	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;

	/*** Manage the first call to this function ***/
	/* no init event for this state */

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
199
		bzrtpEvent_t initEvent;
200 201
		int retval;

johan's avatar
johan committed
202
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
		
		/* now check the type of packet received, we're expecting either Hello, HelloACK may arrive but will be discarded as useless now */
		if (zrtpPacket->messageType != MSGTYPE_HELLO) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* parse the packet */
		retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
		if (retval != 0) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return retval;
		}
		/* packet is valid, set the sequence Number in channel context */
		zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

johan's avatar
johan committed
219
		retval = bzrtp_responseToHelloMessage(zrtpContext, zrtpChannelContext, zrtpPacket);
220 221 222 223 224 225 226 227 228 229 230
		if (retval != 0) {
			return retval;
		}
		
		/* set next state state_keyAgreement_sendingCommit */
		zrtpChannelContext->stateMachine = state_keyAgreement_sendingCommit;

		/* create the init event for next state */
		initEvent.eventType = BZRTP_EVENT_INIT;
		initEvent.bzrtpPacketString = NULL;
		initEvent.bzrtpPacketStringLength = 0;
231
		initEvent.bzrtpPacket = NULL;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
		initEvent.zrtpContext = zrtpContext;
		initEvent.zrtpChannelContext = zrtpChannelContext;

		/* call the next state */
		return zrtpChannelContext->stateMachine(initEvent);
	}

	/*** Manage timer event ***/
	/* no timer event for this state*/
	return 0;
}


/*
 * @brief We are now waiting for the HelloACK packet from peer or a Commit packet 
 *
 * Arrives from :
 * 	- state_discovery_init upon Hello reception
 * Goes to:
 * 	- state_keyAgreement_sendingCommit upon HelloACK reception
 * 	- state_keyAgreement_responderSendingDHPart1 upon Commit reception in DHM mode
 * 	- state_confirmation_responderSendingConfirm1 upon Commit reception in non DHM mode 
 * Send :
 * 	- Hello until timer's end or transition
 * 	- HelloACK on Hello reception
 *
 */
int state_discovery_waitingForHelloAck(bzrtpEvent_t event) {
	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;

	int retval;
	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
johan's avatar
johan committed
267
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
268 269 270 271 272 273 274 275 276 277
		
		/* we can receive either a Hello, HelloACK or Commit packets, others will be ignored */
		if ((zrtpPacket->messageType != MSGTYPE_HELLO) && (zrtpPacket->messageType != MSGTYPE_HELLOACK) && (zrtpPacket->messageType != MSGTYPE_COMMIT)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* We do not need to parse the packet if it is an Hello one as it shall be the duplicate of one we received earlier */
		/* we must check it is the same we initially received, and send a HelloACK */
		if (zrtpPacket->messageType == MSGTYPE_HELLO) {
278 279
			bzrtpPacket_t *helloACKPacket;

280 281 282 283
			if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}
284
			if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength) != 0) {
285 286 287 288 289 290 291
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}

			/* incoming packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

292 293 294
			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

295
			/* build and send the HelloACK packet */
296
			helloACKPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_HELLOACK, &retval);
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
			if (retval != 0) {
				return retval; /* no need to free the Hello message as it is attached to the context, it will be freed when destroying it */
			}
			retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, helloACKPacket, zrtpChannelContext->selfSequenceNumber);
			if (retval != 0) {
				bzrtp_freeZrtpPacket(helloACKPacket);
				return retval;
			} else {
				/* send the message */
				zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, helloACKPacket->packetString, helloACKPacket->messageLength+ZRTP_PACKET_OVERHEAD);
				zrtpChannelContext->selfSequenceNumber++;
				/* sent HelloACK is not stored, free it */
				bzrtp_freeZrtpPacket(helloACKPacket);
			}

			return 0;
		}

		/* parse the packet wich is either HelloACK or Commit */
		retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
		if (retval != 0) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return retval;
		}

		/* packet is valid, set the sequence Number in channel context */
		zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

		
		/* if we have an HelloACK packet, transit to state_keyAgreement_sendingCommit and execute it with an init event */
		if (zrtpPacket->messageType == MSGTYPE_HELLOACK) {
328 329
			bzrtpEvent_t initEvent;

330 331 332 333 334 335 336 337 338 339 340 341 342
			/* stop the timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

			/* set next state to  state_keyAgreement_sendingCommit */
			zrtpChannelContext->stateMachine = state_keyAgreement_sendingCommit;

			/* the HelloACK packet is not stored in context, free it */
			bzrtp_freeZrtpPacket(zrtpPacket);

			/* create the init event for next state and call the next state */
			initEvent.eventType = BZRTP_EVENT_INIT;
			initEvent.bzrtpPacketString = NULL;
			initEvent.bzrtpPacketStringLength = 0;
343
			initEvent.bzrtpPacket = NULL;
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
			initEvent.zrtpContext = zrtpContext;
			initEvent.zrtpChannelContext = zrtpChannelContext;
			return zrtpChannelContext->stateMachine(initEvent);
		}

		/* if we have a Commit packet we shall turn into responder role
		 * then transit to state_keyAgreement_responderSendingDHPart1 or state_confirmation_responderSendingConfirm1 depending on which mode (Multi/PreShared or DHM) we are using and execute it with an init event */
		if (zrtpPacket->messageType == MSGTYPE_COMMIT) {
			bzrtpCommitMessage_t *commitMessage = (bzrtpCommitMessage_t *)zrtpPacket->messageData;

			/* this will stop the timer, update the context channel and run the next state according to current mode */
			return bzrtp_turnIntoResponder(zrtpContext, zrtpChannelContext, zrtpPacket, commitMessage);
		}


	}

	/*** Manage timer event ***/
	if (event.eventType == BZRTP_EVENT_TIMER) {

		/* adjust timer for next time : check we didn't reach the max retransmissions adjust the step(double it until reaching the cap) */
365 366
		if (zrtpChannelContext->timer.firingCount<=HELLO_MAX_RETRANSMISSION_NUMBER) {
			if (2*zrtpChannelContext->timer.timerStep<=HELLO_CAP_RETRANSMISSION_STEP) {
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
				zrtpChannelContext->timer.timerStep *= 2;
			}
			zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + zrtpChannelContext->timer.timerStep;
		} else { /* we have done enough retransmissions, stop it */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
		}

		/* We must resend a Hello packet */
		retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
		if (retval == 0) {
		zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		zrtpChannelContext->selfSequenceNumber++;
		} else {
			return retval;
		}

	}

	return 0;
}

/*
 * @brief For any kind of key agreement (DHM, Mult, PreShared), we keep sending commit.
 *
 * Arrives from : 
 * 	- state_discovery_waitingForHello upon Hello received
 * 	- state_discovery_waitingForHelloAck upon HelloACK received
 * Goes to:
 * 	- state_keyAgreement_initiatorSendingDHPart2 upon DHPart1 reception in DHM mode
 * 	- state_confirmation_initiatorSendingConfirm2 upon Confirm1 reception in non DHM mode
 * 	- state_keyAgreement_responderSendingDHPart1 upon Commit reception in DHM mode and commit contention gives us the responder role
 * 	- state_confirmation_responderSendingConfirm1 upon Commit reception in non DHM mode and commit contention gives us the responder role
 * Send :
 * 	- Commit until timer's end or transition
 * 	- HelloACK on Hello reception
 *
 */
int state_keyAgreement_sendingCommit(bzrtpEvent_t event) {

	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;
409
	int retval;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

	/*** Manage the first call to this function ***/
	/* We are supposed to send commit packet, check if we have one in the channel Context, the event type shall be INIT in this case */
	if ((event.eventType == BZRTP_EVENT_INIT)  && (zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID] == NULL)) {
		int retval;
		/* create the commit packet */
		bzrtpPacket_t *commitPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_COMMIT, &retval);
		if (retval != 0) {
			return retval;
		}

		/* build the packet string */
		if (bzrtp_packetBuild(zrtpContext, zrtpChannelContext, commitPacket, zrtpChannelContext->selfSequenceNumber) ==0) {
			zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID] = commitPacket;
		} else {
			bzrtp_freeZrtpPacket(commitPacket);
			return retval;
		}

		/* it is the first call to this state function, so we must also set the timer for retransmissions */
		zrtpChannelContext->timer.status = BZRTP_TIMER_ON;
		zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + NON_HELLO_BASE_RETRANSMISSION_STEP;
		zrtpChannelContext->timer.firingCount = 0;
		zrtpChannelContext->timer.timerStep = NON_HELLO_BASE_RETRANSMISSION_STEP;

		/* now send the first Commit message */
		zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		zrtpChannelContext->selfSequenceNumber++;
		return 0;
	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
443
		bzrtpEvent_t initEvent;
johan's avatar
johan committed
444
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
445 446 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 473 474 475 476 477 478 479 480 481 482 483
		
		/* now check the type of packet received, we're expecting a commit or a DHPart1 or a Confirm1 packet */
		if ((zrtpPacket->messageType != MSGTYPE_COMMIT) && (zrtpPacket->messageType != MSGTYPE_DHPART1) && (zrtpPacket->messageType != MSGTYPE_CONFIRM1)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}
		/* DHPART1 can be received only if we are in DHM mode */
		if ((zrtpPacket->messageType == MSGTYPE_DHPART1) && ((zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh))) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}
		/* Confirm1 can be received only if we are in Mult or PreShared mode */
		if ((zrtpPacket->messageType == MSGTYPE_CONFIRM1) && (zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Prsh) && (zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Mult)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* if we have a confirm1 and are in multi stream mode, we must first derive s0 and other keys to be able to parse the packet */
		if ((zrtpPacket->messageType == MSGTYPE_CONFIRM1) && (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) {
			retval = bzrtp_computeS0MultiStreamMode(zrtpContext, zrtpChannelContext);
			if (retval!= 0) {
				return retval;
			}
		}

		/* parse the packet wich is either Commit a DHPart1 or a Confirm1 packet */
		retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
		if (retval != 0) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return retval;
		}

		/* packet is valid, set the sequence Number in channel context */
		zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;
		
		/* create the init event for next state */
		initEvent.eventType = BZRTP_EVENT_INIT;
		initEvent.bzrtpPacketString = NULL;
		initEvent.bzrtpPacketStringLength = 0;
484
		initEvent.bzrtpPacket = NULL;
485 486 487 488 489
		initEvent.zrtpContext = zrtpContext;
		initEvent.zrtpChannelContext = zrtpChannelContext;

		/* we have a DHPart1 - so we are initiator in DHM mode - stop timer and go to state_keyAgreement_initiatorSendingDHPart2 */
		if(zrtpPacket->messageType == MSGTYPE_DHPART1) {
490 491
			bzrtpDHPartMessage_t * dhPart1Message;

492 493 494
			/* stop the timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

495
			dhPart1Message = (bzrtpDHPartMessage_t *)zrtpPacket->messageData;
496 497 498

			/* Check shared secret hash found in the DHPart1 message */
			/* if we do not have the secret, don't check it as we do not expect the other part to have it neither */
johan's avatar
johan committed
499 500 501
			/* check matching secret is: check if locally computed(by the initiator) rs1 matches the responder rs1 or rs2 */
			/* if it doesn't check with initiator's rs2 and responder(received in DHPart1) rs1 or rs2 */
			/* In case of cache mismatch, warn the user(reset the Previously Verified Sas Flag) and erase secret as it must not be used to compute s0 */
502
			if (zrtpContext->cachedSecret.rs1!=NULL) {
johan's avatar
johan committed
503
				/* check if rs1 match peer's one */
johan's avatar
johan committed
504
				if (memcmp(zrtpContext->responderCachedSecretHash.rs1ID, dhPart1Message->rs1ID,8) != 0) {
johan's avatar
johan committed
505 506 507 508 509 510
					/* they don't match but self rs1 may match peer rs2 */
					if (memcmp(zrtpContext->responderCachedSecretHash.rs1ID, dhPart1Message->rs2ID,8) != 0) {
						/* They don't match either : erase rs1 and set the cache mismatch flag(which may be unset if self rs2 match peer rs1 or peer rs2 */
						free(zrtpContext->cachedSecret.rs1);
						zrtpContext->cachedSecret.rs1= NULL;
						zrtpContext->cachedSecret.rs1Length = 0;
johan's avatar
johan committed
511
						zrtpContext->cacheMismatchFlag = 1; /* Do not trigger cache mismatch message for now as it may match rs2 */
johan's avatar
johan committed
512
					}
513 514
				}
			}
johan's avatar
johan committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

			/* we didn't have a match with rs1 and have a rs2; check if it matches responder rs1 or rs2 */
			if ((zrtpContext->cacheMismatchFlag == 1) && (zrtpContext->cachedSecret.rs2!=NULL)) {
				/* does it match rs1 */
				if (memcmp(zrtpContext->responderCachedSecretHash.rs2ID, dhPart1Message->rs1ID,8) != 0) {
					/* it doesn't match rs1 but may match rs2 */
					if (memcmp(zrtpContext->responderCachedSecretHash.rs2ID, dhPart1Message->rs2ID,8) != 0) {
						free(zrtpContext->cachedSecret.rs2);
						zrtpContext->cachedSecret.rs2= NULL;
						zrtpContext->cachedSecret.rs2Length = 0;
					} else { /* it matches rs2, reset the cache mismatch flag */
						zrtpContext->cacheMismatchFlag = 0;
					}
				} else { /* it matches rs1, reset the cache mismatch flag */
					zrtpContext->cacheMismatchFlag = 0;
530 531
				}
			}
johan's avatar
johan committed
532

533
			if (zrtpContext->cachedSecret.auxsecret!=NULL) {
johan's avatar
johan committed
534 535 536 537
				if (memcmp(zrtpChannelContext->responderAuxsecretID, dhPart1Message->auxsecretID,8) != 0) {
					free(zrtpContext->cachedSecret.auxsecret);
					zrtpContext->cachedSecret.auxsecret= NULL;
					zrtpContext->cachedSecret.auxsecretLength = 0;
538 539 540
				}
			}
			if (zrtpContext->cachedSecret.pbxsecret!=NULL) {
johan's avatar
johan committed
541 542 543 544
				if (memcmp(zrtpContext->responderCachedSecretHash.pbxsecretID, dhPart1Message->pbxsecretID,8) != 0) {
					free(zrtpContext->cachedSecret.pbxsecret);
					zrtpContext->cachedSecret.pbxsecret= NULL;
					zrtpContext->cachedSecret.pbxsecretLength = 0;
545 546 547
				}
			}

johan's avatar
johan committed
548 549 550
			/* in case of cache mismatch, be sure the Previously Verified Sas flag is reset in cache and in the context */
			if (zrtpContext->cacheMismatchFlag == 1) {
				uint8_t pvsFlag = 0;
551
				const char *colNames[] = {"pvs"};
johan's avatar
johan committed
552 553 554
				uint8_t *colValues[] = {&pvsFlag};
				size_t colLength[] = {1};

johan's avatar
johan committed
555
				zrtpContext->cachedSecret.previouslyVerifiedSas = 0;
johan's avatar
johan committed
556
				bzrtp_cache_write(zrtpContext->zidCache, zrtpContext->zuid, "zrtp", colNames, colValues, colLength, 1);
johan's avatar
johan committed
557

johan's avatar
johan committed
558 559
				/* if we have a statusMessage callback, use it to warn user */
				if (zrtpContext->zrtpCallbacks.bzrtp_statusMessage!=NULL && zrtpContext->zrtpCallbacks.bzrtp_messageLevel>=BZRTP_MESSAGE_ERROR) { /* use error level as this one MUST (RFC section 4.3.2) be warned */
johan's avatar
johan committed
560
					zrtpContext->zrtpCallbacks.bzrtp_statusMessage(zrtpChannelContext->clientData, BZRTP_MESSAGE_ERROR, BZRTP_MESSAGE_CACHEMISMATCH, NULL);
johan's avatar
johan committed
561
				}
johan's avatar
johan committed
562 563
			}

564 565 566 567 568 569 570 571
			/* Check that the received PV is not 1 or Prime-1 TODO*/


			/* update context with the information found in the packet */
			memcpy(zrtpChannelContext->peerH[1], dhPart1Message->H1, 32);
			zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket;

			/* Compute the shared DH secret */
572 573
			zrtpContext->DHMContext->peer = (uint8_t *)malloc(zrtpChannelContext->keyAgreementLength*sizeof(uint8_t));
			memcpy (zrtpContext->DHMContext->peer, dhPart1Message->pv, zrtpChannelContext->keyAgreementLength);
jehan's avatar
jehan committed
574
			bctbx_DHMComputeSecret(zrtpContext->DHMContext, (int (*)(void *, uint8_t *, size_t))bctbx_rng_get, (void *)zrtpContext->RNGContext);
575 576 577 578 579 580 581 582 583 584 585 586 587

			/* Derive the s0 key */
			bzrtp_computeS0DHMMode(zrtpContext, zrtpChannelContext);

			/* set next state to state_keyAgreement_initiatorSendingDHPart2 */
			zrtpChannelContext->stateMachine = state_keyAgreement_initiatorSendingDHPart2;

			/* call it with the init event */
			return zrtpChannelContext->stateMachine(initEvent);
		}

		/* we have a Confirm1 - so we are initiator and in NON-DHM mode - stop timer and go to state_confirmation_initiatorSendingConfirm2 */
		if(zrtpPacket->messageType == MSGTYPE_CONFIRM1) {
588 589
			bzrtpConfirmMessage_t *confirm1Message;

590 591 592 593
			/* stop the timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

			/* save the message and extract some information from it to the channel context */
594
			confirm1Message = (bzrtpConfirmMessage_t *)zrtpPacket->messageData;
595 596
			memcpy(zrtpChannelContext->peerH[0], confirm1Message->H0, 32);

597 598 599
			/* store the packet to check possible repetitions */
			zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID] = zrtpPacket;

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
			/* set next state to state_confirmation_responderSendingConfirm2 */
			zrtpChannelContext->stateMachine = state_confirmation_initiatorSendingConfirm2;

			/* call it with the init event */
			return zrtpChannelContext->stateMachine(initEvent);
		}

		/* we have a commit - do commit contention as in rfc section 4.2 - if we are initiator, keep sending Commits, otherwise stop the timer and go to state_keyAgreement_responderSendingDHPart1 if we are DHM mode or state_confirmation_responderSendingConfirm1 in Multi or PreShared mode */
		if(zrtpPacket->messageType == MSGTYPE_COMMIT) {
			bzrtpCommitMessage_t *peerCommitMessage = (bzrtpCommitMessage_t *)zrtpPacket->messageData;
			bzrtpCommitMessage_t *selfCommitMessage = (bzrtpCommitMessage_t *)zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageData;
			/* - If one Commit is for a DH mode while the other is for Preshared mode, then the Preshared Commit MUST be discarded and the DH Commit proceeds
			 *
			 * - If the two Commits are both Preshared mode, and one party has set the MiTM (M) flag in the Hello message and the other has not, the Commit message from the party who set the (M) flag MUST be discarded, and the one who has not set the (M) flag becomes the initiator, regardless of the nonce values.  In other words, for Preshared mode, the phone is the initiator and the PBX is the responder.
			 *
			 * - If the two Commits are either both DH modes or both non-DH modes, then the Commit message with the lowest hvi (hash value of initiator) value (for DH Commits), or lowest nonce value (for non-DH Commits), MUST be discarded and the other side is the initiator, and the protocol proceeds with the initiator's Commit.  The two hvi or nonce values are compared as large unsigned integers in network byte order.
			 */

			/* we are by default initiator, so just check the statement which turns us into responder */
			if (peerCommitMessage->keyAgreementAlgo != selfCommitMessage->keyAgreementAlgo ) { /* commits have differents modes */
				if ((peerCommitMessage->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Prsh) && (selfCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh)) {
johan's avatar
johan committed
621
					zrtpChannelContext->role = BZRTP_ROLE_RESPONDER;
622 623 624 625 626 627 628
				}
			} else { /* commit have the same mode */ 
				bzrtpHelloMessage_t *peerHelloMessage = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData;
				bzrtpHelloMessage_t *selfHelloMessage = (bzrtpHelloMessage_t *)zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageData;

				if (peerCommitMessage->keyAgreementAlgo ==  ZRTP_KEYAGREEMENT_Prsh && ((selfHelloMessage->M == 1) || (peerHelloMessage->M == 1)) ) {
					if (selfHelloMessage->M == 1) { /* we are a PBX -> act as responder */
johan's avatar
johan committed
629
						zrtpChannelContext->role = BZRTP_ROLE_RESPONDER;
630 631 632 633
					}
				} else { /* modes are the same and no one has the MiTM flag set : compare hvi/nonce */
					if ((selfCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (selfCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { /* non DHM mode, compare the nonce, lower will be responder */
						if (memcmp(selfCommitMessage->nonce, peerCommitMessage->nonce, 16) < 0) { /* self nonce < peer nonce */
johan's avatar
johan committed
634
							zrtpChannelContext->role = BZRTP_ROLE_RESPONDER;
635 636 637 638
						}
	
					} else { /* DHM mode, compare the hvi */
						if (memcmp(selfCommitMessage->hvi, peerCommitMessage->hvi, 32) < 0) { /* self hvi < peer hvi */
johan's avatar
johan committed
639
							zrtpChannelContext->role = BZRTP_ROLE_RESPONDER;
640 641 642 643 644 645
						}
					}
				}
			}
			
			/* so now check if we are responder - if we are initiator just do nothing, continue sending the commits and ignore the one we just receive */
johan's avatar
johan committed
646
			if (zrtpChannelContext->role == BZRTP_ROLE_RESPONDER) {
647 648 649 650 651
				/* free the self commit packet as it is now useless */
				bzrtp_freeZrtpPacket(zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]);
				zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID] = NULL;
				/* this will update the context channel and run the next state according to current mode */
				return bzrtp_turnIntoResponder(zrtpContext, zrtpChannelContext, zrtpPacket, peerCommitMessage);
johan's avatar
johan committed
652 653
			} else { /* we are iniator, just drop the incoming commit packet and keep send our */
				bzrtp_freeZrtpPacket(zrtpPacket);
654 655 656 657 658 659 660 661 662 663
			}
		}

		return 0;
	}

	/*** Manage timer event ***/
	if (event.eventType == BZRTP_EVENT_TIMER) {

		/* adjust timer for next time : check we didn't reach the max retransmissions adjust the step(double it until reaching the cap) */
664 665
		if (zrtpChannelContext->timer.firingCount<=NON_HELLO_MAX_RETRANSMISSION_NUMBER) {
			if (2*zrtpChannelContext->timer.timerStep<=NON_HELLO_CAP_RETRANSMISSION_STEP) {
666 667 668 669 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
				zrtpChannelContext->timer.timerStep *= 2;
			}
			zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + zrtpChannelContext->timer.timerStep;
		} else { /* we have done enough retransmissions, stop it */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
		}

		/* We must resend a Commit packet */
		retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
		if (retval == 0) {
		zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		zrtpChannelContext->selfSequenceNumber++;
		} else {
			return retval;
		}

	}

	return 0;
}


/*
 * @brief For DHM mode only, responder send DHPart1 packet
 *
 * Arrives from:
 *  - state_discovery_waitingForHelloAck upon Commit reception in DHM mode
 *  - state_keyAgreement_sendingCommit upon Commit reception in DHM mode and commit contention gives us the responder role
 * Goes to:
 * 	- state_confirmation_responderSendingConfirm1 upon DHPart2 reception
 * Send :
 * 	- DHPart1 on Commit reception
 *
 */
int state_keyAgreement_responderSendingDHPart1(bzrtpEvent_t event) {

	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;
705
	int retval;
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723

	/* We are supposed to send DHPart1 packet and it is already in context(built from DHPart when turning into responder) or it's an error */
	if (zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID] == NULL) {
		return BZRTP_ERROR_INVALIDCONTEXT;
	}

	/*** Manage the first call to this function ***/
	if (event.eventType == BZRTP_EVENT_INIT) {
		/* There is no timer in this state, make sure it is off */
		zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

		/* now send the first DHPart1 message, note the sequence number has already been incremented when turning the DHPart2 message in DHPart1 */
		zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		return 0;
	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
johan's avatar
johan committed
724
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
725 726 727 728 729 730 731 732 733 734
		
		/* now check the type of packet received, we're expecting DHPart2 or a Commit packet */
		if ((zrtpPacket->messageType != MSGTYPE_COMMIT) && (zrtpPacket->messageType != MSGTYPE_DHPART2)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}
		
		
		/* we have a Commit, check it is the same as received previously and resend the DHPart1 packet */
		if(zrtpPacket->messageType == MSGTYPE_COMMIT) {
735 736 737 738
			if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}
739
			if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength) != 0) {
740 741 742 743 744 745 746
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}

			/* incoming packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

747 748 749
			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

750 751 752 753 754 755 756 757 758 759 760 761 762 763
			/* update and send the DHPart1 packet */
			retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
			if (retval != 0) {
				return retval;
			}

			zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
			zrtpChannelContext->selfSequenceNumber++;

			return 0;
		}

		/* we have a DHPart2 go to state_confirmation_responderSendingConfirm1 */
		if(zrtpPacket->messageType == MSGTYPE_DHPART2) {
764 765 766 767
			bzrtpDHPartMessage_t * dhPart2Message;
			uint8_t cacheMatchFlag = 0;
			bzrtpEvent_t initEvent;

768 769 770 771 772 773 774
			/* parse the packet */
			retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
			if (retval != 0) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return retval;
			}

775
			dhPart2Message = (bzrtpDHPartMessage_t *)zrtpPacket->messageData;
776 777 778

			/* Check shared secret hash found in the DHPart2 message */
			/* if we do not have the secret, don't check it as we do not expect the other part to have it neither */
johan's avatar
johan committed
779
			/* shared secret matching is: check if initiator rs1(received in DHPart2) match localy computed(by responder from cache) rs1 or rs2 */
johan's avatar
johan committed
780 781 782
			/* of not check if received rs2 match local rs1 or rs2 */
			/* keep the rs1 or rs2 in cachedSecret only if it matches the received one, it will the be used to compute s0 */
			/* In case of cache mismatch, warn the user(reset the previously verified Sas flag) and erase secret as it must not be used to compute s0 */
783
			if (zrtpContext->cachedSecret.rs1!=NULL) {
johan's avatar
johan committed
784
				/* check if rs1 match peer's one */
785
				if (memcmp(zrtpContext->initiatorCachedSecretHash.rs1ID, dhPart2Message->rs1ID,8) != 0) {
johan's avatar
johan committed
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
					/* they don't match but self rs2 may match peer rs1 */
					if (zrtpContext->cachedSecret.rs2!=NULL) {
						if (memcmp(zrtpContext->initiatorCachedSecretHash.rs2ID, dhPart2Message->rs1ID,8) == 0) {
							/* responder rs2 match initiator rs1, erase responder rs1 */
							cacheMatchFlag = 1;
							free(zrtpContext->cachedSecret.rs1);
							zrtpContext->cachedSecret.rs1= NULL;
							zrtpContext->cachedSecret.rs1Length = 0;
						}
					}
				} else { /* responder rs1 match initiator rs1 */
					cacheMatchFlag = 1;
				}
			}

johan's avatar
johan committed
801
			/* if we didn't found a match yet(initiator rs1 doesn't match local rs1 or rs2) */
johan's avatar
johan committed
802 803 804 805
			if ((zrtpContext->cachedSecret.rs1!=NULL) && (cacheMatchFlag == 0)) {
				/* does it match initiator rs2 */
				if (memcmp(zrtpContext->initiatorCachedSecretHash.rs1ID, dhPart2Message->rs2ID,8) != 0) {
					/* it doesn't match rs1 (erase it) but may match rs2 */
johan's avatar
johan committed
806 807 808
					free(zrtpContext->cachedSecret.rs1);
					zrtpContext->cachedSecret.rs1= NULL;
					zrtpContext->cachedSecret.rs1Length = 0;
johan's avatar
johan committed
809 810 811 812 813 814 815 816 817 818 819 820

					if (zrtpContext->cachedSecret.rs2!=NULL) {
						if (memcmp(zrtpContext->initiatorCachedSecretHash.rs2ID, dhPart2Message->rs2ID,8) != 0) {
							/* no match found erase rs2 and set the cache mismatch flag */
							free(zrtpContext->cachedSecret.rs2);
							zrtpContext->cachedSecret.rs2= NULL;
							zrtpContext->cachedSecret.rs2Length = 0;
							zrtpContext->cacheMismatchFlag = 1;
						}
					} else {
							zrtpContext->cacheMismatchFlag = 1;
					}
821 822
				}
			}
johan's avatar
johan committed
823

824 825
			if (zrtpContext->cachedSecret.auxsecret!=NULL) {
				if (memcmp(zrtpChannelContext->initiatorAuxsecretID, dhPart2Message->auxsecretID,8) != 0) {
johan's avatar
johan committed
826 827 828 829 830
					free(zrtpContext->cachedSecret.auxsecret);
					zrtpContext->cachedSecret.auxsecret= NULL;
					zrtpContext->cachedSecret.auxsecretLength = 0;
					/*bzrtp_freeZrtpPacket(zrtpPacket);
					return BZRTP_ERROR_CACHEMISMATCH;*/
831 832 833 834
				}
			}
			if (zrtpContext->cachedSecret.pbxsecret!=NULL) {
				if (memcmp(zrtpContext->initiatorCachedSecretHash.pbxsecretID, dhPart2Message->pbxsecretID,8) != 0) {
johan's avatar
johan committed
835 836 837 838 839
					free(zrtpContext->cachedSecret.pbxsecret);
					zrtpContext->cachedSecret.pbxsecret= NULL;
					zrtpContext->cachedSecret.pbxsecretLength = 0;
					/*bzrtp_freeZrtpPacket(zrtpPacket);
					return BZRTP_ERROR_CACHEMISMATCH;*/
840 841 842
				}
			}

johan's avatar
johan committed
843 844 845
			/* in case of cache mismatch, be sure the Previously Verified Sas flag is reset in cache and in the context */
			if (zrtpContext->cacheMismatchFlag == 1) {
				uint8_t pvsFlag = 0;
846
				const char *colNames[] = {"pvs"};
johan's avatar
johan committed
847 848 849
				uint8_t *colValues[] = {&pvsFlag};
				size_t colLength[] = {1};

johan's avatar
johan committed
850
				zrtpContext->cachedSecret.previouslyVerifiedSas = 0;
johan's avatar
johan committed
851
				bzrtp_cache_write(zrtpContext->zidCache, zrtpContext->zuid, "zrtp", colNames, colValues, colLength, 1);
johan's avatar
johan committed
852

johan's avatar
johan committed
853 854
				/* if we have a statusMessage callback, use it to warn user */
				if (zrtpContext->zrtpCallbacks.bzrtp_statusMessage!=NULL && zrtpContext->zrtpCallbacks.bzrtp_messageLevel>=BZRTP_MESSAGE_ERROR) { /* use error level as this one MUST (RFC section 4.3.2) be warned */
johan's avatar
johan committed
855
					zrtpContext->zrtpCallbacks.bzrtp_statusMessage(zrtpChannelContext->clientData, BZRTP_MESSAGE_ERROR, BZRTP_MESSAGE_CACHEMISMATCH, NULL);
johan's avatar
johan committed
856
				}
johan's avatar
johan committed
857 858 859
			}


johan's avatar
johan committed
860
			/* Check that the received PV is not 1 or Prime-1 : is performed by crypto lib */
861 862 863 864 865 866 867 868 869

			/* packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

			/* update context with the information found in the packet */
			memcpy(zrtpChannelContext->peerH[1], dhPart2Message->H1, 32);
			zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket;

			/* Compute the shared DH secret */
870 871
			zrtpContext->DHMContext->peer = (uint8_t *)malloc(zrtpChannelContext->keyAgreementLength*sizeof(uint8_t));
			memcpy (zrtpContext->DHMContext->peer, dhPart2Message->pv, zrtpChannelContext->keyAgreementLength);
jehan's avatar
jehan committed
872
			bctbx_DHMComputeSecret(zrtpContext->DHMContext, (int (*)(void *, uint8_t *, size_t))bctbx_rng_get, (void *)zrtpContext->RNGContext);
873 874 875 876 877 878 879 880

			/* Derive the s0 key */
			bzrtp_computeS0DHMMode(zrtpContext, zrtpChannelContext);

			/* create the init event for next state */
			initEvent.eventType = BZRTP_EVENT_INIT;
			initEvent.bzrtpPacketString = NULL;
			initEvent.bzrtpPacketStringLength = 0;
881
			initEvent.bzrtpPacket = NULL;
882 883 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
			initEvent.zrtpContext = zrtpContext;
			initEvent.zrtpChannelContext = zrtpChannelContext;

			/* set the next state to state_confirmation_responderSendingConfirm1 */
			zrtpChannelContext->stateMachine = state_confirmation_responderSendingConfirm1;

			/* call it with the init event */
			return zrtpChannelContext->stateMachine(initEvent);
		}

	}

	/*** Manage timer event ***/
	/* no timer for this state, initiator only retransmit packets, we just send DHPart1 when ever a commit arrives */
	return 0;
}

/*
 * @brief For DHM mode only, initiator send DHPart2 packet
 *
 * Arrives from:
 *  - state_keyAgreement_sendingCommit upon DHPart1 reception
 * Goes to:
 * 	- state_confirmation_initiatorSendingConfirm2 upon reception of Confirm1
 * Send :
 * 	- DHPart2 until timer's end or transition
 *
 */
int state_keyAgreement_initiatorSendingDHPart2(bzrtpEvent_t event) {
	int retval;

	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;

	/*** Manage the first call to this function ***/
	/* We have to send a DHPart2 packet, it is already present in the context */
919
	if (event.eventType == BZRTP_EVENT_INIT) {
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
		/* adjust the sequence number and sennd the packet */
		retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
		if (retval == 0) {
			zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
			zrtpChannelContext->selfSequenceNumber++;
		} else {
			return retval;
		}
		
		/* it is the first call to this state function, so we must set the timer for retransmissions */
		zrtpChannelContext->timer.status = BZRTP_TIMER_ON;
		zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + NON_HELLO_BASE_RETRANSMISSION_STEP;
		zrtpChannelContext->timer.firingCount = 0;
		zrtpChannelContext->timer.timerStep = NON_HELLO_BASE_RETRANSMISSION_STEP;

		return 0;
	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
johan's avatar
johan committed
940
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
941 942 943 944 945 946 947 948 949 950 951
		
		/* now check the type of packet received, we're expecting a confirm1 packet, DHPart1 packet may arrives, just check they are the same we previously received */
		if ((zrtpPacket->messageType != MSGTYPE_DHPART1) && (zrtpPacket->messageType != MSGTYPE_CONFIRM1)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}


		
		/* we have DHPart1 packet, just check it is the same we received previously and do nothing */
		if (zrtpPacket->messageType == MSGTYPE_DHPART1) {
952 953 954 955
			if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}
956
			if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength) != 0) {
957 958 959 960 961 962 963
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}

			/* incoming packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

964 965 966 967

			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

968 969 970 971 972
			return 0;
		}

		/* we have a confirm1 packet, go to state_confirmation_initiatorSendingConfirm2 state */
		if (zrtpPacket->messageType == MSGTYPE_CONFIRM1) {
973 974 975
			bzrtpConfirmMessage_t *confirm1Packet;
			bzrtpEvent_t initEvent;

976 977 978 979 980 981 982 983 984 985 986
			/* parse the packet */
			retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
			if (retval != 0) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return retval;
			}

			/* stop the timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

			/* update context with the information found in the packet */
987
			confirm1Packet = (bzrtpConfirmMessage_t *)zrtpPacket->messageData;
988
			memcpy(zrtpChannelContext->peerH[0], confirm1Packet->H0, 32);
989 990 991 992
			/* on the first channel, set peerPVS in context */
			if (zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Mult) {
				zrtpContext->peerPVS=confirm1Packet->V;
			}
993 994 995 996 997 998 999 1000 1001 1002 1003

			/* store the packet to check possible repetitions */
			zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID] = zrtpPacket;

			/* packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

			/* create the init event for next state */
			initEvent.eventType = BZRTP_EVENT_INIT;
			initEvent.bzrtpPacketString = NULL;
			initEvent.bzrtpPacketStringLength = 0;
1004
			initEvent.bzrtpPacket = NULL;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
			initEvent.zrtpContext = zrtpContext;
			initEvent.zrtpChannelContext = zrtpChannelContext;

			/* next state is state_confirmation_initiatorSendingConfirm2*/
			zrtpChannelContext->stateMachine = state_confirmation_initiatorSendingConfirm2;

			/* call the next state with the init event */
			return zrtpChannelContext->stateMachine(initEvent);
		}
	}


	/*** Manage timer event ***/
	if (event.eventType == BZRTP_EVENT_TIMER) {

		/* adjust timer for next time : check we didn't reach the max retransmissions adjust the step(double it until reaching the cap) */
1021 1022
		if (zrtpChannelContext->timer.firingCount<=NON_HELLO_MAX_RETRANSMISSION_NUMBER) {
			if (2*zrtpChannelContext->timer.timerStep<=NON_HELLO_CAP_RETRANSMISSION_STEP) {
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
				zrtpChannelContext->timer.timerStep *= 2;
			}
			zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + zrtpChannelContext->timer.timerStep;
		} else { /* we have done enough retransmissions, stop it */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
		}

		/* We must resend a DHPart1 packet */
		retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
		if (retval == 0) {
			zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
			zrtpChannelContext->selfSequenceNumber++;
		} else {
			return retval;
		}

	}

	return 0;
}


/*
 * @brief Responder send the confirm1 message
 *
 * Arrives from:
 * - state_keyAgreement_responderSendingDHPart1 upon DHPart2 reception
 * - state_keyAgreement_sendingCommit upon Commit reception in non DHM mode and commit contention gives us the responder role
 * - state_discovery_waitingForHelloAck upon Commit reception in non DHM mode
 * Goes to:
 * - state_secure on Confirm2 reception
 * Send :
 * - Confirm1 on Commit or DHPart2 reception
 *
 */
int state_confirmation_responderSendingConfirm1(bzrtpEvent_t event) {
	int retval;

	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;

	/*** Manage the first call to this function ***/
	if (event.eventType == BZRTP_EVENT_INIT) {
1067 1068
		bzrtpPacket_t *confirm1Packet;

1069 1070 1071
		/* when in multistream mode, we must derive s0 and other keys from ZRTPSess */
		if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) {
			/* we need ZRTPSess */
1072
			if (zrtpContext->ZRTPSess == NULL) {
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
				return BZRTP_ERROR_INVALIDCONTEXT;
			}
			retval = bzrtp_computeS0MultiStreamMode(zrtpContext, zrtpChannelContext);
			if (retval!= 0) {
				return retval;
			}
		} else if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { /* when in preShared mode: todo */
		} else { /* we are in DHM mode, check that we have the keys needed to build the confirm1 packet */
			/* we must build the confirm1 packet, check in the channel context if we have the needed keys */
			if ((zrtpChannelContext->mackeyr == NULL) || (zrtpChannelContext->zrtpkeyr == NULL)) {
				return BZRTP_ERROR_INVALIDCONTEXT;
			}
		}

		/* There is no timer in this state, make sure it is off */
		zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

		/* build the confirm1 packet */
1091
		confirm1Packet = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_CONFIRM1, &retval);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
		if (retval!=0) {
			return retval;
		}
		retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, confirm1Packet, zrtpChannelContext->selfSequenceNumber);
		if (retval!=0) {
			bzrtp_freeZrtpPacket(confirm1Packet);
			return retval;
		}
		zrtpChannelContext->selfSequenceNumber++;

		/* save it so we can send it again if needed */
		zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID] = confirm1Packet;

		/* now send the confirm1 message */
		zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		return 0;
	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
johan's avatar
johan committed
1112
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128

		/* we expect packets Confirm2, Commit in NON-DHM mode  or DHPart2 in DHM mode */
		if ((zrtpPacket->messageType != MSGTYPE_CONFIRM2) && (zrtpPacket->messageType != MSGTYPE_COMMIT) && (zrtpPacket->messageType != MSGTYPE_DHPART2)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* We have a commit packet, check we are in non DHM mode, that the commit is identical to the one we already had and resend the Confirm1 packet */
		if (zrtpPacket->messageType == MSGTYPE_COMMIT) {
			/* Check we are not in DHM mode */
			if ((zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Prsh) && (zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Mult)) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
			}

			/* Check the commit packet is the same we already had */
1129 1130 1131 1132
			if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}
1133
			if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength) != 0) {
1134 1135 1136 1137 1138 1139 1140
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}

			/* incoming packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

1141 1142 1143
			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
			/* update sequence number and resend confirm1 packet */
			retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
			if (retval!=0) {
				return retval;
			}
			zrtpChannelContext->selfSequenceNumber++;
			return zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		}

		/* We have a DHPart2 packet, check we are in DHM mode, that the DHPart2 is identical to the one we already had and resend the Confirm1 packet */
		if (zrtpPacket->messageType == MSGTYPE_DHPART2) {
			/* Check we are not DHM mode */
1156
			if ((zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) {
1157 1158 1159 1160
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
			}

1161 1162 1163 1164 1165
			/* Check the DHPart2 packet is the same we already had */
			if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}
1166
			if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength) != 0) {
1167 1168 1169 1170 1171 1172 1173
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}

			/* incoming packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

1174 1175 1176
			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
			/* update sequence number and resend confirm1 packet */
			retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
			if (retval!=0) {
				return retval;
			}
			zrtpChannelContext->selfSequenceNumber++;
			return zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		}

		/* We have a Confirm2 packet, check it, send a conf2ACK and go to secure state */
		if (zrtpPacket->messageType == MSGTYPE_CONFIRM2) {
1188 1189 1190 1191
			bzrtpConfirmMessage_t *confirm2Packet;
			bzrtpPacket_t *conf2ACKPacket;
			bzrtpEvent_t initEvent;

1192 1193 1194 1195 1196 1197 1198 1199
			/* parse the packet */
			retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
			if (retval != 0) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return retval;
			}

			/* update context with the information found in the packet */
1200
			confirm2Packet = (bzrtpConfirmMessage_t *)zrtpPacket->messageData;
1201
			memcpy(zrtpChannelContext->peerH[0], confirm2Packet->H0, 32);
1202 1203 1204 1205
			/* on the first channel, set peerPVS in context */
			if (zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Mult) {
				zrtpContext->peerPVS = confirm2Packet->V;
			}
1206

1207 1208
			/* store the packet to check possible repetitions : note the storage points to confirm1, delete it as we don't need it anymore */
			bzrtp_freeZrtpPacket(zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]);
1209 1210 1211 1212 1213
			zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID] = zrtpPacket;

			/* packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

johan's avatar
johan committed
1214 1215 1216 1217 1218
			/* compute SAS and srtp secrets */
			retval = bzrtp_deriveSrtpKeysFromS0(zrtpContext, zrtpChannelContext); 
			if (retval!=0) {
				return retval;
			}
johan's avatar
johan committed
1219 1220 1221
			
			/* compute and update in cache the retained shared secret */
			bzrtp_updateCachedSecrets(zrtpContext, zrtpChannelContext);
johan's avatar
johan committed
1222

johan's avatar
johan committed
1223
			/* send them to the environment for receiver as we may receive a srtp packet in response to our conf2ACK */
1224
			if (zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable != NULL) {
johan's avatar
johan committed
1225
				zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable(zrtpChannelContext->clientData, &zrtpChannelContext->srtpSecrets, ZRTP_SRTP_SECRETS_FOR_RECEIVER);
1226 1227
			}

1228
			/* create and send a conf2ACK packet */
1229
			conf2ACKPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_CONF2ACK, &retval);
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
			if (retval!=0) {
				return retval;
			}
			retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, conf2ACKPacket, zrtpChannelContext->selfSequenceNumber);
			if (retval!=0) {
				bzrtp_freeZrtpPacket(conf2ACKPacket);
				return retval;
			}
			zrtpChannelContext->selfSequenceNumber++;

			retval = zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, conf2ACKPacket->packetString, conf2ACKPacket->messageLength+ZRTP_PACKET_OVERHEAD);
			bzrtp_freeZrtpPacket(conf2ACKPacket);
			if (retval!=0) {
				return retval;
			}

johan's avatar
johan committed
1246 1247 1248 1249 1250
			/* send SRTP secrets for sender as we can start sending srtp packets just after sending the conf2ACK */
			if (zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable != NULL) {
				zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable(zrtpChannelContext->clientData, &zrtpChannelContext->srtpSecrets, ZRTP_SRTP_SECRETS_FOR_SENDER);
			}
			
1251 1252 1253 1254
			/* create the init event for next state */
			initEvent.eventType = BZRTP_EVENT_INIT;
			initEvent.bzrtpPacketString = NULL;
			initEvent.bzrtpPacketStringLength = 0;
1255
			initEvent.bzrtpPacket = NULL;
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
			initEvent.zrtpContext = zrtpContext;
			initEvent.zrtpChannelContext = zrtpChannelContext;

			/* next state is state_secure */
			zrtpChannelContext->stateMachine = state_secure;

			/* call the next state with the init event */
			return zrtpChannelContext->stateMachine(initEvent);
		}
	}

	/*** Manage timer event ***/
	/* no timer for this state, initiator only retransmit packets, we just send confirm11 when ever a DHPart2 or commit arrives */

	return 0;
}


/*
 * @brief Initiator send the confirm2 message
 *
 * Arrives from:
 * - state_keyAgreement_initiatorSendingDHPart2 upon confirm1 reception
 * - state_keyAgreement_sendingCommit upon Confirm1 reception in non DHM mode
 * Goes to:
 * - state_secure on Conf2ACK reception or first SRTP message
 * Send :
 * - Confirm2 until timer's end or transition
 *
 */
int state_confirmation_initiatorSendingConfirm2(bzrtpEvent_t event) {
	int retval;

	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;

	/*** Manage the first call to this function ***/
	if (event.eventType == BZRTP_EVENT_INIT) {
1295
		bzrtpPacket_t *confirm2Packet;
1296 1297 1298 1299 1300 1301 1302

		/* we must build the confirm2 packet, check in the channel context if we have the needed keys */
		if ((zrtpChannelContext->mackeyi == NULL) || (zrtpChannelContext->zrtpkeyi == NULL)) {
			return BZRTP_ERROR_INVALIDCONTEXT;
		}

		/* build the confirm2 packet */
1303
		confirm2Packet = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_CONFIRM2, &retval);
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
		if (retval!=0) {
			return retval;
		}
		retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, confirm2Packet, zrtpChannelContext->selfSequenceNumber);
		if (retval!=0) {
			bzrtp_freeZrtpPacket(confirm2Packet);
			return retval;
		}

		/* save it so we can send it again if needed */
		zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID] = confirm2Packet;

johan's avatar
johan committed
1316 1317 1318 1319 1320
		/* compute SAS and SRTP secrets as responder may directly send SRTP packets and non conf2ACK */
		retval = bzrtp_deriveSrtpKeysFromS0(zrtpContext, zrtpChannelContext); 
		if (retval!=0) {
			return retval;
		}
1321

johan's avatar
johan committed
1322 1323
		/* send them to the environment, but specify they are for receiver only as we must wait for the conf2ACK or the first valid srtp packet from peer
		 * to start sending srtp packets */
1324
		if (zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable != NULL) {
johan's avatar
johan committed
1325 1326 1327 1328 1329 1330 1331
			zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable(zrtpChannelContext->clientData, &zrtpChannelContext->srtpSecrets, ZRTP_SRTP_SECRETS_FOR_RECEIVER);
		}

		/* now send the confirm2 message */
		retval = zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
		if (retval != 0) {
			return retval;
1332
		}
johan's avatar
johan committed
1333 1334
		zrtpChannelContext->selfSequenceNumber++;

1335

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
		/* it is the first call to this state function, so we must set the timer for retransmissions */
		zrtpChannelContext->timer.status = BZRTP_TIMER_ON;
		zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + NON_HELLO_BASE_RETRANSMISSION_STEP;
		zrtpChannelContext->timer.firingCount = 0;
		zrtpChannelContext->timer.timerStep = NON_HELLO_BASE_RETRANSMISSION_STEP;

	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
johan's avatar
johan committed
1346
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
1347 1348 1349 1350 1351 1352 1353 1354 1355

		/* we expect packets Conf2ACK, or a Confirm1 */
		if ((zrtpPacket->messageType != MSGTYPE_CONFIRM1) && (zrtpPacket->messageType != MSGTYPE_CONF2ACK)) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* we have confirm1 packet, just check it is the same we received previously and do nothing */
		if (zrtpPacket->messageType == MSGTYPE_CONFIRM1) {
1356 1357 1358 1359
			if (zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}
1360
			if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength) != 0) {
1361 1362 1363 1364 1365 1366 1367
				bzrtp_freeZrtpPacket(zrtpPacket);
				return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
			}

			/* incoming packet is valid, set the sequence Number in channel context */
			zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

1368 1369 1370
			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

1371 1372 1373 1374 1375
			return 0;
		}

		/* we have a conf2ACK packet, parse it to validate it, stop the timer and go to secure state */
		if (zrtpPacket->messageType == MSGTYPE_CONF2ACK) {
1376 1377
			bzrtpEvent_t initEvent;

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
			/* parse the packet */
			retval = bzrtp_packetParser(zrtpContext, zrtpChannelContext, event.bzrtpPacketString, event.bzrtpPacketStringLength, zrtpPacket);
			if (retval != 0) {
				bzrtp_freeZrtpPacket(zrtpPacket);
				return retval;
			}

			/* free the incoming packet */
			bzrtp_freeZrtpPacket(zrtpPacket);

			/* stop the retransmission timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
			
johan's avatar
johan committed
1391 1392 1393
			/* compute and update in cache the retained shared secret */
			bzrtp_updateCachedSecrets(zrtpContext, zrtpChannelContext);

johan's avatar
johan committed
1394 1395 1396 1397 1398
			/* send the sender srtp keys to the client(we sent receiver only when the first confirm1 packet arrived) */
			if (zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable != NULL) {
				zrtpContext->zrtpCallbacks.bzrtp_srtpSecretsAvailable(zrtpChannelContext->clientData, &zrtpChannelContext->srtpSecrets, ZRTP_SRTP_SECRETS_FOR_SENDER);
			}

1399 1400 1401 1402
			/* create the init event for next state */
			initEvent.eventType = BZRTP_EVENT_INIT;
			initEvent.bzrtpPacketString = NULL;
			initEvent.bzrtpPacketStringLength = 0;
1403
			initEvent.bzrtpPacket = NULL;
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
			initEvent.zrtpContext = zrtpContext;
			initEvent.zrtpChannelContext = zrtpChannelContext;

			/* next state is state_secure */
			zrtpChannelContext->stateMachine = state_secure;

			/* call the next state with the init event */
			return zrtpChannelContext->stateMachine(initEvent);
		}
	}

	/*** Manage timer event ***/
	if (event.eventType == BZRTP_EVENT_TIMER) {

		/* adjust timer for next time : check we didn't reach the max retransmissions adjust the step(double it until reaching the cap) */
1419 1420
		if (zrtpChannelContext->timer.firingCount<=NON_HELLO_MAX_RETRANSMISSION_NUMBER) {
			if (2*zrtpChannelContext->timer.timerStep<=NON_HELLO_CAP_RETRANSMISSION_STEP) {
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
				zrtpChannelContext->timer.timerStep *= 2;
			}
			zrtpChannelContext->timer.firingTime = zrtpContext->timeReference + zrtpChannelContext->timer.timerStep;
		} else { /* we have done enough retransmissions, stop it */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
		}

		/* We must resend a Confirm2 packet */
		retval = bzrtp_packetUpdateSequenceNumber(zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
		if (retval == 0) {
			zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->packetString, zrtpChannelContext->selfPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength+ZRTP_PACKET_OVERHEAD);
			zrtpChannelContext->selfSequenceNumber++;
		} else {
			return retval;
		}

	}

	return 0;
}

/*
 * @brief We are in secure state
 *
 * Arrives from:
 * 	- state_confirmation_responderSendingConfirm1 on Confirm2 reception
 * 	- state_confirmation_initiatorSendingConfirm2 on conf2ACK or first SRTP message
 * Goes to:
 * 	- This is the end(we do not support GoClear message), state machine may be destroyed after going to secure mode
 * Send :
 * 	- Conf2ACK on Confirm2 reception
 *
 */
int state_secure(bzrtpEvent_t event) {
	/* get the contextes from the event */
	bzrtpContext_t *zrtpContext = event.zrtpContext;
1457
	bzrtpChannelContext_t *zrtpChannelContext = event.zrtpChannelContext;
1458

1459 1460
	/*** Manage the first call to this function ***/
	if (event.eventType == BZRTP_EVENT_INIT) {
1461 1462
		/* there is no timer in this state, turn it off */
		zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;
1463 1464 1465 1466 1467 1468 1469

		/* if we are not in Multistream mode, turn the global context isSecure flag to 1 */
		if (zrtpChannelContext->keyAgreementAlgo != ZRTP_KEYAGREEMENT_Mult) {
			zrtpContext->isSecure = 1;
		}
		/* turn channel isSecure flag to 1 */
		zrtpChannelContext->isSecure = 1;
1470
	
1471 1472
		/* call the environment to signal we're ready to operate */
		if (zrtpContext->zrtpCallbacks.bzrtp_startSrtpSession!= NULL) {
1473
			zrtpContext->zrtpCallbacks.bzrtp_startSrtpSession(zrtpChannelContext->clientData, &(zrtpChannelContext->srtpSecrets), zrtpContext->cachedSecret.previouslyVerifiedSas && zrtpContext->peerPVS);
1474 1475 1476 1477 1478 1479
		}
		return 0;
	}

	/*** Manage message event ***/
	if (event.eventType == BZRTP_EVENT_MESSAGE) {
1480 1481
		int retval;
		bzrtpPacket_t *conf2ACKPacket;
1482
		bzrtpPacket_t *zrtpPacket = event.bzrtpPacket;
1483

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
		/* we expect confirm2 packet */
		if (zrtpPacket->messageType != MSGTYPE_CONFIRM2) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE;
		}

		/* We have a confirm2 packet, check it is identical to the one we already had and resend the Conf2ACK packet */
		/* Check the commit packet is the same we already had */
		if (zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength != zrtpPacket->messageLength) {
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
		}
1496
		if (memcmp(event.bzrtpPacketString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[CONFIRM_MESSAGE_STORE_ID]->messageLength) != 0) {
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
			bzrtp_freeZrtpPacket(zrtpPacket);
			return BZRTP_ERROR_UNMATCHINGPACKETREPETITION;
		}

		/* incoming packet is valid, set the sequence Number in channel context */
		zrtpChannelContext->peerSequenceNumber = zrtpPacket->sequenceNumber;

		/* free the incoming packet */
		bzrtp_freeZrtpPacket(zrtpPacket);

		/* create and send a conf2ACK packet */
1508
		conf2ACKPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_CONF2ACK, &retval);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
		if (retval!=0) {
			return retval;
		}
		retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, conf2ACKPacket, zrtpChannelContext->selfSequenceNumber);
		if (retval!=0) {
			bzrtp_freeZrtpPacket(conf2ACKPacket);
			return retval;
		}
		zrtpChannelContext->selfSequenceNumber++;

		retval = zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, conf2ACKPacket->packetString, conf2ACKPacket->messageLength+ZRTP_PACKET_OVERHEAD);
		/* free the conf2ACK packet */
		bzrtp_freeZrtpPacket(conf2ACKPacket);

		return retval;
1524
	}
1525

1526 1527 1528 1529

	/*** Manage timer event ***/
	/* no timer in this state */

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
	return 0;
}

/**
 * @brief Turn the current Channel into responder role
 * This happens when receiving a commit message when in state state_discovery_waitingForHelloAck or state_keyAgreement_sendingCommit if commit contention gives us the responder role.
 * State will be changed to state_confirmation_responderSendingConfirm1 or state_confirmation_responderSendingDHPart1 depending on DHM or non-DHM operation mode
 *
 * @param[in]		zrtpContext				The current zrtp Context
 * @param[in/out]	zrtpChannelContext		The channel we are operating
 * @param[in]		zrtpPacket				The zrtpPacket receives, it contains the commit message
 * @param[in]		commitMessage			A direct pointer to the commitMessage structure contained in the zrtp packet
 *
 * @return 0 on succes, error code otherwise
 */
int bzrtp_turnIntoResponder(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, bzrtpPacket_t *zrtpPacket, bzrtpCommitMessage_t *commitMessage) {
1546 1547
			bzrtpEvent_t initEvent;

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
			/* kill the ongoing timer */
			zrtpChannelContext->timer.status = BZRTP_TIMER_OFF;

			/* store the commit packet in the channel context as it is needed later to check MAC */
			zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket;

			/* save the peer H2 */
			memcpy(zrtpChannelContext->peerH[2], commitMessage->H2, 32); /* H2 */

			/* we are receiver, set it in the context and update our selected algos */
johan's avatar
johan committed
1558
			zrtpChannelContext->role = BZRTP_ROLE_RESPONDER;
1559 1560 1561 1562 1563
			zrtpChannelContext->hashAlgo = commitMessage->hashAlgo;
			zrtpChannelContext->cipherAlgo = commitMessage->cipherAlgo;
			zrtpChannelContext->authTagAlgo = commitMessage->authTagAlgo;
			zrtpChannelContext->keyAgreementAlgo = commitMessage->keyAgreementAlgo;
			zrtpChannelContext->sasAlgo = commitMessage->sasAlgo;
Ghislain MARY's avatar
Ghislain MARY committed
1564
			bzrtp_updateCryptoFunctionPointers(zrtpChannelContext);
1565 1566 1567 1568 1569

			/* if we have a self DHPart packet (means we are in DHM mode) we must rebuild the self DHPart packet to be responder and not initiator */
			/* as responder we must swap the aux shared secret between responder and initiator as they are computed using the H3 and not a constant string */
			if (zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID] != NULL) {
				uint8_t tmpBuffer[8];
1570 1571 1572
				bzrtpDHPartMessage_t *selfDHPart1Packet;
				int retval;

1573 1574 1575 1576 1577 1578 1579 1580
				memcpy(tmpBuffer, zrtpChannelContext->initiatorAuxsecretID, 8);
				memcpy(zrtpChannelContext->initiatorAuxsecretID, zrtpChannelContext->responderAuxsecretID, 8);
				memcpy(zrtpChannelContext->responderAuxsecretID, tmpBuffer, 8);
	
				/* responder self DHPart packet is DHPart1, change the type (we created a DHPart2) */
				zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageType = MSGTYPE_DHPART1;
	
				/* change the shared secret ID to the responder one (we set them by default to the initiator's one) */
1581
				selfDHPart1Packet = (bzrtpDHPartMessage_t *)zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageData;
1582 1583 1584 1585 1586
				memcpy(selfDHPart1Packet->rs1ID, zrtpContext->responderCachedSecretHash.rs1ID, 8);
				memcpy(selfDHPart1Packet->rs2ID, zrtpContext->responderCachedSecretHash.rs2ID, 8);
				memcpy(selfDHPart1Packet->auxsecretID, zrtpChannelContext->responderAuxsecretID, 8);
				memcpy(selfDHPart1Packet->pbxsecretID, zrtpContext->responderCachedSecretHash.pbxsecretID, 8);
	
1587 1588 1589
				/* free the packet string and rebuild the packet */
				free(zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString);
				zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString = NULL;
1590
				retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID], zrtpChannelContext->selfSequenceNumber);
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
				if (retval == 0) {
					zrtpChannelContext->selfSequenceNumber++;
				} else {
					return retval;
				}
			}

			/* create the init event for next state */
			initEvent.eventType = BZRTP_EVENT_INIT;
			initEvent.bzrtpPacketString = NULL;
			initEvent.bzrtpPacketStringLength = 0;
1602
			initEvent.bzrtpPacket = NULL;
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
			initEvent.zrtpContext = zrtpContext;
			initEvent.zrtpChannelContext = zrtpChannelContext;

			/* if we are in PreShared or Multi mode, go to state_confirmation_responderSendingConfirm1 */
			if ((zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) {
				/* set next state to state_confirmation_responderSendingConfirm1 */
				zrtpChannelContext->stateMachine = state_confirmation_responderSendingConfirm1;

				/* call it with the init event */
				return zrtpChannelContext->stateMachine(initEvent);

			} else {/* if we are in DHM mode, goes to state_keyAgreement_responderSendingDHPart1 */
				/* set next state to state_keyAgreement_responderSendingDHPart1 */
				zrtpChannelContext->stateMachine = state_keyAgreement_responderSendingDHPart1;

				/* call it with the init event */
				return zrtpChannelContext->stateMachine(initEvent);
			}
}

/**
 * @brief When a Hello message arrive from peer for the first time, we shall parse it to check if it match our configuration and act on the context
 * This message may arrives when in state state_discovery_init or state_discovery_waitingForHello.
 * - Find agreement on algo to use
 * - Check if we have retained secrets in cache matching the peer ZID
 * - if agreed on a DHM mode : compute the public value and prepare a DHPart2 packet(assume we are initiator, change later if needed)
 * - if agreed on a non-DHM mode : compute s0 and derive keys from it TODO
 *
 * @param[in]		zrtpContext				The current zrtp Context
 * @param[in/out]	zrtpChannelContext		The channel we are operating
1633
 * @param[in]		zrtpPacket				The zrtpPacket received, it contains the hello message
1634 1635 1636
 *
 * @return 0 on succes, error code otherwise
 */
johan's avatar
johan committed
1637
int bzrtp_responseToHelloMessage(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, bzrtpPacket_t *zrtpPacket) {
1638
	int retval;
1639 1640 1641
	int i;
	uint8_t peerSupportMultiChannel = 0;
	bzrtpPacket_t *helloACKPacket;
1642 1643 1644 1645 1646 1647 1648 1649 1650
	bzrtpHelloMessage_t *helloMessage = (bzrtpHelloMessage_t *)zrtpPacket->messageData;

	/* check supported version of ZRTP protocol */
	if (memcmp(helloMessage->version, ZRTP_VERSION, 3) != 0) { /* we support version 1.10 only but checking is done on 1.1? as explained in rfc section 4.1.1 */
		bzrtp_freeZrtpPacket(zrtpPacket);
		return BZRTP_ERROR_UNSUPPORTEDZRTPVERSION; /* packet shall be ignored*/
	}

	/* now check we have some algo in common. zrtpChannelContext will be updated with common algos if found */
Ghislain MARY's avatar
Ghislain MARY committed
1651
	retval = bzrtp_cryptoAlgoAgreement(zrtpContext, zrtpChannelContext, helloMessage);
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
	if(retval != 0) {
		bzrtp_freeZrtpPacket(zrtpPacket);
		return retval;
	}

	/* check if the peer accept MultiChannel */
	for (i=0; i<helloMessage->kc; i++) {
		if (helloMessage->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) {
			peerSupportMultiChannel = 1;
		}
	}
	zrtpContext->peerSupportMultiChannel = peerSupportMultiChannel;

	/* copy into the channel context the relevant informations */
	memcpy(zrtpContext->peerZID, helloMessage->ZID, 12); /* peer ZID */
	memcpy(zrtpChannelContext->peerH[3], helloMessage->H3, 32); /* H3 */
	zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; /* peer hello packet */

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
	/* Extract from peerHello packet the version of bzrtp used by peer and store it in global context(needed later when exporting keys)
	 * Bzrtp version started to be publicised in version 1.1, before that the client identifier was simply BZRTP and earlier version also have LINPHONE-ZRTPCPP
	 * We must know this version in order to keep export key computation compatible between version as before v1.1 it was badly implemented
	 * So basically check :
	 *	if the client identifier is BZRTP or LINPHONE-ZRTPCPP -> version 1.0 (use the old and incorrect way of creating an export key)
	 * 	if BZRTPv1.1 -> version 1.1 (use RFC compliant way of creating the export key )
	 * 	if anything else peer use another library, set version to 0.0 and use RFC compliant way of creating the export key as peer library is expected to be RFC compliant
	*/
	/* This is BZRTP in its old version */
	if ((strncmp(ZRTP_CLIENT_IDENTIFIERv1_0a, (char *)helloMessage->clientIdentifier, 16)==0) || (strncmp(ZRTP_CLIENT_IDENTIFIERv1_0b, (char *)helloMessage->clientIdentifier, 16)==0)){
johan's avatar
johan committed
1680
		zrtpContext->peerBzrtpVersion=10000;
1681 1682 1683 1684 1685 1686 1687 1688 1689
		if (zrtpContext->zrtpCallbacks.bzrtp_statusMessage!=NULL && zrtpContext->zrtpCallbacks.bzrtp_messageLevel>=BZRTP_MESSAGE_WARNING) { /* use warning level as the client may really wants to know this */
				zrtpContext->zrtpCallbacks.bzrtp_statusMessage(zrtpChannelContext->clientData, BZRTP_MESSAGE_WARNING, BZRTP_MESSAGE_PEERVERSIONOBSOLETE, (const char *)helloMessage->clientIdentifier);
		}
	} else if (strncmp(ZRTP_CLIENT_IDENTIFIERv1_1, (char *)helloMessage->clientIdentifier, 16)==0) { /* peer has the current version, everything is Ok */
		zrtpContext->peerBzrtpVersion=10100;
	} else { /* peer uses another lib, we're probably not LIME compliant, log it */
		zrtpContext->peerBzrtpVersion=0;
		if (zrtpContext->zrtpCallbacks.bzrtp_statusMessage!=NULL && zrtpContext->zrtpCallbacks.bzrtp_messageLevel>=BZRTP_MESSAGE_LOG) {
				zrtpContext->zrtpCallbacks.bzrtp_statusMessage(zrtpChannelContext->clientData, BZRTP_MESSAGE_LOG, BZRTP_MESSAGE_PEERNOTBZRTP, (const char *)helloMessage->clientIdentifier);
johan's avatar
johan committed
1690
		}
johan's avatar
johan committed
1691 1692
	}

1693 1694 1695 1696 1697 1698 1699
	/* now select mode according to context */
	if ((zrtpContext->peerSupportMultiChannel) == 1 && (zrtpContext->ZRTPSess != NULL)) { /* if we support multichannel and already have a ZRTPSess key, switch to multichannel mode */
		zrtpChannelContext->keyAgreementAlgo = ZRTP_KEYAGREEMENT_Mult;
		zrtpChannelContext->keyAgreementLength = 0;
	} else { /* we are not in multiStream mode, so we shall compute the hash of shared secrets */
		/* get from cache, if relevant, the retained secrets associated to the peer ZID */
		if (zrtpContext->cachedSecret.rs1 == NULL) { /* if we do not have already secret hashes in this session context. Note, they may be updated in cache file but they also will be in the context at the same time, so no need to parse the cache again */
johan's avatar
johan committed
1700
			bzrtp_getPeerAssociatedSecrets(zrtpContext, helloMessage->ZID);
1701
		}
1702

1703 1704 1705 1706 1707
		/* now compute the retained secret hashes (secrets may be updated but not their hash) as in rfc section 4.3.1 */
		if (zrtpContext->cachedSecret.rs1!=NULL) {
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.rs1, zrtpContext->cachedSecret.rs1Length, (uint8_t *)"Initiator", 9, 8, zrtpContext->initiatorCachedSecretHash.rs1ID);
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.rs1, zrtpContext->cachedSecret.rs1Length, (uint8_t *)"Responder", 9, 8, zrtpContext->responderCachedSecretHash.rs1ID);
		} else { /* we have no secret, generate a random */
jehan's avatar
jehan committed
1708 1709
			bctbx_rng_get(zrtpContext->RNGContext, zrtpContext->initiatorCachedSecretHash.rs1ID, 8);
			bctbx_rng_get(zrtpContext->RNGContext, zrtpContext->responderCachedSecretHash.rs1ID, 8);
1710
		}
1711

1712 1713 1714 1715
		if (zrtpContext->cachedSecret.rs2!=NULL) {
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.rs2, zrtpContext->cachedSecret.rs2Length, (uint8_t *)"Initiator", 9, 8, zrtpContext->initiatorCachedSecretHash.rs2ID);
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.rs2, zrtpContext->cachedSecret.rs2Length, (uint8_t *)"Responder", 9, 8, zrtpContext->responderCachedSecretHash.rs2ID);
		} else { /* we have no secret, generate a random */
jehan's avatar
jehan committed
1716 1717
			bctbx_rng_get(zrtpContext->RNGContext, zrtpContext->initiatorCachedSecretHash.rs2ID, 8);
			bctbx_rng_get(zrtpContext->RNGContext, zrtpContext->responderCachedSecretHash.rs2ID, 8);
1718
		}
1719 1720

		
1721 1722 1723 1724
		if (zrtpContext->cachedSecret.pbxsecret!=NULL) {
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.pbxsecret, zrtpContext->cachedSecret.pbxsecretLength, (uint8_t *)"Initiator", 9, 8, zrtpContext->initiatorCachedSecretHash.pbxsecretID);
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.pbxsecret, zrtpContext->cachedSecret.pbxsecretLength, (uint8_t *)"Responder", 9, 8, zrtpContext->responderCachedSecretHash.pbxsecretID);
		} else { /* we have no secret, generate a random */
jehan's avatar
jehan committed
1725 1726
			bctbx_rng_get(zrtpContext->RNGContext, zrtpContext->initiatorCachedSecretHash.pbxsecretID, 8);
			bctbx_rng_get(zrtpContext->RNGContext, zrtpContext->responderCachedSecretHash.pbxsecretID, 8);
1727
		}
1728

1729 1730 1731 1732
		if (zrtpContext->cachedSecret.auxsecret!=NULL) {
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.auxsecret, zrtpContext->cachedSecret.auxsecretLength, zrtpChannelContext->selfH[3], 32, 8, zrtpChannelContext->initiatorAuxsecretID);
			zrtpChannelContext->hmacFunction(zrtpContext->cachedSecret.auxsecret, zrtpContext->cachedSecret.auxsecretLength, zrtpChannelContext->peerH[3], 32, 8, zrtpChannelContext->responderAuxsecretID);
		} else { /* we have no secret, generate a random */
jehan's avatar
jehan committed
1733 1734
			bctbx_rng_get(zrtpContext->RNGContext, zrtpChannelContext->initiatorAuxsecretID, 8);
			bctbx_rng_get(zrtpContext->RNGContext, zrtpChannelContext->responderAuxsecretID, 8);
1735
		}
1736 1737 1738 1739

	}

	/* When in PreShared mode Derive ZRTPSess, s0 from the retained secret and then all the other keys */
1740
	if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) {
johan's avatar
johan committed
1741
		/*TODO*/
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
	} else if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) { /* when in Multistream mode, do nothing, will derive s0 from ZRTPSess when we know who is initiator */


	} else { /* when in DHM mode : Create the DHPart2 packet (that we then may change to DHPart1 if we ended to be the responder)*/
		bzrtpPacket_t *selfDHPartPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_DHPART2, &retval);
		if (retval != 0) {
			return retval; /* no need to free the Hello message as it is attached to the context, it will be freed when destroying it */
		}

		retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, selfDHPartPacket, 0); /* we don't care now about sequence number as we just need to build the message to be able to insert a hash of it into the commit packet */
		if (retval == 0) { /* ok, insert it in context as we need it to build the commit packet */
			zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID] = selfDHPartPacket;
		} else {
			return retval; /* no need to free the Hello message as it is attached to the context, it will be freed when destroying it */
		}
	}

	/* now respond to this Hello packet sending a Hello ACK */
1760
	helloACKPacket = bzrtp_createZrtpPacket(zrtpContext, zrtpChannelContext, MSGTYPE_HELLOACK, &retval);
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
	if (retval != 0) {
		return retval; /* no need to free the Hello message as it is attached to the context, it will be freed when destroying it */
	}
	retval = bzrtp_packetBuild(zrtpContext, zrtpChannelContext, helloACKPacket, zrtpChannelContext->selfSequenceNumber);
	if (retval != 0) {
		bzrtp_freeZrtpPacket(helloACKPacket);
		return retval;
	} else {
		/* send the message */
		zrtpContext->zrtpCallbacks.bzrtp_sendData(zrtpChannelContext->clientData, helloACKPacket->packetString, helloACKPacket->messageLength+ZRTP_PACKET_OVERHEAD);
		zrtpChannelContext->selfSequenceNumber++;
		bzrtp_freeZrtpPacket(helloACKPacket);
	}
	return 0;
}

/**
 * @brief After the DHPart1 or DHPart2 arrives from peer, validity check and shared secret computation
 * call this function to compute s0, KDF Context, ZRTPSess, 
 *
 * param[in]	zrtpContext			The context we are operation on(where to find the DHM context with the shared secret ready)
 * param[in]	zrtpChannelContext	The channel context we are operation on
 *
 * return 0 on success, error code otherwise
 */
int bzrtp_computeS0DHMMode(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext) {

	uint8_t *dataToHash; /* a buffer used to store concatened data to be hashed */
	uint16_t hashDataLength; /* Length of the buffer */
	uint16_t hashDataIndex; /* an index used while filling the buffer */

	uint8_t *ZIDi; /* a pointer to the 12 bytes string initiator's ZID */
	uint8_t *ZIDr; /* a pointer to the 12 bytes string responder's ZID */
1794 1795

	uint8_t *totalHash;
1796
	
1797 1798 1799 1800 1801 1802 1803
	uint8_t *s1=NULL; /* s1 is rs1 if we have it, rs2 otherwise, or null if we do not have rs2 too */
	uint32_t s1Length=0;
	uint8_t *s2=NULL; /* s2 is aux secret if we have it, null otherwise */
	uint32_t s2Length=0;
	uint8_t *s3=NULL; /* s3 is pbx secret if we have it, null otherwise */
	uint32_t s3Length=0;

1804 1805
	/* first compute the total_hash as in rfc section 4.4.1.4 
	 * total_hash = hash(Hello of responder || Commit || DHPart1 || DHPart2)
1806
	 * total_hash length depends on the agreed hash algo
1807
	 */
johan's avatar
johan committed
1808
	if (zrtpChannelContext->role == BZRTP_ROLE_RESPONDER) {
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
		hashDataLength = zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength
			+ zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength
			+ zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength
			+ zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength;
	
		dataToHash = (uint8_t *)malloc(hashDataLength*sizeof(uint8_t));
		hashDataIndex = 0;

		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength);
		hashDataIndex +=zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength;
		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength);
		hashDataIndex +=zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength;
		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength);
		hashDataIndex +=zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength;
		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength);

		ZIDi = zrtpContext->peerZID;
		ZIDr = zrtpContext->selfZID;

	} else { /* we are initiator */
		
		hashDataLength = zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength
			+ zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength
			+ zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength
			+ zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength;

		dataToHash = (uint8_t *)malloc(hashDataLength*sizeof(uint8_t));
		hashDataIndex = 0;

		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength);
		hashDataIndex +=zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength;
		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength);
		hashDataIndex +=zrtpChannelContext->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength;
		memcpy(dataToHash+hashDataIndex, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength);