1 /*
2  * libZRTP SDK library, implements the ZRTP secure VoIP protocol.
3  * Copyright (c) 2006-2009 Philip R. Zimmermann.  All rights reserved.
4  * Contact: http://philzimmermann.com
5  * For licensing and other legal details, see the file zrtp_legal.c.
6  *
7  * Viktor Krykun <v.krikun at zfoneproject.com>
8  */
9 
10 #include "zrtp.h"
11 
12 #define _ZTU_ "zrtp engine"
13 
14 /*!
15  * Data type for state-handlers: every state has a state handler
16  * function which is called by zrtp_process_srtp().
17  */
18 typedef zrtp_status_t state_handler_t( zrtp_stream_t* stream, zrtp_rtp_info_t* packet );
19 extern state_handler_t* state_handler[ZRTP_STATE_COUNT];
20 
21 extern zrtp_status_t _zrtp_machine_process_sasrelay(zrtp_stream_t *stream, zrtp_rtp_info_t *packet);
22 
23 static void _zrtp_machine_switch_to_error(zrtp_stream_t* stream);
24 static zrtp_status_t _zrtp_machine_enter_initiatingclear(zrtp_stream_t* stream);
25 static zrtp_status_t _zrtp_machine_enter_clear(zrtp_stream_t* stream);
26 static zrtp_status_t _zrtp_machine_enter_pendingerror(zrtp_stream_t *stream, zrtp_protocol_error_t code);
27 
28 zrtp_status_t _zrtp_machine_process_hello(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
29 zrtp_status_t _zrtp_machine_process_goclear(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
30 
31 static void _send_helloack(zrtp_stream_t* stream);
32 static void _send_goclearack(zrtp_stream_t* stream);
33 
34 zrtp_status_t _zrtp_machine_start_send_and_resend_hello(zrtp_stream_t* stream);
35 static zrtp_status_t _zrtp_machine_start_send_and_resend_goclear(zrtp_stream_t* stream);
36 static zrtp_status_t _zrtp_machine_start_send_and_resend_errorack(zrtp_stream_t* stream);
37 static zrtp_status_t _zrtp_machine_start_send_and_resend_error(zrtp_stream_t* stream);
38 
39 void _clear_stream_crypto(zrtp_stream_t* stream);
40 
41 
42 /*===========================================================================*/
43 // MARK: ===> Main ZRTP interfaces
44 /*===========================================================================*/
45 
46 /*----------------------------------------------------------------------------*/
zrtp_process_rtcp(zrtp_stream_t * stream,char * packet,unsigned int * length)47 zrtp_status_t zrtp_process_rtcp(zrtp_stream_t *stream, char* packet, unsigned int* length)
48 {
49 
50     /*
51 	 * In transition states, drop outgoing packets. In SECURE state, encrypt
52        outgoing packets.  In all other states leave them unchanged.
53 	 */
54 
55     if (stream) {
56 		switch (stream->state)
57 		{
58 		case ZRTP_STATE_START_INITIATINGSECURE:
59 		case ZRTP_STATE_INITIATINGSECURE:
60 		case ZRTP_STATE_WAIT_CONFIRM1:
61 		case ZRTP_STATE_WAIT_CONFIRMACK:
62 		case ZRTP_STATE_PENDINGSECURE:
63 		case ZRTP_STATE_WAIT_CONFIRM2:
64 		case ZRTP_STATE_PENDINGCLEAR:
65 			return zrtp_status_drop;
66 
67 		case ZRTP_STATE_SASRELAYING:
68 		case ZRTP_STATE_SECURE:
69 		{
70 			zrtp_rtp_info_t info;
71 
72 			if (*length < RTCP_HDR_SIZE) {
73 				return zrtp_status_fail;
74 			}
75 
76 			zrtp_memset(&info, 0, sizeof(info));
77 			info.packet = packet;
78 			info.length = length;
79 			info.seq = 0; /*sequence number will be generated in zrtp_srtp_protect_rtcp()*/
80 			info.ssrc = (uint32_t) *(packet+sizeof(uint32_t));
81 
82 			return _zrtp_protocol_encrypt(stream->protocol, &info, 0);
83 		}
84 
85 		default:
86 		return zrtp_status_ok;
87 		}
88     }
89 
90     return zrtp_status_ok;
91 }
92 
93 /*----------------------------------------------------------------------------*/
zrtp_process_srtcp(zrtp_stream_t * stream,char * packet,unsigned int * length)94 zrtp_status_t zrtp_process_srtcp(zrtp_stream_t *stream, char* packet, unsigned int* length)
95 {
96 
97     /*
98 	 * In transition states, drop incoming packets. In SECURE state, decrypt
99 	 * incoming packets. In all other states leave them unchanged.
100 	 */
101 
102     if (stream) {
103 		switch (stream->state)
104 		{
105 		case ZRTP_STATE_INITIATINGCLEAR:
106 			case ZRTP_STATE_PENDINGCLEAR:
107 			case ZRTP_STATE_INITIATINGSECURE:
108 			case ZRTP_STATE_PENDINGSECURE:
109 				return zrtp_status_drop;
110 
111 			case ZRTP_STATE_SECURE:
112 			case ZRTP_STATE_SASRELAYING:
113 			{
114 				zrtp_rtp_info_t info;
115 
116 				if (*length < RTCP_HDR_SIZE) {
117 					return zrtp_status_fail;
118 				}
119 
120 				zrtp_memset(&info, 0, sizeof(info));
121 				info.packet = packet;
122 				info.length = length;
123 				info.seq = 0; /*sequence number will be determined from packet in zrtp_srtp_unprotect_rtcp()*/
124 				info.ssrc = (uint32_t) *(packet+sizeof(uint32_t));
125 
126 				return _zrtp_protocol_decrypt(stream->protocol, &info, 0);
127 			}
128 
129 			default:
130 				return zrtp_status_ok;
131 		}
132     }
133 
134     return zrtp_status_ok;
135 }
136 
137 /*----------------------------------------------------------------------------*/
zrtp_process_rtp(zrtp_stream_t * stream,char * packet,unsigned int * length)138 zrtp_status_t zrtp_process_rtp(zrtp_stream_t *stream, char* packet, unsigned int* length)
139 {
140 	zrtp_rtp_info_t info;
141 
142 	if (!stream || !packet || !length) {
143 		return zrtp_status_bad_param;
144 	}
145 
146 	/* Skip packet processing within uninitiated stream */
147 	if ((stream->state < ZRTP_STATE_START) || (stream->state > ZRTP_STATE_NO_ZRTP)) {
148 		return zrtp_status_ok;
149 	}
150 
151 	/* Prepare RTP packet: detect type and other options */
152 	if (zrtp_status_ok != _zrtp_packet_preparse(stream, packet, length, &info, 0)) {
153 		return zrtp_status_fail;
154 	}
155 
156 	/* Drop packets in transition states and encrypt in SECURE state */
157 	switch (stream->state)
158 	{
159 	case ZRTP_STATE_START_INITIATINGSECURE:
160 	case ZRTP_STATE_INITIATINGSECURE:
161 	case ZRTP_STATE_WAIT_CONFIRM1:
162 	case ZRTP_STATE_WAIT_CONFIRMACK:
163 	case ZRTP_STATE_PENDINGSECURE:
164 	case ZRTP_STATE_WAIT_CONFIRM2:
165 	case ZRTP_STATE_PENDINGCLEAR:
166 		if (ZRTP_NONE == info.type) {
167 			/* Add dropped media to the entropy hash */
168 			ZRTP_LOG(1,(_ZTU_,"Add %d bytes of entropy to the RNG pool.\n", *length));
169 			zrtp_entropy_add(stream->zrtp, (unsigned char*)packet, *length);
170 
171 			return zrtp_status_drop;
172 		}
173 		break;
174 
175 	case ZRTP_STATE_SASRELAYING:
176 	case ZRTP_STATE_SECURE:
177 		if (ZRTP_NONE == info.type) {
178 			return _zrtp_protocol_encrypt(stream->protocol, &info, 1);
179 		}
180 		break;
181 
182 	default:
183 		break;
184 	}
185 
186 	return zrtp_status_ok;
187 }
188 
189 /*----------------------------------------------------------------------------*/
190 extern int _send_message(zrtp_stream_t* stream, zrtp_msg_type_t type, const void* message, uint32_t ssrc);
zrtp_process_srtp(zrtp_stream_t * stream,char * packet,unsigned int * length)191 zrtp_status_t zrtp_process_srtp(zrtp_stream_t *stream, char* packet, unsigned int* length)
192 {
193     zrtp_rtp_info_t info;
194 	zrtp_status_t s = zrtp_status_ok;
195 
196     if (!stream || !packet || !length) {
197 		return zrtp_status_bad_param;
198 	}
199 
200 	if (*length <= RTP_HDR_SIZE) {
201 		return zrtp_status_bad_param;
202 	}
203 
204 	/* Preparse RTP packet: detect type and other options */
205 	s = _zrtp_packet_preparse(stream, packet, length, &info, 1);
206 	if (zrtp_status_ok != s) {
207 		return s;
208 	}
209 
210 	/*************************************************************************/
211 	/* For Zfone3 Compatibility */
212 	if (ZRTP_ZFONEPING == info.type) {
213 		zrtp_packet_zfoneping_t* ping = (zrtp_packet_zfoneping_t*) info.message;
214 		zrtp_packet_zfonepingack_t pingack;
215 
216 		zrtp_memcpy(pingack.version, ZRTP_ZFONE_PROTOCOL_VERSION, 4);
217 		zrtp_memcpy(pingack.endpointhash, stream->session->zid.buffer, sizeof(pingack.endpointhash));
218 		zrtp_memcpy(pingack.peerendpointhash, ping->endpointhash, sizeof(pingack.endpointhash));
219 		pingack.peerssrc = info.ssrc;
220 
221 		_zrtp_packet_fill_msg_hdr( stream,
222 								   ZRTP_ZFONEPINGACK,
223 								   sizeof(zrtp_packet_zfonepingack_t) - sizeof(zrtp_msg_hdr_t),
224 								   &pingack.hdr);
225 
226 		_zrtp_packet_send_message(stream, ZRTP_ZFONEPINGACK, &pingack);
227 		return zrtp_status_drop;
228 	}
229 	/*************************************************************************/
230 
231 	/* Skip packet processing within non-started stream */
232 	if ((stream->state < ZRTP_STATE_START) || (stream->state > ZRTP_STATE_NO_ZRTP)) {
233 		return (ZRTP_NONE == info.type) ? zrtp_status_ok : zrtp_status_drop;
234 	}
235 
236 	/*
237 	 * This mutex should protect stream data against asynchr. calls e.g.:
238 	 * zrtp_stream_secure(), zrtp_stream_clear() etc. Media packet handlers
239 	 * don't change any internal data, so this applies only to ZRTP messages.
240 	 */
241 	if (info.type != ZRTP_NONE) {
242 		zrtp_mutex_lock(stream->stream_protector);
243 	}
244 
245 	/* Extra protection. We need protocol to handle ZRTP messages in following states. */
246 	switch (stream->state)
247 	{
248 	case ZRTP_STATE_INITIATINGSECURE:
249 	case ZRTP_STATE_WAIT_CONFIRM1:
250 	case ZRTP_STATE_WAIT_CONFIRMACK:
251 	case ZRTP_STATE_PENDINGSECURE:
252 	case ZRTP_STATE_WAIT_CONFIRM2:
253 	case ZRTP_STATE_SECURE:
254 	case ZRTP_STATE_SASRELAYING:
255 		if (!stream->protocol) {
256 			if (info.type != ZRTP_NONE) {
257 				zrtp_mutex_unlock(stream->stream_protector);
258 			}
259 			return zrtp_status_fail;
260 		}
261 	default:
262 		break;
263 	}
264 
265 	/* Handle Error packet from any state */
266 	if (ZRTP_ERROR == info.type && stream->state > ZRTP_STATE_START)
267 	{
268 		switch (stream->state)
269 		{
270 		case ZRTP_STATE_NONE:
271 		case ZRTP_STATE_ACTIVE:
272 		case ZRTP_STATE_SECURE:
273 		case ZRTP_STATE_PENDINGERROR:
274 		case ZRTP_STATE_INITIATINGERROR:
275 		case ZRTP_STATE_NO_ZRTP:
276 		    break;
277 		default:
278 			{
279 				zrtp_packet_Error_t* error = (zrtp_packet_Error_t*) info.message;
280 				_zrtp_machine_enter_pendingerror(stream, zrtp_ntoh32(error->code));
281 			} break;
282 		}
283 	}
284 
285 	/* Process packet by state-machine according to packet type and current protocol state */
286 	if (state_handler[stream->state]) {
287 		s = state_handler[stream->state](stream, &info);
288 	}
289 
290 	/* Unlock stream mutex for a ZRTP message packet. See comments above. */
291 	if (info.type != ZRTP_NONE) {
292 		s = zrtp_status_drop;
293 		zrtp_mutex_unlock(stream->stream_protector);
294 	}
295 
296 	return s;
297 }
298 
299 /*----------------------------------------------------------------------------*/
zrtp_stream_start(zrtp_stream_t * stream,uint32_t ssrc)300 zrtp_status_t zrtp_stream_start(zrtp_stream_t* stream, uint32_t ssrc)
301 {
302 	zrtp_status_t s = zrtp_status_ok;
303 	 /*
304 	  * (ZRTP stream starts from START state and HELLO packets resending.
305 	  * Stream can be started from START, ERROR or NOZRTP states only.)
306 	  */
307 	ZRTP_LOG(3,(_ZTU_,"START STREAM ID=%u mode=%s state=%s.\n",
308 				stream->id, zrtp_log_mode2str(stream->mode), zrtp_log_state2str(stream->state)));
309 
310 	if ( (ZRTP_STATE_ACTIVE != stream->state) &&
311 		 (ZRTP_STATE_ERROR != stream->state) &&
312 		 (ZRTP_STATE_NO_ZRTP != stream->state)) {
313 		ZRTP_LOG(1,(_ZTU_,"ERROR! Can't start Stream ID=%u from %s state.\n",
314 					stream->id, zrtp_log_state2str(stream->state)));
315 		s = zrtp_status_wrong_state;
316 	} else {
317 		stream->media_ctx.ssrc = zrtp_hton32(ssrc);
318 
319 		_zrtp_change_state(stream, ZRTP_STATE_START);
320 		_zrtp_machine_start_send_and_resend_hello(stream);
321 	}
322 
323 	return s;
324 }
325 
326 /*----------------------------------------------------------------------------*/
zrtp_stream_stop(zrtp_stream_t * stream)327 zrtp_status_t zrtp_stream_stop(zrtp_stream_t* stream)
328 {
329 	zrtp_status_t s = zrtp_status_ok;
330 	/*
331 	 * Stop all packet replays, deinitialize crypto data and prepare the stream
332 	 * for the next use. The stream can be terminated from any protocol state.
333 	 */
334 	 ZRTP_LOG(3,(_ZTU_,"STOP STREAM ID=%u mode=%s state=%s.\n",
335 				stream->id, zrtp_log_mode2str(stream->mode), zrtp_log_state2str(stream->state)));
336 
337 	/*
338 	 * Unlink deleted stream for the peer MiTM stream if necessary. It may
339 	 * prevent some recae-conditions as we always test for NULL before
340 	 * accessing linked_mitm.
341 	 */
342 	if (stream->linked_mitm) {
343 		stream->linked_mitm->linked_mitm = NULL;
344 	}
345 
346     if (stream->state != ZRTP_STATE_NONE) {
347 		/*
348 		 * This function can be called in parallel to the main processing loop
349 		 * - protect internal stream data.
350 		 */
351 		zrtp_mutex_lock(stream->stream_protector);
352 
353 		_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
354 		if (stream->zrtp->cb.sched_cb.on_wait_call_later) {
355 			stream->zrtp->cb.sched_cb.on_wait_call_later(stream);
356 		}
357 
358 		_clear_stream_crypto(stream);
359 
360 		zrtp_mutex_unlock(stream->stream_protector);
361 		zrtp_mutex_destroy(stream->stream_protector);
362 
363 		zrtp_memset(stream, 0, sizeof(zrtp_stream_t));
364 
365 		stream->mode = ZRTP_STREAM_MODE_UNKN;
366 
367 		_zrtp_change_state(stream, ZRTP_STATE_NONE);
368     } else {
369 		s = zrtp_status_wrong_state;
370 	}
371 
372 	return s;
373 }
374 
375 /*----------------------------------------------------------------------------*/
zrtp_stream_clear(zrtp_stream_t * stream)376 zrtp_status_t zrtp_stream_clear(zrtp_stream_t *stream)
377 {
378 	/*
379 	 * This function can be called for two reasons: either our user is
380 	 * initiating the go-clear ritual or we accepting that ritual as
381 	 * initiated by the other end of the line. If our user initiates the
382 	 * go-clear process libzrtp switches to INITIATING_CLEAR and runs
383 	 * GoClear replays. The go-clear ritual can be started from SECURE state
384 	 * only. If the other end of the line is initiating and this function is
385 	 * being called to accept the go-clear procedure - protocol transites to
386 	 * CLEAR state imediately. One can accept go-clear from PENDING CLEAR
387 	 * state only. See state-macine diagram for more information.
388 	 */
389 	zrtp_status_t s = zrtp_status_fail;
390 
391 	/* This function can be called in parallel to the main processing loop - protect stream data. */
392 	zrtp_mutex_lock(stream->stream_protector);
393 
394 	ZRTP_LOG(3,(_ZTU_,"CLEAR STREAM ID=%u mode=%s state=%s.\n",
395 				stream->id, zrtp_log_mode2str(stream->mode), zrtp_log_state2str(stream->state)));
396 
397     switch (stream->state)
398     {
399 	case ZRTP_STATE_SECURE:
400 		/* Clearing ritual can't be started if "allow clear" is disabled */
401 		if (stream->session->profile.allowclear) {
402 			s = _zrtp_machine_enter_initiatingclear(stream);
403 		}
404 		break;
405 	case ZRTP_STATE_PENDINGCLEAR:
406 		s = _zrtp_machine_enter_clear(stream);
407 		break;
408 	default:
409 		break;
410     }
411 
412 	zrtp_mutex_unlock(stream->stream_protector);
413 
414 	return s;
415 }
416 
417 /*----------------------------------------------------------------------------*/
_initiating_secure(zrtp_stream_t * stream,zrtp_retry_task_t * task)418 void _initiating_secure(zrtp_stream_t *stream, zrtp_retry_task_t* task)
419 {
420 	/*
421 	 * In accordance with the ZRTP standard, there can be multiple simultaneous
422 	 * DH streams, as well as preshared streams.
423 	 *
424 	 * Before entering the INITIATING_SECURE state, we check several conditions.
425 	 * For details see \doc\img\odg\zrtp_streams.odg and zrtp_statemach.odg)
426 	 */
427 
428 	/* The first call to this function is already protected by a mutex in zrtp_process_srtp() */
429 	uint8_t use_mutex = (task->_retrys > 0);
430 
431 	if (!task->_is_enabled) {
432 		return;
433 	}
434 
435 	if (use_mutex) {
436 		zrtp_mutex_lock(stream->stream_protector);
437 	}
438 
439 	ZRTP_LOG(3,(_ZTU_,"\tInitiating Secure iteration... ID=%u.\n", stream->id));
440 
441 	/* Skip the last replay after switching to another state to avoid unwanted replays */
442 	if (stream->state <= ZRTP_STATE_START_INITIATINGSECURE)
443 	{
444 		stream->mode = _zrtp_define_stream_mode(stream);
445 		ZRTP_LOG(3,(_ZTU_,"\tGot mode=%s. Check approval of starting.\n", zrtp_log_mode2str(stream->mode)));
446 		if (!_zrtp_can_start_stream(stream, &stream->concurrent, stream->mode))
447 		{
448 			if (task->_retrys > ZRTP_PROCESS_T1_MAX_COUNT) {
449 				ZRTP_LOG(3,(_ZTU_,"\tInitiating Secure. Max retransmissions count reached"
450 							 "for stream ID=%u.\n", stream->id));
451 
452 				_zrtp_machine_enter_initiatingerror(stream, zrtp_error_timeout, 0);
453 			} else {
454 				ZRTP_LOG(3,(_ZTU_,"\tInitiating Secure. stream ID=%u is DH but one more DH"
455 							" stream is in progress - waiting...\n", stream->id));
456 
457 				task->_retrys++;
458 				if (stream->zrtp->cb.sched_cb.on_call_later) {
459 					stream->zrtp->cb.sched_cb.on_call_later(stream, task);
460 				}
461 			}
462 		}
463 		else
464 		{
465 			ZRTP_LOG(3,(_ZTU_,"\tMode=%s Cccepted. Starting ZRTP Initiator Protocol.\n", zrtp_log_mode2str(stream->mode)));
466 			_zrtp_cancel_send_packet_later(stream, ZRTP_PROCESS);
467 			_zrtp_machine_enter_initiatingsecure(stream);
468 		}
469 	}
470 
471 	if (use_mutex) {
472 		zrtp_mutex_unlock(stream->stream_protector);
473 	}
474 }
475 
_zrtp_machine_start_initiating_secure(zrtp_stream_t * stream)476 zrtp_status_t _zrtp_machine_start_initiating_secure(zrtp_stream_t *stream)
477 {
478 	/*
479 	 * This function creates a task to do retries of the first packet in the
480 	 * "Going secure" procedure, and then _initiating_secure() will start
481 	 * protocol.
482 	 */
483 	zrtp_retry_task_t* task = &stream->messages.dh_task;
484 	task->_is_enabled = 1;
485 	task->_retrys = 0;
486 	task->callback = _initiating_secure;
487 	task->timeout = ZRTP_PROCESS_T1;
488 
489 	/*
490 	 * Prevent race conditions on starting multiple streams.
491 	 */
492 	zrtp_mutex_lock(stream->session->init_protector);
493 
494 	_zrtp_change_state(stream, ZRTP_STATE_START_INITIATINGSECURE);
495 	_initiating_secure(stream, task);
496 
497 	zrtp_mutex_unlock(stream->session->init_protector);
498 
499 	return zrtp_status_ok;
500 }
501 
502 
zrtp_stream_secure(zrtp_stream_t * stream)503 zrtp_status_t zrtp_stream_secure(zrtp_stream_t *stream)
504 {
505 	/*
506 	 * Wrapper function for going into secure mode.  It can be initiated in
507 	 * parallel to the main processing loop.  The internal stream data has to
508 	 * be protected by mutex.
509 	 */
510 
511 	zrtp_status_t s = zrtp_status_fail;
512 
513 	ZRTP_LOG(3,(_ZTU_,"SECURE STREAM ID=%u mode=%s state=%s.\n",
514 				stream->id, zrtp_log_mode2str(stream->mode), zrtp_log_state2str(stream->state)));
515 
516 	zrtp_mutex_lock(stream->stream_protector);
517 
518     /* Limit ZRTP Session initiation procedure according to the license */
519 	if ( (stream->state == ZRTP_STATE_CLEAR) && ZRTP_PASSIVE1_TEST(stream)) {
520 		s = _zrtp_machine_start_initiating_secure(stream);
521 	} else {
522 		ZRTP_LOG(1,(_ZTU_,"\tWARNING! Can't Start Stream from %s state and with %d license mode. ID=%u\n",
523 					zrtp_log_state2str(stream->state), stream->zrtp->lic_mode, stream->id));
524 
525 		if (!ZRTP_PASSIVE1_TEST(stream)) {
526 			if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event ) {
527 				stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_PASSIVE_RESTRICTION);
528 			}
529 		}
530 	}
531 
532 	zrtp_mutex_unlock(stream->stream_protector);
533 
534     return s;
535 }
536 
537 
538 /*===========================================================================*/
539 /*		State handlers														 */
540 /*===========================================================================*/
541 
542 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_start(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)543 zrtp_status_t _zrtp_machine_process_while_in_start( zrtp_stream_t* stream,
544 													zrtp_rtp_info_t* packet)
545 {
546 	zrtp_status_t s = zrtp_status_ok;
547 
548 	switch (packet->type)
549 	{
550 	case ZRTP_HELLO:
551 		s = _zrtp_machine_process_hello(stream, packet);
552 		if (zrtp_status_ok != s) {
553 			ZRTP_LOG(1,(_ZTU_,"\tERROR! _zrtp_machine_process_hello() failed with status=%d. ID=%u\n", s, stream->id));
554 			break; /* Just stay in START state. */
555 		}
556 
557 		/* Now we have ZIDs for both sides and can upload secrets from the cache */
558 		s = _zrtp_prepare_secrets(stream->session);
559 		if (zrtp_status_ok != s) {
560 			ZRTP_LOG(1,(_ZTU_,"\tERROR! _zrtp_prepare_secrets() failed with status=%d. ID=%u\n", s, stream->id));
561 			break; /* Just stay in START state. */
562 		}
563 
564 		_send_helloack(stream);
565 		_zrtp_change_state(stream, ZRTP_STATE_WAIT_HELLOACK);
566 		break;
567 
568 	case ZRTP_HELLOACK:
569 		_zrtp_cancel_send_packet_later(stream, ZRTP_HELLO);
570 		_zrtp_change_state(stream, ZRTP_STATE_WAIT_HELLO);
571 		break;
572 
573 	default:
574 		break;
575 	}
576 
577 	return s;
578 }
579 
580 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_wait4hello(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)581 zrtp_status_t _zrtp_machine_process_while_in_wait4hello( zrtp_stream_t* stream,
582 														 zrtp_rtp_info_t* packet)
583 {
584 	zrtp_status_t s = zrtp_status_ok;
585 
586 	switch (packet->type)
587 	{
588 	case ZRTP_HELLO:
589 		s = _zrtp_machine_process_hello(stream, packet);
590 		if (zrtp_status_ok != s) {
591 			ZRTP_LOG(1,(_ZTU_,"\tERROR! _zrtp_machine_process_hello()2 failed with status=%d. ID=%u\n", s, stream->id));
592 			break; /* Just stay in the current state. */
593 		}
594 
595 		/* Now we have ZIDs for both sides and can upload secrets from the cache */
596 		s = _zrtp_prepare_secrets(stream->session);
597 		if (zrtp_status_ok != s) {
598 			ZRTP_LOG(1,(_ZTU_,"\tERROR! _zrtp_prepare_secrets()2 failed with status=%d. ID=%u\n", s, stream->id));
599 			break; /* Just stay in the current state. */
600 		}
601 
602 		/* Start initiating the secure state if "autosecure" is enabled */
603 		if ((stream->session->profile.autosecure) && ZRTP_PASSIVE1_TEST(stream)) {
604 			if (!stream->session->profile.discovery_optimization) {
605 				_send_helloack(stream); /* Response with HelloAck before start computing DH value */
606 			}
607 			s = _zrtp_machine_start_initiating_secure(stream);
608 		} else {
609 			_send_helloack(stream);
610 
611 			if (!ZRTP_PASSIVE1_TEST(stream)) {
612 				if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
613 					stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_PASSIVE_RESTRICTION);
614 				}
615 				ZRTP_LOG(2,(_ZTU_,"\tINFO: Switching to Clear due to Active/Passive restrictions.\n"));
616 			}
617 
618 			s = _zrtp_machine_enter_clear(stream);
619 		}
620 
621 		break;
622 
623 	default:
624 		break;
625 	}
626 
627 	return s;
628 }
629 
630 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_wait4helloack(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)631 zrtp_status_t _zrtp_machine_process_while_in_wait4helloack( zrtp_stream_t* stream,
632 														    zrtp_rtp_info_t* packet)
633 {
634 	zrtp_status_t status = zrtp_status_ok;
635 
636 	switch (packet->type)
637 	{
638 	case ZRTP_HELLO:
639 		_send_helloack(stream);
640 		break;
641 
642 	case ZRTP_COMMIT:
643 	{
644 		/* Passive Initiator can't talk to anyone */
645 		if (ZRTP_PASSIVE2_TEST(stream))
646 		{
647 			zrtp_statemachine_type_t role = _zrtp_machine_preparse_commit(stream, packet);
648 			if (ZRTP_STATEMACHINE_RESPONDER == role) {
649 				_zrtp_cancel_send_packet_later(stream, ZRTP_HELLO);
650 				status = _zrtp_machine_enter_pendingsecure(stream, packet);
651 			} else if (ZRTP_STATEMACHINE_INITIATOR == role) {
652 				_zrtp_cancel_send_packet_later(stream, ZRTP_HELLO);
653 				status = _zrtp_machine_start_initiating_secure(stream);
654 			} else {
655 				status = zrtp_status_fail;
656 			}
657 		} else {
658 			ZRTP_LOG(2,(_ZTU_,"\tERROR: The endpoint is in passive mode and Signaling Initiator -"
659 						" can't handle connections from anyone. ID=%u\n", stream->id));
660 			if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
661 				stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_PASSIVE_RESTRICTION);
662 			}
663 			_zrtp_machine_enter_initiatingerror(stream, zrtp_error_service_unavail, 1);
664 		}
665 	} break;
666 
667 	case ZRTP_HELLOACK:
668 		_zrtp_cancel_send_packet_later(stream, ZRTP_HELLO);
669 
670 		/* Start initiating the secure state if "autosecure" is enabled */
671 		if ((stream->session->profile.autosecure) && ZRTP_PASSIVE1_TEST(stream)) {
672 			status = _zrtp_machine_start_initiating_secure(stream);
673 		} else {
674 			if (!ZRTP_PASSIVE1_TEST(stream)) {
675 				if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
676 					stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_PASSIVE_RESTRICTION);
677 				}
678 				ZRTP_LOG(2,(_ZTU_,"\tINFO: Switching to Clear due to Active/Passive restrictions.\n"));
679 			}
680 			status = _zrtp_machine_enter_clear(stream);
681 		}
682 
683 		break;
684 
685 	default:
686 		break;
687 	}
688 
689 	return status;
690 }
691 
692 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_clear(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)693 zrtp_status_t _zrtp_machine_process_while_in_clear( zrtp_stream_t* stream,
694 												    zrtp_rtp_info_t* packet)
695 {
696 	zrtp_status_t s = zrtp_status_ok;
697 
698 	switch (packet->type)
699 	{
700 	case ZRTP_GOCLEAR:
701 		_send_goclearack(stream);
702 		break;
703 
704 	case ZRTP_HELLO:
705 		_send_helloack(stream);
706 		break;
707 
708 	case ZRTP_COMMIT:
709 	{
710 		zrtp_statemachine_type_t role = _zrtp_machine_preparse_commit(stream, packet);
711 		if (ZRTP_STATEMACHINE_RESPONDER == role) {
712 			s = _zrtp_machine_enter_pendingsecure(stream, packet);
713 		} else if (ZRTP_STATEMACHINE_INITIATOR == role) {
714 			s = _zrtp_machine_start_initiating_secure(stream);
715 		} else {
716 			s = zrtp_status_fail;
717 		}
718 	} break;
719 
720 	default:
721 		break;
722 	}
723 
724 	return s;
725 }
726 
727 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_initiatingclear(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)728 zrtp_status_t _zrtp_machine_process_while_in_initiatingclear( zrtp_stream_t* stream,
729 															  zrtp_rtp_info_t* packet)
730 {
731 	zrtp_status_t s = zrtp_status_ok;
732 
733 	switch (packet->type)
734 	{
735 	case ZRTP_GOCLEARACK:
736 	case ZRTP_COMMIT:
737 		s = _zrtp_machine_enter_clear(stream);
738 		break;
739 
740 	case ZRTP_NONE:
741 		s = zrtp_status_drop;
742 		break;
743 
744 	default:
745 		break;
746 	}
747 
748 	return s;
749 }
750 
751 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_pendingclear(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)752 zrtp_status_t _zrtp_machine_process_while_in_pendingclear( zrtp_stream_t* stream,
753 														   zrtp_rtp_info_t* packet)
754 {
755 	zrtp_status_t s = zrtp_status_ok;
756 
757 	switch (packet->type)
758 	{
759 	case ZRTP_GOCLEAR:
760 		_send_goclearack(stream);
761 		break;
762 
763 	case ZRTP_COMMIT:
764 	{
765 		zrtp_statemachine_type_t role = _zrtp_machine_preparse_commit(stream, packet);
766 		if (ZRTP_STATEMACHINE_RESPONDER == role) {
767 			s = _zrtp_machine_enter_pendingsecure(stream, packet);
768 		} else if (ZRTP_STATEMACHINE_INITIATOR == role) {
769 			s = _zrtp_machine_start_initiating_secure(stream);
770 		} else {
771 			s = zrtp_status_fail;
772 		}
773 	} break;
774 
775 	default:
776 		break;
777 	}
778 
779 	return s;
780 }
781 
782 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_start_initiatingsecure(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)783 zrtp_status_t _zrtp_machine_process_while_in_start_initiatingsecure( zrtp_stream_t* stream,
784 																	 zrtp_rtp_info_t* packet)
785 {
786 	zrtp_status_t s = zrtp_status_ok;
787 
788 	switch (packet->type)
789 	{
790 	case ZRTP_HELLO:
791 		_send_helloack(stream);
792 		break;
793 
794 	case ZRTP_COMMIT:
795 	{
796 		zrtp_statemachine_type_t role = _zrtp_machine_preparse_commit(stream, packet);
797 		if (ZRTP_STATEMACHINE_RESPONDER == role) {
798 			_zrtp_cancel_send_packet_later(stream, ZRTP_PROCESS);
799 			s = _zrtp_machine_enter_pendingsecure(stream, packet);
800 		} else {
801 			s = zrtp_status_fail;
802 		}
803 	} break;
804 
805 	default:
806 		break;
807 	}
808 
809 	return s;
810 }
811 
812 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_secure(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)813 zrtp_status_t _zrtp_machine_process_while_in_secure( zrtp_stream_t* stream,
814 													 zrtp_rtp_info_t* packet)
815 {
816 	zrtp_status_t s = zrtp_status_ok;
817 
818 	switch (packet->type)
819 	{
820 	case ZRTP_CONFIRM2:
821 		_zrtp_packet_send_message(stream, ZRTP_CONFIRM2ACK, NULL);
822 		break;
823 
824 	case ZRTP_SASRELAY:
825 		/*
826 		 * _zrtp_machine_process_sasrelay() updates SAS, sends events and does
827 		 * other things if SAS transferring is allowed
828 		 */
829 		s = _zrtp_machine_process_sasrelay(stream, packet);
830 		if (zrtp_status_ok == s) {
831 			_zrtp_packet_send_message(stream, ZRTP_RELAYACK, NULL);
832 		}
833 		break;
834 
835 	case ZRTP_GOCLEAR:
836 		s = _zrtp_machine_process_goclear(stream, packet);
837 		if (zrtp_status_ok == s) {
838 			s = _zrtp_machine_enter_pendingclear(stream);
839 			_send_goclearack(stream);
840 		}
841 		break;
842 
843 	case ZRTP_NONE:
844 		s = _zrtp_protocol_decrypt(stream->protocol, packet, 1);
845 		break;
846 
847 	default:
848 		break;
849 	}
850 
851 	return s;
852 }
853 
854 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_initiatingerror(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)855 zrtp_status_t _zrtp_machine_process_while_in_initiatingerror( zrtp_stream_t* stream,
856 															  zrtp_rtp_info_t* packet)
857 {
858 	switch (packet->type)
859 	{
860 	case ZRTP_ERROR:
861 		_zrtp_machine_enter_pendingerror(stream, ((zrtp_packet_Error_t*) packet->message)->code );
862 		break;
863 
864 	case ZRTP_ERRORACK:
865 		_zrtp_machine_switch_to_error(stream);
866 		break;
867 
868 	default:
869 		break;
870 	}
871 
872 	return zrtp_status_ok;
873 }
874 
875 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_while_in_nozrtp(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)876 zrtp_status_t _zrtp_machine_process_while_in_nozrtp( zrtp_stream_t* stream,
877 													 zrtp_rtp_info_t* packet)
878 {
879 	zrtp_status_t s = zrtp_status_ok;
880 
881 	switch (packet->type)
882 	{
883 		case ZRTP_HELLO:
884 			s = _zrtp_machine_process_hello(stream, packet);
885 			if (zrtp_status_ok != s) {
886 				ZRTP_LOG(1,(_ZTU_,"\tERROR! _zrtp_machine_process_hello()3 failed with status=%d ID=%u.\n", s, stream->id));
887 				break;
888 			}
889 
890 			_zrtp_change_state(stream, ZRTP_STATE_START);
891 			_zrtp_machine_start_send_and_resend_hello(stream);
892 			break;
893 
894 		case ZRTP_COMMIT: /* this logic should be similar to Commit handler in ZRTP_STATE_WAIT_HELLOACK state */
895 		{
896 			/* Passive Initiator can't talk to anyone */
897 			if (ZRTP_PASSIVE2_TEST(stream))
898 			{
899 				zrtp_statemachine_type_t role = _zrtp_machine_preparse_commit(stream, packet);
900 				if (ZRTP_STATEMACHINE_RESPONDER == role) {
901 					s = _zrtp_machine_enter_pendingsecure(stream, packet);
902 				} else if (ZRTP_STATEMACHINE_INITIATOR == role) {
903 					s = _zrtp_machine_start_initiating_secure(stream);
904 				} else {
905 					s = zrtp_status_fail;
906 				}
907 			} else {
908 				ZRTP_LOG(2,(_ZTU_,"\tERROR: The endpoint is in passive mode and Signaling Initiator -"
909 							" can't handle connections from anyone. ID=%u\n", stream->id));
910 				if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event ) {
911 					stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_PASSIVE_RESTRICTION);
912 				}
913 				_zrtp_machine_enter_initiatingerror(stream, zrtp_error_service_unavail, 1);
914 			}
915 		} break;
916 
917 		default:
918 			break;
919 	}
920 
921 	return s;
922 }
923 
924 
925 /* Initiator logic */
926 extern zrtp_status_t _zrtp_machine_process_while_in_initiatingsecure(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
927 extern zrtp_status_t _zrtp_machine_process_while_in_waitconfirmack(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
928 extern zrtp_status_t _zrtp_machine_process_while_in_waitconfirm1(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
929 
930 /* Responder logic */
931 extern zrtp_status_t _zrtp_machine_process_while_in_pendingsecure(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
932 extern zrtp_status_t _zrtp_machine_process_while_in_waitconfirm2(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
933 
934 /* PBX transferring logic */
935 extern zrtp_status_t _zrtp_machine_process_while_in_sasrelaying(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
936 
937 #if (defined(ZRTP_BUILD_FOR_CSD) && (ZRTP_BUILD_FOR_CSD == 1))
938 /* Driven Discovery state-machine */
939 extern zrtp_status_t _zrtp_machine_process_while_in_driven_initiator(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
940 extern zrtp_status_t _zrtp_machine_process_while_in_driven_responder(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
941 extern zrtp_status_t _zrtp_machine_process_while_in_driven_pending(zrtp_stream_t* stream, zrtp_rtp_info_t* packet);
942 #endif
943 
944 state_handler_t* state_handler[ZRTP_STATE_COUNT] =
945 {
946 	NULL,
947 	NULL,
948 	_zrtp_machine_process_while_in_start,
949 	_zrtp_machine_process_while_in_wait4helloack,
950 	_zrtp_machine_process_while_in_wait4hello,
951 	_zrtp_machine_process_while_in_clear,
952 	_zrtp_machine_process_while_in_start_initiatingsecure,
953 	_zrtp_machine_process_while_in_initiatingsecure,
954 	_zrtp_machine_process_while_in_waitconfirm1,
955 	_zrtp_machine_process_while_in_waitconfirmack,
956 	_zrtp_machine_process_while_in_pendingsecure,
957 	_zrtp_machine_process_while_in_waitconfirm2,
958 	_zrtp_machine_process_while_in_secure,
959 	_zrtp_machine_process_while_in_sasrelaying,
960 	_zrtp_machine_process_while_in_initiatingclear,
961 	_zrtp_machine_process_while_in_pendingclear,
962 	_zrtp_machine_process_while_in_initiatingerror,
963 	NULL,
964 	NULL,
965 #if (defined(ZRTP_BUILD_FOR_CSD) && (ZRTP_BUILD_FOR_CSD == 1))
966 	_zrtp_machine_process_while_in_driven_initiator,
967 	_zrtp_machine_process_while_in_driven_responder,
968 	_zrtp_machine_process_while_in_driven_pending,
969 #endif
970 	_zrtp_machine_process_while_in_nozrtp
971 };
972 
973 
974 /*===========================================================================*/
975 /*		State switchers													     */
976 /*===========================================================================*/
977 
_zrtp_machine_switch_to_error(zrtp_stream_t * stream)978 static void _zrtp_machine_switch_to_error(zrtp_stream_t* stream)
979 {
980 	_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
981 	_clear_stream_crypto(stream);
982 
983 	_zrtp_change_state(stream, ZRTP_STATE_ERROR);
984 
985 	if (stream->zrtp->cb.event_cb.on_zrtp_security_event) {
986 		stream->zrtp->cb.event_cb.on_zrtp_security_event(stream, ZRTP_EVENT_PROTOCOL_ERROR);
987 	}
988 	if (stream->zrtp->cb.event_cb.on_zrtp_not_secure) {
989 		stream->zrtp->cb.event_cb.on_zrtp_not_secure(stream);
990 	}
991     stream->last_error = 0;
992 }
993 
994 /*---------------------------------------------------------------------------*/
_zrtp_machine_enter_pendingclear(zrtp_stream_t * stream)995 zrtp_status_t _zrtp_machine_enter_pendingclear(zrtp_stream_t* stream)
996 {
997 	_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
998 	_zrtp_change_state(stream, ZRTP_STATE_PENDINGCLEAR);
999 
1000 	/*
1001 	 * We have to destroy the ZRTP Session Key because user may not press "clear
1002 	 * button", and the remote endpoint may subsequently initiate a new secure
1003 	 * session.  Other secret values will be destroyed in Clear state or
1004 	 * rewritten with new.
1005 	 */
1006 	{
1007 		zrtp_string64_t new_zrtpsess = ZSTR_INIT_EMPTY(new_zrtpsess);
1008 		// TODO: hash
1009 		stream->session->hash->hash( stream->session->hash,
1010 									 ZSTR_GV(stream->session->zrtpsess),
1011 									 ZSTR_GV(new_zrtpsess));
1012 		zrtp_zstrcpy(ZSTR_GV(stream->session->zrtpsess), ZSTR_GV(new_zrtpsess));
1013 	}
1014 
1015 	if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1016 		stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_PENDINGCLEAR);
1017 	}
1018 
1019 	return zrtp_status_ok;
1020 }
1021 
1022 /*---------------------------------------------------------------------------*/
_zrtp_machine_enter_initiatingclear(zrtp_stream_t * stream)1023 static zrtp_status_t _zrtp_machine_enter_initiatingclear(zrtp_stream_t* stream)
1024 {
1025 
1026 	_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
1027 	_zrtp_change_state(stream, ZRTP_STATE_INITIATINGCLEAR);
1028 
1029 	{
1030 	zrtp_string64_t new_zrtpsess = ZSTR_INIT_EMPTY(new_zrtpsess);
1031 	// TODO: hash
1032 	stream->session->hash->hash( stream->session->hash,
1033 								 ZSTR_GV(stream->session->zrtpsess),
1034 								 ZSTR_GV(new_zrtpsess));
1035 	zrtp_zstrcpy(ZSTR_GV(stream->session->zrtpsess), ZSTR_GV(new_zrtpsess));
1036 	}
1037 
1038 	return _zrtp_machine_start_send_and_resend_goclear(stream);
1039 }
1040 
1041 /*---------------------------------------------------------------------------*/
_zrtp_machine_enter_clear(zrtp_stream_t * stream)1042 static zrtp_status_t _zrtp_machine_enter_clear(zrtp_stream_t* stream)
1043 {
1044 	_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
1045 	_clear_stream_crypto(stream);
1046 	_zrtp_change_state(stream, ZRTP_STATE_CLEAR);
1047 
1048 	if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1049 		stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_CLEAR);
1050 	}
1051 
1052 	/*
1053 	 * Now, let's check if the transition to CLEAR was caused by Active/Passive rules.
1054 	 * If local endpoint is a MitM and peer MiTM linked stream is Unlimited, we
1055 	 * could break the rules and send commit to Passive endpoint.
1056 	 */
1057 	if (stream->zrtp->is_mitm && stream->peer_passive) {
1058 		if (stream->linked_mitm && stream->linked_mitm->peer_super_flag) {
1059 			ZRTP_LOG(2,(_ZTU_,"INFO: Current stream ID=%u was switched to CLEAR-mode due to Active/Passive"
1060 						" restrictions, but we are running in MiTM mode and peer linked stream is"
1061 						" Super-active. Go Secure!\n", stream->id));
1062 
1063 			/* @note: don't use zrtp_secure_stream() wrapper as it checks for Active/Passive stuff. */
1064 			_zrtp_machine_start_initiating_secure(stream);
1065 		}
1066 	}
1067 
1068 	return zrtp_status_ok;
1069 }
1070 
1071 
1072 /*---------------------------------------------------------------------------*/
_zrtp_machine_enter_initiatingerror(zrtp_stream_t * stream,zrtp_protocol_error_t code,uint8_t notif)1073 zrtp_status_t _zrtp_machine_enter_initiatingerror( zrtp_stream_t *stream,
1074 												   zrtp_protocol_error_t code,
1075 												   uint8_t notif)
1076 {
1077 	if ( (ZRTP_STATE_ERROR != stream->state) &&
1078 		 (ZRTP_STATE_INITIATINGERROR != stream->state) &&
1079 		 (ZRTP_STATE_PENDINGERROR != stream->state) )
1080 	{
1081 		stream->last_error = code;
1082 
1083 		ZRTP_LOG(3,(_ZTU_,"\tEnter InitiatingError State with ERROR:<%s>, notification %s. ID=%u\n",
1084 				zrtp_log_error2str(stream->last_error), (notif?"Enabled":"Disabled"), stream->id));
1085 
1086 		/* If we can't deliver a ZRTP message, just switch to the ERROR state. */
1087 		if (notif) {
1088 			_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
1089 			_zrtp_change_state(stream, ZRTP_STATE_INITIATINGERROR);
1090 			_zrtp_machine_start_send_and_resend_error(stream);
1091 		} else {
1092 			_zrtp_machine_switch_to_error(stream);
1093 		}
1094 	}
1095 
1096 	return zrtp_status_ok;
1097 }
1098 
_zrtp_machine_enter_pendingerror(zrtp_stream_t * stream,zrtp_protocol_error_t code)1099 zrtp_status_t _zrtp_machine_enter_pendingerror(zrtp_stream_t *stream, zrtp_protocol_error_t code)
1100 {
1101 	ZRTP_LOG(3,(_ZTU_,"\tEnter PendingError State with ERROR:<%s>. ID=%u\n",
1102 				zrtp_log_error2str(stream->last_error), stream->id));
1103 
1104 	_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
1105 	_zrtp_change_state(stream, ZRTP_STATE_PENDINGERROR);
1106 
1107 	stream->last_error = code;
1108 	_zrtp_machine_start_send_and_resend_errorack(stream);
1109 	return zrtp_status_ok;
1110 }
1111 
1112 
1113 /*===========================================================================*/
1114 /*		Packet handlers														 */
1115 /*===========================================================================*/
1116 
_zrtp_machine_process_goclear(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)1117 zrtp_status_t _zrtp_machine_process_goclear(zrtp_stream_t* stream, zrtp_rtp_info_t* packet)
1118 {
1119 	zrtp_packet_GoClear_t *goclear	= (zrtp_packet_GoClear_t*) packet->message;
1120 	zrtp_string128_t clear_hmac = ZSTR_INIT_EMPTY(clear_hmac);
1121 	static const zrtp_string16_t clear_hmac_str	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_CLEAR_HMAC_STR);
1122 
1123 	if (!stream->allowclear) {
1124 		ZRTP_LOG(2, (_ZTU_,"\tWARNING! Allowclear is disabled but GoClear was received. ID=%u.\n", stream->id));
1125 		_zrtp_machine_enter_initiatingerror(stream, zrtp_error_goclear_unsp, 1);
1126 		return zrtp_status_fail;
1127 	}
1128 
1129 	stream->session->hash->hmac( stream->session->hash,
1130 								 ZSTR_GV(stream->cc.peer_hmackey),
1131 								 ZSTR_GV(clear_hmac_str),
1132 								 ZSTR_GV(clear_hmac));
1133 	clear_hmac.length = ZRTP_HMAC_SIZE;
1134 
1135 	if (0 != zrtp_memcmp(clear_hmac.buffer, goclear->clear_hmac, ZRTP_HMAC_SIZE)) {
1136 		ZRTP_LOG(2, (_ZTU_,"\tWARNING! Wrong GoClear hmac. ID=%u.\n", stream->id));
1137 		return zrtp_status_fail; /* EH: Just ignore malformed packets */
1138 	}
1139 
1140 	return zrtp_status_ok;
1141 }
1142 
1143 /*---------------------------------------------------------------------------*/
_zrtp_machine_process_hello(zrtp_stream_t * stream,zrtp_rtp_info_t * packet)1144 zrtp_status_t _zrtp_machine_process_hello(zrtp_stream_t* stream, zrtp_rtp_info_t* packet)
1145 {
1146 	zrtp_session_t* session = stream->session;
1147     zrtp_packet_Hello_t* peer_hello = NULL;
1148 	uint32_t comp_block_len = 0;
1149 	uint8_t id = 0;
1150 
1151 	/* Size of HELLO packet must be bigger then <RTP+static HELLO part>. */
1152 	if (*(packet->length) < (ZRTP_MIN_PACKET_LENGTH + ZRTP_HELLO_STATIC_SIZE + ZRTP_HMAC_SIZE)) {
1153 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! Wrong HELLO static size=%d must be=%d. ID=%u\n", *packet->length,
1154 					ZRTP_MIN_PACKET_LENGTH + ZRTP_HELLO_STATIC_SIZE + ZRTP_HMAC_SIZE, stream->id));
1155 
1156 		_zrtp_machine_enter_initiatingerror(stream, zrtp_error_invalid_packet, 1);
1157 		return zrtp_status_fail;
1158 	}
1159 
1160 	peer_hello = (zrtp_packet_Hello_t*) packet->message;
1161 
1162 	/* Now we can verify packet size according to size of its parts */
1163 	comp_block_len = ( peer_hello->hc + peer_hello->cc +
1164 					   peer_hello->ac + peer_hello->kc +
1165 					   peer_hello->sc) * ZRTP_COMP_TYPE_SIZE;
1166 
1167 	if (*packet->length < (ZRTP_MIN_PACKET_LENGTH + ZRTP_HELLO_STATIC_SIZE + comp_block_len + ZRTP_HMAC_SIZE))
1168 	{
1169 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! Wrong HELLO dynamic size=%d must be=%d. ID=%u\n", *packet->length,
1170 					comp_block_len+ ZRTP_MIN_PACKET_LENGTH + ZRTP_HELLO_STATIC_SIZE + ZRTP_HMAC_SIZE, stream->id));
1171 
1172 		_zrtp_machine_enter_initiatingerror(stream, zrtp_error_invalid_packet, 1);
1173 		return zrtp_status_fail;
1174 	}
1175 
1176 	/* Every component quantity must be less than or equal to 7 */
1177 	if ( (peer_hello->hc > ZRTP_MAX_COMP_COUNT) || (peer_hello->cc > ZRTP_MAX_COMP_COUNT) ||
1178 		 (peer_hello->ac > ZRTP_MAX_COMP_COUNT) || (peer_hello->kc > ZRTP_MAX_COMP_COUNT) ||
1179 		 (peer_hello->sc > ZRTP_MAX_COMP_COUNT) )
1180 	{
1181 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! Wrong HELLO packet data. Components count can't be greater"
1182 					" then 7. ID=%u\n", stream->id));
1183 
1184 		_zrtp_machine_enter_initiatingerror(stream, zrtp_error_invalid_packet, 1);
1185 		return zrtp_status_fail;
1186 	}
1187 
1188 	/* Print out ZRTP Hello message for debug purposes */
1189 	{
1190 	char print_buffer[ZRTP_MAX_COMP_COUNT*20];
1191 	zrtp_memcpy(print_buffer, peer_hello->comp, comp_block_len);
1192 	print_buffer[comp_block_len] = 0;
1193 	ZRTP_LOG(3,(_ZTU_,"\tProcessing HELLO from %.16s V=%.4s, P=%d, M=%d.\n",
1194 				peer_hello->cliend_id, peer_hello->version, peer_hello->pasive, peer_hello->mitmflag));
1195 	ZRTP_LOG(3,(_ZTU_,"\t\tac=%d cc=%d sc=%d kc=%d\n",
1196 				peer_hello->ac, peer_hello->cc, peer_hello->sc, peer_hello->kc));
1197 	ZRTP_LOG(3,(_ZTU_,"\t\t%s\n", print_buffer));
1198 	}
1199 
1200 	/*
1201 	 * Check protocol version. Try to resolve versions missmatch according to ZRTP Draft sec. 5.1
1202 	 */
1203 	{
1204 		uint32_t peer_version = 0;
1205 		peer_version = (char)((*peer_hello->version) - '0') *10; /* only 3 first octets are significant */
1206 		peer_version += (char)(*(peer_hello->version+2) - '0');
1207 
1208 		if ((ZRTP_PROTOCOL_VERSION_VALUE/10) == peer_version) {
1209 			ZRTP_LOG(3,(_ZTU_,"\tReceived HELLO had the same protocol V.\n"));
1210 		}
1211 		else if ((ZRTP_PROTOCOL_VERSION_VALUE/10) < peer_version) {
1212 			ZRTP_LOG(2,(_ZTU_,"\tWARNING! Received HELLO greater ZRTP V=%d - wait for other party"
1213 						" to resolve this issue. ID=%u.\n", peer_version, stream->id));
1214 		} else {
1215 			ZRTP_LOG(2,(_ZTU_,"\tWARNING! Received a ZRTP_HELLO smaller ZRTP V=%d and we don't"
1216 						" support it - terminate session. ID=%u\n", peer_version, stream->id));
1217 
1218 			_zrtp_machine_enter_initiatingerror(stream, zrtp_error_version, 1);
1219 			return zrtp_status_fail;
1220 		}
1221 	}
1222 
1223 	/* Close session if ZID duplication */
1224 	if (!zrtp_memcmp(stream->messages.hello.zid, peer_hello->zid, sizeof(zrtp_zid_t))) {
1225 		ZRTP_LOG(2,(_ZTU_,ZRTP_EQUAL_ZID_WARNING_STR));
1226 		_zrtp_machine_enter_initiatingerror(stream, zrtp_error_equal_zid, 1);
1227 		return zrtp_status_fail;
1228 	}
1229 
1230 	/* All streams within a single session MUST have the same ZID */
1231 	if (session->peer_zid.length > 0) {
1232 		if (0 != zrtp_memcmp(session->peer_zid.buffer, peer_hello->zid, sizeof(zrtp_zid_t))) {
1233 			ZRTP_LOG(2,(_ZTU_,"\tWARNING! Received HELLO which had a different ZID from that of the"
1234 						" previous stream within the same session. sID=%u ID=%u\n", session->id, stream->id));
1235 
1236 			_zrtp_machine_enter_initiatingerror(stream, zrtp_error_wrong_zid, 1);
1237 			return zrtp_status_fail;
1238 		}
1239 	} else {
1240 		zrtp_zstrncpyc(ZSTR_GV(session->peer_zid), (const char*) peer_hello->zid, sizeof(zrtp_zid_t));
1241 	}
1242 
1243 	/*
1244 	 * Process Remote flags.
1245 	 */
1246 	if (peer_hello->pasive && peer_hello->uflag) {
1247 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! Received HELLO which both P and U flags set.\n"));
1248 		return zrtp_status_fail;
1249 	}
1250 
1251 	stream->peer_passive = peer_hello->pasive;
1252 	stream->peer_super_flag = peer_hello->uflag;
1253 
1254 	stream->peer_mitm_flag = peer_hello->mitmflag;
1255 	if (stream->peer_mitm_flag) {
1256 		stream->mitm_mode = ZRTP_MITM_MODE_CLIENT;
1257 	}
1258 
1259 	/* Current version doesn't support Digital Signatures. Ignore peer Hello with S flag enabled. */
1260 	if (peer_hello->sigflag) {
1261 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! Received a ZRTP_HELLO with S flag enabled. We don't support Digital Signatures - ignore message.\n"));
1262 		return zrtp_status_fail;
1263 	}
1264 
1265 	/* Copy packet for future hashing */
1266 	zrtp_memcpy(&stream->messages.peer_hello, peer_hello, zrtp_ntoh16(peer_hello->hdr.length)*4);
1267 	stream->is_hello_received = 1;
1268 
1269 	/*
1270 	 * Choose PK exchange scheme and PK mode.
1271 	 * We do this right after receiving Hello to speedup DH calculations.
1272 	 */
1273 	stream->pubkeyscheme = zrtp_comp_find(ZRTP_CC_PKT, ZRTP_PKTYPE_DH3072, session->zrtp);
1274 	id = _zrtp_choose_best_comp(&session->profile, peer_hello, ZRTP_CC_PKT);
1275 	if (id != ZRTP_COMP_UNKN) {
1276 		stream->pubkeyscheme = zrtp_comp_find(ZRTP_CC_PKT, id, session->zrtp);
1277 	}
1278 
1279 	ZRTP_LOG(3,(_ZTU_,"\tReceived HELLO Accepted\n"));
1280 
1281     return zrtp_status_ok;
1282 }
1283 
1284 
1285 /*===========================================================================*/
1286 /*		Packet senders														 */
1287 /*===========================================================================*/
1288 
1289 /*---------------------------------------------------------------------------*/
_send_and_resend_hello(zrtp_stream_t * stream,zrtp_retry_task_t * task)1290 static void _send_and_resend_hello(zrtp_stream_t* stream, zrtp_retry_task_t* task)
1291 {
1292 	if ((task->_retrys == ZRTP_NO_ZRTP_FAST_COUNT) && !stream->is_hello_received) {
1293 		ZRTP_LOG(2,(_ZTU_,"WARNING! HELLO have been resent %d times without a response."
1294 					" Raising ZRTP_EVENT_NO_ZRTP_QUICK event. ID=%u\n", task->_retrys, stream->id));
1295 
1296 		if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1297 			stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_NO_ZRTP_QUICK);
1298 		}
1299 	}
1300 
1301 	if (task->_retrys >= (uint32_t)((ZRTP_STATE_WAIT_HELLOACK==stream->state)?ZRTP_T1_MAX_COUNT_EXT:ZRTP_T1_MAX_COUNT)) {
1302 		ZRTP_LOG(2,(_ZTU_,"WARNING! HELLO Max retransmissions count reached (%d retries). ID=%u\n", task->_retrys, stream->id));
1303 
1304 		_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
1305 		_clear_stream_crypto(stream);
1306 		_zrtp_change_state(stream, ZRTP_STATE_NO_ZRTP);
1307 
1308 		if (stream->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1309 			stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_NO_ZRTP);
1310 		}
1311 	} else if (task->_is_enabled) {
1312 		zrtp_status_t s = _zrtp_packet_send_message(stream, ZRTP_HELLO, &stream->messages.hello);
1313 		task->timeout = _zrtp_get_timeout((uint32_t)task->timeout, ZRTP_HELLO);
1314 		if (zrtp_status_ok == s) {
1315 			task->_retrys++;
1316 		}
1317 
1318 
1319 		if (stream->zrtp->cb.sched_cb.on_call_later) {
1320 			stream->zrtp->cb.sched_cb.on_call_later(stream, task);
1321 		}
1322 	}
1323 }
1324 
_zrtp_machine_start_send_and_resend_hello(zrtp_stream_t * stream)1325 zrtp_status_t _zrtp_machine_start_send_and_resend_hello(zrtp_stream_t* stream)
1326 {
1327 	zrtp_retry_task_t* task = &stream->messages.hello_task;
1328 
1329 	task->_is_enabled = 1;
1330 	task->callback = _send_and_resend_hello;
1331 	task->_retrys = 0;
1332 
1333 	_send_and_resend_hello(stream, task);
1334 
1335 	return zrtp_status_ok;
1336 }
1337 
_send_helloack(zrtp_stream_t * stream)1338 static void _send_helloack(zrtp_stream_t* stream)
1339 {
1340 	_zrtp_packet_send_message(stream, ZRTP_HELLOACK, NULL);
1341 }
1342 
1343 
1344 /*---------------------------------------------------------------------------*/
_send_and_resend_goclear(zrtp_stream_t * stream,zrtp_retry_task_t * task)1345 static void _send_and_resend_goclear(zrtp_stream_t* stream, zrtp_retry_task_t* task)
1346 {
1347 	if (task->_is_enabled) {
1348 		if (task->_retrys > ZRTP_T2_MAX_COUNT) {
1349 			ZRTP_LOG(2,(_ZTU_,"\tWARNING!: GOCLEAR Nax retransmissions count reached. ID=%u\n", stream->id));
1350 			_zrtp_machine_enter_clear(stream);
1351 		} else {
1352 			zrtp_packet_GoClear_t* goclear = (zrtp_packet_GoClear_t*) &stream->messages.goclear;
1353 
1354 			_zrtp_packet_send_message(stream, ZRTP_GOCLEAR, goclear);
1355 			task->_retrys++;
1356 			if (stream->zrtp->cb.sched_cb.on_call_later) {
1357 				stream->zrtp->cb.sched_cb.on_call_later(stream, task);
1358 			}
1359 		}
1360 	}
1361 }
1362 
_zrtp_machine_start_send_and_resend_goclear(zrtp_stream_t * stream)1363 static zrtp_status_t  _zrtp_machine_start_send_and_resend_goclear(zrtp_stream_t* stream)
1364 {
1365 	zrtp_retry_task_t* task = &stream->messages.goclear_task;
1366 	zrtp_string128_t clear_hmac = ZSTR_INIT_EMPTY(clear_hmac);
1367 	static const zrtp_string16_t clear_hmac_str	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_CLEAR_HMAC_STR);
1368 
1369 	zrtp_memset(&stream->messages.goclear, 0, sizeof(zrtp_packet_GoClear_t));
1370 
1371 	/* Compute Clear HMAC as: HMAC(hmackey, "Clear hmac") */
1372 	stream->session->hash->hmac( stream->session->hash,
1373 								 ZSTR_GV(stream->cc.hmackey),
1374 								 ZSTR_GV(clear_hmac_str),
1375 								 ZSTR_GV(clear_hmac));
1376 	clear_hmac.length = ZRTP_HMAC_SIZE;
1377 
1378 	zrtp_memcpy(stream->messages.goclear.clear_hmac, clear_hmac.buffer, clear_hmac.length);
1379 	_zrtp_packet_fill_msg_hdr( stream,
1380 							   ZRTP_GOCLEAR,
1381 							   sizeof(zrtp_packet_GoClear_t) - sizeof(zrtp_msg_hdr_t),
1382 							   &stream->messages.goclear.hdr);
1383 
1384 	task->_is_enabled	= 1;
1385 	task->callback		= _send_and_resend_goclear;
1386 	task->timeout		= ZRTP_T2;
1387 	task->_retrys		= 0;
1388 
1389 	_send_and_resend_goclear(stream, task);
1390 
1391 	return zrtp_status_ok;
1392 }
1393 
1394 
_send_goclearack(zrtp_stream_t * stream)1395 static void _send_goclearack(zrtp_stream_t* stream)
1396 {
1397 	_zrtp_packet_send_message(stream, ZRTP_GOCLEARACK, NULL);
1398 }
1399 
1400 /*---------------------------------------------------------------------------*/
_send_and_resend_error(zrtp_stream_t * stream,zrtp_retry_task_t * task)1401 static void _send_and_resend_error(zrtp_stream_t* stream, zrtp_retry_task_t* task)
1402 {
1403 	if (task->_retrys >= ZRTP_ETI_MAX_COUNT) {
1404 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! ERROR Max retransmissions count reached. ID=%u\n", stream->id));
1405 		_zrtp_machine_switch_to_error(stream);
1406 	} else if (task->_is_enabled) {
1407 		if (zrtp_status_ok == _zrtp_packet_send_message(stream, ZRTP_ERROR, &stream->messages.error)) {
1408 			task->_retrys++;
1409 		}
1410 		if (stream->zrtp->cb.sched_cb.on_call_later) {
1411 			stream->zrtp->cb.sched_cb.on_call_later(stream, task);
1412 		}
1413 	}
1414 }
1415 
_zrtp_machine_start_send_and_resend_error(zrtp_stream_t * stream)1416 static zrtp_status_t  _zrtp_machine_start_send_and_resend_error(zrtp_stream_t* stream)
1417 {
1418 	zrtp_retry_task_t* task = &stream->messages.error_task;
1419 
1420 	zrtp_memset(&stream->messages.error, 0, sizeof(zrtp_packet_Error_t));
1421 	stream->messages.error.code = zrtp_hton32(stream->last_error);
1422 
1423 	_zrtp_packet_fill_msg_hdr( stream,
1424 							   ZRTP_ERROR,
1425 							   sizeof(zrtp_packet_Error_t) - sizeof(zrtp_msg_hdr_t),
1426 							   &stream->messages.error.hdr);
1427 
1428 	task->_is_enabled	= 1;
1429 	task->callback		= _send_and_resend_error;
1430 	task->timeout		= ZRTP_ET;
1431 	task->_retrys		= 0;
1432 
1433 	_send_and_resend_error(stream, task);
1434 
1435 	return zrtp_status_ok;
1436 }
1437 
1438 /*---------------------------------------------------------------------------*/
_send_and_resend_errorack(zrtp_stream_t * stream,zrtp_retry_task_t * task)1439 static void _send_and_resend_errorack(zrtp_stream_t* stream, zrtp_retry_task_t* task)
1440 {
1441 	if (task->_retrys >= ZRTP_ETR_MAX_COUNT) {
1442 		ZRTP_LOG(2,(_ZTU_,"\tWARNING! ERRORACK Max retransmissions count reached. ID=%u\n", stream->id));
1443 		_zrtp_machine_switch_to_error(stream);
1444 	} else if (task->_is_enabled) {
1445 		if (zrtp_status_ok == _zrtp_packet_send_message(stream, ZRTP_ERRORACK, NULL)) {
1446 			task->_retrys++;
1447 		}
1448 		if (stream->zrtp->cb.sched_cb.on_call_later) {
1449 			stream->zrtp->cb.sched_cb.on_call_later(stream, task);
1450 		}
1451 	}
1452 }
1453 
_zrtp_machine_start_send_and_resend_errorack(zrtp_stream_t * stream)1454 static zrtp_status_t  _zrtp_machine_start_send_and_resend_errorack(zrtp_stream_t* stream)
1455 {
1456 	zrtp_retry_task_t* task = &stream->messages.errorack_task;
1457 
1458 	task->_is_enabled	= 1;
1459 	task->callback		= _send_and_resend_errorack;
1460 	task->timeout		= ZRTP_ET;
1461 	task->_retrys		= 0;
1462 
1463 	_send_and_resend_errorack(stream, task);
1464 
1465 	return zrtp_status_ok;
1466 }
1467 
1468 
_clear_stream_crypto(zrtp_stream_t * stream)1469 void _clear_stream_crypto(zrtp_stream_t* stream)
1470 {
1471 	if (stream->protocol) {
1472 		_zrtp_protocol_destroy(stream->protocol);
1473 		stream->protocol = 0;
1474 	}
1475 
1476 	zrtp_wipe_zstring(ZSTR_GV(stream->cc.hmackey));
1477 	zrtp_wipe_zstring(ZSTR_GV(stream->cc.peer_hmackey));
1478 	zrtp_wipe_zstring(ZSTR_GV(&stream->cc.zrtp_key));
1479 	zrtp_wipe_zstring(ZSTR_GV(stream->cc.peer_zrtp_key));
1480 }
1481