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 protocol"
13 
14 
15 /*===========================================================================*/
16 /*	PROTOCOL Logic														     */
17 /*===========================================================================*/
18 
19 /*----------------------------------------------------------------------------*/
_attach_secret(zrtp_session_t * session,zrtp_proto_secret_t * psec,zrtp_shared_secret_t * sec,uint8_t is_initiator)20 static zrtp_status_t _attach_secret( zrtp_session_t *session,
21 									 zrtp_proto_secret_t* psec,
22 									 zrtp_shared_secret_t* sec,
23 									 uint8_t is_initiator)
24 {
25 	zrtp_uchar32_t buff;
26 	static const zrtp_string16_t initiator	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_ROLE_INITIATOR);
27 	static const zrtp_string16_t responder	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_ROLE_RESPONDER);
28 
29 	const zrtp_string16_t* role				= is_initiator ? &initiator : &responder;
30 	const zrtp_string16_t* his_role			= is_initiator ? &responder : &initiator;
31 
32 	ZSTR_SET_EMPTY(psec->id);
33 	ZSTR_SET_EMPTY(psec->peer_id);
34 	psec->secret = sec;
35 
36 	/*
37 	 * If secret's value is available (from the cache or from SIP) - use hmac;
38 	 * use zero-strings in other case.
39 	 */
40 	if (psec->secret) {
41 		session->hash->hmac_truncated( session->hash,
42 									   ZSTR_GV(sec->value),
43 									   ZSTR_GVP(role),
44 									   ZRTP_RSID_SIZE,
45 									   ZSTR_GV(psec->id));
46 
47 		session->hash->hmac_truncated( session->hash,
48 									   ZSTR_GV(sec->value),
49 									   ZSTR_GVP(his_role),
50 									   ZRTP_RSID_SIZE,
51 									   ZSTR_GV(psec->peer_id));
52 	} else {
53 		psec->id.length = ZRTP_RSID_SIZE;
54 		zrtp_memset(psec->id.buffer, 0, psec->id.length);
55 
56 		psec->peer_id.length = ZRTP_RSID_SIZE;
57 		zrtp_memset(psec->peer_id.buffer, 0, psec->peer_id.length);
58 	}
59 
60 	ZRTP_LOG(3,(_ZTU_,"\tAttach RS id=%s.\n",
61 				hex2str((const char*)psec->id.buffer, psec->id.length, (char*)buff, sizeof(buff))));
62 	ZRTP_LOG(3,(_ZTU_,"\tAttach RS peer_id=%s.\n",
63 				hex2str((const char*)psec->peer_id.buffer, psec->peer_id.length, (char*)buff, sizeof(buff))));
64 
65 	return zrtp_status_ok;
66 }
67 
_attach_auxs_secret(zrtp_stream_t * stream,zrtp_proto_secret_t * psec,zrtp_shared_secret_t * sec,uint8_t is_initiator)68 static zrtp_status_t _attach_auxs_secret(zrtp_stream_t *stream,
69 										 zrtp_proto_secret_t* psec,
70 										 zrtp_shared_secret_t* sec,
71 										 uint8_t is_initiator)
72 {
73 	zrtp_uchar32_t buff;
74 
75 	zrtp_string32_t myH3;
76 	ZSTR_SET_EMPTY(myH3);
77 	zrtp_zstrncpyc(ZSTR_GV(myH3), stream->messages.hello.hash, sizeof(stream->messages.hello.hash));
78 
79 	zrtp_string32_t peerH3;
80 	ZSTR_SET_EMPTY(peerH3);
81 	zrtp_zstrncpyc(ZSTR_GV(peerH3), stream->messages.peer_hello.hash, sizeof(stream->messages.peer_hello.hash));
82 
83 	ZSTR_SET_EMPTY(psec->id);
84 	ZSTR_SET_EMPTY(psec->peer_id);
85 	psec->secret = sec;
86 
87 	if (psec->secret) {
88 		stream->session->hash->hmac_truncated(stream->session->hash,
89 			ZSTR_GV(sec->value),
90 			ZSTR_GV(myH3),
91 			ZRTP_RSID_SIZE,
92 			ZSTR_GV(psec->id));
93 
94 		stream->session->hash->hmac_truncated(stream->session->hash,
95 			ZSTR_GV(sec->value),
96 			ZSTR_GV(peerH3),
97 			ZRTP_RSID_SIZE,
98 			ZSTR_GV(psec->peer_id));
99 	}
100 	else {
101 		psec->id.length = ZRTP_RSID_SIZE;
102 		zrtp_memset(psec->id.buffer, 0, psec->id.length);
103 
104 		psec->peer_id.length = ZRTP_RSID_SIZE;
105 		zrtp_memset(psec->peer_id.buffer, 0, psec->peer_id.length);
106 	}
107 
108 	ZRTP_LOG(3, (_ZTU_, "\tAttach RS/auxs id=%s.\n",
109 		hex2str((const char*)psec->id.buffer, psec->id.length, (char*)buff, sizeof(buff))));
110 	ZRTP_LOG(3, (_ZTU_, "\tAttach RS/auxs peer_id=%s.\n",
111 		hex2str((const char*)psec->peer_id.buffer, psec->peer_id.length, (char*)buff, sizeof(buff))));
112 
113 	return zrtp_status_ok;
114 }
115 
_zrtp_protocol_init(zrtp_stream_t * stream,uint8_t is_initiator,zrtp_protocol_t ** protocol)116 zrtp_status_t _zrtp_protocol_init(zrtp_stream_t *stream, uint8_t is_initiator, zrtp_protocol_t **protocol)
117 {
118 	zrtp_protocol_t	*new_proto = NULL;
119 	zrtp_status_t s = zrtp_status_ok;
120 
121 	ZRTP_LOG(3,(_ZTU_,"\tInit %s Protocol ID=%u mode=%s...\n",
122 				is_initiator ? "INITIATOR's" : "RESPONDER's", stream->id, zrtp_log_mode2str(stream->mode)));
123 
124 	/* Destroy previous protocol structure (Responder or Preshared) */
125     if (*protocol) {
126 		_zrtp_protocol_destroy(*protocol);
127 		*protocol = NULL;
128     }
129 
130 	/* Allocate memory for all branching structures */
131 	do
132 	{
133 		new_proto = zrtp_sys_alloc(sizeof(zrtp_protocol_t));
134 		if (!new_proto) {
135 			s = zrtp_status_alloc_fail;
136 			break;
137 		}
138 		zrtp_memset(new_proto, 0, sizeof(zrtp_protocol_t));
139 
140 		new_proto->cc = zrtp_sys_alloc(sizeof(zrtp_proto_crypto_t));
141 		if (!new_proto->cc) {
142 			s = zrtp_status_alloc_fail;
143 			break;
144 		}
145 		zrtp_memset(new_proto->cc, 0, sizeof(zrtp_proto_crypto_t));
146 
147 		/* Create and Initialize DH crypto context	(for DH streams only) */
148 		if (ZRTP_IS_STREAM_DH(stream)) {
149 			if (stream->dh_cc.initialized_with != stream->pubkeyscheme->base.id) {
150 				stream->pubkeyscheme->initialize(stream->pubkeyscheme, &stream->dh_cc);
151 				stream->dh_cc.initialized_with = stream->pubkeyscheme->base.id;
152 			}
153 		}
154 
155 		/* Initialize main structure at first: functions pointers and generate nonce */
156 		new_proto->type		= is_initiator ? ZRTP_STATEMACHINE_INITIATOR : ZRTP_STATEMACHINE_RESPONDER;
157 		new_proto->context = stream;
158 
159 		/* Initialize protocol crypto context and prepare it for further usage */
160 		ZSTR_SET_EMPTY(new_proto->cc->kdf_context);
161 		ZSTR_SET_EMPTY(new_proto->cc->s0);
162 		ZSTR_SET_EMPTY(new_proto->cc->mes_hash);
163 		ZSTR_SET_EMPTY(new_proto->cc->hv);
164 		ZSTR_SET_EMPTY(new_proto->cc->peer_hv);
165 
166 		if (ZRTP_IS_STREAM_DH(stream)) {
167 			_attach_secret(stream->session, &new_proto->cc->rs1, stream->session->secrets.rs1, is_initiator);
168 			_attach_secret(stream->session, &new_proto->cc->rs2, stream->session->secrets.rs2, is_initiator);
169 			_attach_auxs_secret(stream, &new_proto->cc->auxs, stream->session->secrets.auxs, is_initiator);
170 			_attach_secret(stream->session, &new_proto->cc->pbxs, stream->session->secrets.pbxs, is_initiator);
171 		}
172 
173 		s = zrtp_status_ok;
174 		*protocol = new_proto;
175 	} while (0);
176 
177 	if (s != zrtp_status_ok) {
178 		ZRTP_LOG(1,(_ZTU_,"\tERROR! _zrtp_protocol_attach() with code %s.\n", zrtp_log_status2str(s)));
179 		if (new_proto && new_proto->cc) {
180 			zrtp_sys_free(new_proto->cc);
181 		}
182 		if (new_proto) {
183 			zrtp_sys_free(new_proto);
184 		}
185 		*protocol = NULL;
186 	}
187 
188     return s;
189 }
190 
191 /*----------------------------------------------------------------------------*/
clear_crypto_sources(zrtp_stream_t * stream)192 static void clear_crypto_sources(zrtp_stream_t* stream)
193 {
194 	zrtp_protocol_t* proto = stream->protocol;
195 	if (proto && proto->cc) {
196 		zrtp_memset(proto->cc, 0, sizeof(zrtp_proto_crypto_t));
197 		zrtp_sys_free(proto->cc);
198 		proto->cc = 0;
199 	}
200 }
201 
_zrtp_protocol_destroy(zrtp_protocol_t * proto)202 void _zrtp_protocol_destroy(zrtp_protocol_t *proto)
203 {
204 	/* Clear protocol crypto values, destroy SRTP unit, clear and release memory. */
205 	if (proto) {
206 		/* if protocol is being destroyed by exception, ->context may be NULL */
207 		if (proto->context) {
208 			_zrtp_cancel_send_packet_later(proto->context, ZRTP_NONE);
209 			if (proto->_srtp) {
210 				zrtp_srtp_destroy(proto->context->zrtp->srtp_global, proto->_srtp);
211 			}
212 		}
213 
214 		clear_crypto_sources(proto->context);
215 		zrtp_memset(proto, 0, sizeof(zrtp_protocol_t));
216 		zrtp_sys_free(proto);
217 	}
218 }
219 
220 /*----------------------------------------------------------------------------*/
_zrtp_protocol_encrypt(zrtp_protocol_t * proto,zrtp_rtp_info_t * packet,uint8_t is_rtp)221 zrtp_status_t _zrtp_protocol_encrypt( zrtp_protocol_t *proto,
222 									  zrtp_rtp_info_t *packet,
223 									  uint8_t is_rtp)
224 {
225 	zrtp_status_t s = zrtp_status_ok;
226 
227 	if (is_rtp) {
228 		s = zrtp_srtp_protect(proto->context->zrtp->srtp_global, proto->_srtp, packet);
229 	} else {
230 		s = zrtp_srtp_protect_rtcp(proto->context->zrtp->srtp_global, proto->_srtp, packet);
231 	}
232 
233 	if (zrtp_status_ok != s) {
234 		ZRTP_UNALIGNED(zrtp_rtp_hdr_t) *hdr = (zrtp_rtp_hdr_t*) packet->packet;
235 
236 		ZRTP_LOG(2,(_ZTU_,"ERROR! Encrypt failed. ID=%u:%s s=%s (%s size=%d ssrc=%u seq=%d pt=%d)\n",
237 					    proto->context->id,
238 						zrtp_log_mode2str(proto->context->mode),
239 						zrtp_log_status2str(s),
240 						is_rtp ? "RTP" : "RTCP",
241 						*packet->length,
242 						zrtp_ntoh32(hdr->ssrc),
243 						zrtp_ntoh16(hdr->seq),
244 						hdr->pt));
245     }
246 
247 	return s;
248 }
249 
250 /*----------------------------------------------------------------------------*/
_zrtp_protocol_decrypt(zrtp_protocol_t * proto,zrtp_rtp_info_t * packet,uint8_t is_rtp)251 zrtp_status_t _zrtp_protocol_decrypt( zrtp_protocol_t *proto,
252 									  zrtp_rtp_info_t *packet,
253 									  uint8_t is_rtp)
254 {
255 	zrtp_status_t s = zrtp_status_ok;
256 
257 	if (is_rtp) {
258 		s = zrtp_srtp_unprotect(proto->context->zrtp->srtp_global, proto->_srtp, packet);
259 	} else {
260 		s = zrtp_srtp_unprotect_rtcp(proto->context->zrtp->srtp_global, proto->_srtp, packet);
261 	}
262 
263 	if (zrtp_status_ok != s) {
264 		ZRTP_UNALIGNED(zrtp_rtp_hdr_t) *hdr = (zrtp_rtp_hdr_t*) packet->packet;
265 		ZRTP_LOG(2,(_ZTU_,"ERROR! Decrypt failed. ID=%u:%s s=%s (%s size=%d ssrc=%u seq=%u/%u pt=%d)\n",
266 					    proto->context->id,
267 						zrtp_log_mode2str(proto->context->mode),
268 						zrtp_log_status2str(s),
269 						is_rtp ? "RTP" : "RTCP",
270 						*packet->length,
271 						zrtp_ntoh32(hdr->ssrc),
272 						zrtp_ntoh16(hdr->seq),
273 						packet->seq,
274 						hdr->pt));
275     }
276 
277 	return s;
278 }
279 
280 
281 /*===========================================================================*/
282 /*	CRYPTO Utilites														     */
283 /*===========================================================================*/
284 
285 /*---------------------------------------------------------------------------*/
_derive_s0(zrtp_stream_t * stream,int is_initiator)286 static zrtp_status_t _derive_s0(zrtp_stream_t* stream, int is_initiator)
287 {
288 	static const zrtp_string32_t zrtp_kdf_label	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_KDF_STR);
289 	static const zrtp_string32_t zrtp_sess_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_SESS_STR);
290 	static const zrtp_string32_t zrtp_multi_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_MULTI_STR);
291 	static const zrtp_string32_t zrtp_presh_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_PRESH_STR);
292 
293 	zrtp_session_t *session = stream->session;
294 	zrtp_secrets_t* secrets  = &session->secrets;
295 	zrtp_proto_crypto_t* cc  = stream->protocol->cc;
296 	void* hash_ctx = NULL;
297 	char print_buff[256];
298 
299 	switch (stream->mode)
300 	{
301 	/*
302 	 * S0 computing for FULL DH exchange
303 	 * S0 computing.  s0 is the master shared secret used for all
304 	 * cryptographic operations.  In particular, note the inclusion
305 	 * of "total_hash", a hash of all packets exchanged up to this
306 	 * point.  This belatedly detects any tampering with earlier
307 	 * packets, e.g. bid-down attacks.
308 	 *
309 	 * s0 = hash( 1 | DHResult | "ZRTP-HMAC-KDF" | ZIDi | ZIDr |
310 	 *                        total_hash | len(s1) | s1 | len(s2) | s2 | len(s3) | s3 )
311 	 * The constant 1 and all lengths are 32 bits big-endian values.
312 	 * The fields without length prefixes are fixed-witdh:
313 	 * - DHresult is fixed to the width of the DH prime.
314 	 * - The hash type string and ZIDs are fixed width.
315 	 * - total_hash is fixed by the hash negotiation.
316 	 * The constant 1 is per NIST SP 800-56A section 5.8.1, and is
317 	 * a counter which can be incremented to generate more than 256
318 	 * bits of key material.
319 	 * ========================================================================
320 	 */
321 	case ZRTP_STREAM_MODE_DH:
322 	{
323 		zrtp_proto_secret_t *C[3] = { 0, 0, 0};
324 		int i = 0;
325 		uint32_t comp_length = 0;
326 		zrtp_stringn_t *zidi = NULL, *zidr = NULL;
327 		struct BigNum dhresult;
328 #if (defined(ZRTP_USE_STACK_MINIM) && (ZRTP_USE_STACK_MINIM == 1))
329 		zrtp_uchar1024_t* buffer = zrtp_sys_alloc( sizeof(zrtp_uchar1024_t) );
330 		if (!buffer) {
331 			return zrtp_status_alloc_fail;
332 		}
333 #else
334 		zrtp_uchar1024_t holder;
335 		zrtp_uchar1024_t* buffer = &holder;
336 #endif
337 
338 		ZRTP_LOG(3,(_ZTU_,"\tDERIVE S0 from DH exchange and RS secrets...\n"));
339 		ZRTP_LOG(3,(_ZTU_,"\t       my rs1ID:%s\n", hex2str(cc->rs1.id.buffer, cc->rs1.id.length, print_buff, sizeof(print_buff))));
340 		ZRTP_LOG(3,(_ZTU_,"\t      his rs1ID:%s\n", hex2str((const char*)stream->messages.peer_dhpart.rs1ID, ZRTP_RSID_SIZE, print_buff, sizeof(print_buff))));
341 		ZRTP_LOG(3,(_ZTU_,"\t his rs1ID comp:%s\n", hex2str(cc->rs1.peer_id.buffer, cc->rs1.peer_id.length, print_buff, sizeof(print_buff))));
342 
343 		ZRTP_LOG(3,(_ZTU_,"\t       my rs2ID:%s\n", hex2str(cc->rs2.id.buffer, cc->rs2.id.length, print_buff, sizeof(print_buff))));
344 		ZRTP_LOG(3,(_ZTU_,"\t      his rs2ID:%s\n", hex2str((const char*)stream->messages.peer_dhpart.rs2ID, ZRTP_RSID_SIZE, print_buff, sizeof(print_buff))));
345 		ZRTP_LOG(3,(_ZTU_,"\t his rs2ID comp:%s\n", hex2str(cc->rs2.peer_id.buffer, cc->rs2.peer_id.length, print_buff, sizeof(print_buff))));
346 
347 		ZRTP_LOG(3,(_ZTU_,"\t      my pbxsID:%s\n", hex2str(cc->pbxs.id.buffer, cc->pbxs.id.length, print_buff, sizeof(print_buff))));
348 		ZRTP_LOG(3,(_ZTU_,"\t     his pbxsID:%s\n", hex2str((const char*)stream->messages.peer_dhpart.pbxsID, ZRTP_RSID_SIZE, print_buff, sizeof(print_buff))));
349 		ZRTP_LOG(3,(_ZTU_,"\this pbxsID comp:%s\n", hex2str(cc->pbxs.peer_id.buffer, cc->pbxs.peer_id.length, print_buff, sizeof(print_buff))));
350 
351 		ZRTP_LOG(3, (_ZTU_, "\t      my auxsID:%s\n", hex2str(cc->auxs.id.buffer, cc->auxs.id.length, print_buff, sizeof(print_buff))));
352 		ZRTP_LOG(3, (_ZTU_, "\t     his auxsID:%s\n", hex2str((const char*)stream->messages.peer_dhpart.auxsID, ZRTP_RSID_SIZE, print_buff, sizeof(print_buff))));
353 		ZRTP_LOG(3, (_ZTU_, "\this auxsID comp:%s\n", hex2str(cc->auxs.peer_id.buffer, cc->auxs.peer_id.length, print_buff, sizeof(print_buff))));
354 
355 		hash_ctx = session->hash->hash_begin(session->hash);
356 		if (0 == hash_ctx) {
357 			ZRTP_LOG(1,(_ZTU_, "\tERROR! can't start hash calculation for S0 computing. ID=%u.\n", stream->id));
358 			return zrtp_status_fail;
359 		}
360 
361 		/*
362 		 * NIST requires a 32-bit big-endian integer counter to be included
363 		 * in the hash each time the hash is computed, which we have set to
364 		 * the fixed value of 1, because we only compute the hash once.
365 		 */
366 		comp_length = zrtp_hton32(1L);
367 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)&comp_length, 4);
368 
369 
370 		switch (stream->pubkeyscheme->base.id) {
371 			case ZRTP_PKTYPE_DH2048:
372 			case ZRTP_PKTYPE_DH3072:
373 			case ZRTP_PKTYPE_DH4096:
374 				comp_length = stream->pubkeyscheme->pv_length;
375 				ZRTP_LOG(3,(_ZTU_,"DH comp_length=%u\n", comp_length));
376 				break;
377 			case ZRTP_PKTYPE_EC256P:
378 			case ZRTP_PKTYPE_EC384P:
379 			case ZRTP_PKTYPE_EC521P:
380 				comp_length = stream->pubkeyscheme->pv_length/2;
381 				ZRTP_LOG(3,(_ZTU_,"ECDH comp_length=%u\n", comp_length));
382 				break;
383 			default:
384 				break;
385 		}
386 
387 		bnBegin(&dhresult);
388 		stream->pubkeyscheme->compute(stream->pubkeyscheme,
389 									  &stream->dh_cc,
390 									  &dhresult,
391 									  &stream->dh_cc.peer_pv);
392 
393 		bnExtractBigBytes(&dhresult, (uint8_t *)buffer, 0, comp_length);
394 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)buffer, comp_length);
395 		bnEnd(&dhresult);
396 
397 #if (defined(ZRTP_USE_STACK_MINIM) && (ZRTP_USE_STACK_MINIM == 1))
398 		zrtp_sys_free(buffer);
399 #endif
400 
401 		/* Add "ZRTP-HMAC-KDF" to the S0 hash */
402 		session->hash->hash_update( session->hash, hash_ctx,
403 									(const int8_t*)&zrtp_kdf_label.buffer,
404 									zrtp_kdf_label.length);
405 
406 		/* Then Initiator's and Responder's ZIDs */
407 		if (stream->protocol->type == ZRTP_STATEMACHINE_INITIATOR) {
408 			zidi = ZSTR_GV(stream->session->zid);
409 			zidr = ZSTR_GV(stream->session->peer_zid);
410 		} else {
411 			zidr = ZSTR_GV(stream->session->zid);
412 			zidi = ZSTR_GV(stream->session->peer_zid);
413 		}
414 
415 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)&zidi->buffer, zidi->length);
416 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)&zidr->buffer, zidr->length);
417 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)&cc->mes_hash.buffer, cc->mes_hash.length);
418 
419 		/* If everything is OK - RS1 should much */
420 		if (!zrtp_memcmp(cc->rs1.peer_id.buffer, stream->messages.peer_dhpart.rs1ID, ZRTP_RSID_SIZE))
421 		{
422 			C[0] = &cc->rs1;
423 			secrets->matches |= ZRTP_BIT_RS1;
424 		}
425 		/* If we have lost our RS1 - remote party should use backup (RS2) instead */
426 		else if (!zrtp_memcmp(cc->rs1.peer_id.buffer, stream->messages.peer_dhpart.rs2ID, ZRTP_RSID_SIZE))
427 		{
428 			C[0] = &cc->rs1;
429 			secrets->matches |= ZRTP_BIT_RS1;
430 			ZRTP_LOG(2,(_ZTU_,"\tINFO! We have lost our RS1 from previous broken exchange"
431 						" - remote party will use RS2 backup. ID=%u\n", stream->id));
432 		}
433 		/* If remote party lost it's secret - we will use backup */
434 		else if (!zrtp_memcmp(cc->rs2.peer_id.buffer, stream->messages.peer_dhpart.rs1ID, ZRTP_RSID_SIZE))
435 		{
436 			C[0] = &cc->rs2;
437 			cc->rs1 = cc->rs2;
438 			secrets->matches |= ZRTP_BIT_RS1;
439 			secrets->cached  |= ZRTP_BIT_RS1;
440 			ZRTP_LOG(2,(_ZTU_,"\tINFO! Remote party has lost it's RS1 - use RS2 backup. ID=%u\n", stream->id));
441 		}
442 		else
443 		{
444 			secrets->matches &= ~ZRTP_BIT_RS1;
445 			if (session->zrtp->cb.cache_cb.on_set_verified) {
446 				session->zrtp->cb.cache_cb.on_set_verified( ZSTR_GV(session->zid),
447 															ZSTR_GV(session->peer_zid),
448 															0);
449 			}
450 
451 			if (session->zrtp->cb.cache_cb.on_reset_since) {
452 				session->zrtp->cb.cache_cb.on_reset_since(ZSTR_GV(session->zid), ZSTR_GV(session->peer_zid));
453 			}
454 
455 			ZRTP_LOG(2,(_ZTU_,"\tINFO! Our RS1 doesn't equal to other-side's one %s. ID=%u\n",
456 						cc->rs1.secret->_cachedflag ? " - drop verified!" : "", stream->id));
457 		}
458 
459 		if (!zrtp_memcmp(cc->rs2.peer_id.buffer, stream->messages.peer_dhpart.rs2ID, ZRTP_RSID_SIZE)) {
460 			secrets->matches |= ZRTP_BIT_RS2;
461 			if (0 == C[0]) {
462 				C[0] = &cc->rs2;
463 			}
464 		}
465 
466 
467 		if (secrets->auxs &&
468 			(!zrtp_memcmp(stream->messages.peer_dhpart.auxsID, cc->auxs.peer_id.buffer, ZRTP_RSID_SIZE)) ) {
469 			C[1] =&cc->auxs;
470 	    	secrets->matches |= ZRTP_BIT_AUX;
471 		}
472 
473 		if ( secrets->pbxs &&
474 			(!zrtp_memcmp(stream->messages.peer_dhpart.pbxsID, cc->pbxs.peer_id.buffer, ZRTP_RSID_SIZE)) ) {
475 			C[2] = &cc->pbxs;
476 			secrets->matches |= ZRTP_BIT_PBX;
477 		}
478 
479 		/* Finally hashing matched shared secrets */
480 		for (i=0; i<3; i++) {
481 			/*
482 			 * Some of the shared secrets s1 through s5 may have lengths of zero
483 			 * if they are null (not shared), and are each preceded by a 4-octet
484 			 * length field. For example, if s4 is null, len(s4) is 00 00 00 00,
485 			 * and s4 itself would be absent from the hash calculation, which
486 			 * means len(s5) would immediately follow len(s4).
487 			 */
488 			comp_length = C[i] ? zrtp_hton32(ZRTP_RS_SIZE) : 0;
489 			session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)&comp_length, 4);
490 			if (C[i]) {
491 				session->hash->hash_update( session->hash,
492 											 hash_ctx,
493 											 (const int8_t*)C[i]->secret->value.buffer,
494 											 C[i]->secret->value.length );
495 				ZRTP_LOG(3,(_ZTU_,"\tUse S%d in calculations.\n", i+1));
496 			}
497 		}
498 
499 		session->hash->hash_end(session->hash, hash_ctx, ZSTR_GV(cc->s0));
500 	} break; /* S0 for for DH and Preshared streams */
501 
502 	/*
503 	 * Compute all possible combinations of preshared_key:
504 	 * hash(len(rs1) | rs1 | len(auxsecret) | auxsecret | len(pbxsecret) | pbxsecret)
505 	 * Find matched preshared_key and derive S0 from it:
506 	 * s0 = KDF(preshared_key, "ZRTP Stream Key", KDF_Context, negotiated hash length)
507 	 *
508 	 * INFO: Take into account that RS1 and RS2 may be swapped.
509 	 * If no matched were found - generate DH commit.
510 	 * ========================================================================
511 	 */
512 	case ZRTP_STREAM_MODE_PRESHARED:
513 	{
514 		zrtp_status_t s				= zrtp_status_ok;
515 		zrtp_string32_t presh_key	= ZSTR_INIT_EMPTY(presh_key);
516 
517 		ZRTP_LOG(3,(_ZTU_,"\tDERIVE S0 for PRESHARED from cached secret. ID=%u\n", stream->id));
518 
519 		/* Use the same hash as we used for Commitment */
520 		if (is_initiator)
521 		{
522 			s = _zrtp_compute_preshared_key( session,
523 											 ZSTR_GV(session->secrets.rs1->value),
524 											 (session->secrets.auxs->_cachedflag) ? ZSTR_GV(session->secrets.auxs->value) : NULL,
525 											 (session->secrets.pbxs->_cachedflag) ? ZSTR_GV(session->secrets.pbxs->value) : NULL,
526 											 ZSTR_GV(presh_key),
527 											 NULL);
528 			if (zrtp_status_ok != s) {
529 				return s;
530 			}
531 
532 			secrets->matches |= ZRTP_BIT_RS1;
533 			if (session->secrets.auxs->_cachedflag) {
534 				secrets->matches |= ZRTP_BIT_AUX;
535 			}
536 			if (session->secrets.pbxs->_cachedflag) {
537 				secrets->matches |= ZRTP_BIT_PBX;
538 			}
539 		}
540 		/*
541 		 * Let's find appropriate hv key for Responder:
542 		 * <RS1, 0, 0>, <RS1, AUX, 0>, <RS1, 0, PBX>, <RS1, AUX, PBX>.
543 		 */
544 		else
545 		{
546 			int res=-1;
547 			char* peer_key_id		= (char*)stream->messages.peer_commit.hv+ZRTP_HV_NONCE_SIZE;
548 			zrtp_string8_t key_id	= ZSTR_INIT_EMPTY(key_id);
549 
550 			do {
551 				/* RS1 MUST be available at this stage.*/
552 				s = _zrtp_compute_preshared_key( session,
553 												 ZSTR_GV(secrets->rs1->value),
554 												 NULL,
555 												 NULL,
556 												 ZSTR_GV(presh_key),
557 												 ZSTR_GV(key_id));
558 				if (zrtp_status_ok == s) {
559 					res = zrtp_memcmp(peer_key_id, key_id.buffer, ZRTP_HV_KEY_SIZE);
560 					if (0 == res) {
561 						secrets->matches |= ZRTP_BIT_RS1;
562 						break;
563 					}
564 				}
565 
566 				if (session->secrets.pbxs->_cachedflag)
567 				{
568 					s = _zrtp_compute_preshared_key( session,
569 													 ZSTR_GV(secrets->rs1->value),
570 													 NULL,
571 													 ZSTR_GV(secrets->pbxs->value),
572 													 ZSTR_GV(presh_key),
573 													 ZSTR_GV(key_id));
574 					if (zrtp_status_ok == s) {
575 						res = zrtp_memcmp(peer_key_id, key_id.buffer, ZRTP_HV_KEY_SIZE);
576 						if (0 == res) {
577 							secrets->matches |= ZRTP_BIT_PBX;
578 							break;
579 						}
580 					}
581 				}
582 
583 				if (session->secrets.auxs->_cachedflag)
584 				{
585 					s = _zrtp_compute_preshared_key( session,
586 													 ZSTR_GV(secrets->rs1->value),
587 													 ZSTR_GV(secrets->auxs->value),
588 													 NULL,
589 													 ZSTR_GV(presh_key),
590 													 ZSTR_GV(key_id));
591 					if (zrtp_status_ok == s) {
592 						res = zrtp_memcmp(peer_key_id, key_id.buffer, ZRTP_HV_KEY_SIZE);
593 						if (0 == res) {
594 							secrets->matches |= ZRTP_BIT_AUX;
595 							break;
596 						}
597 					}
598 				}
599 
600 				if ((session->secrets.pbxs->_cachedflag) && (session->secrets.auxs->_cachedflag))
601 				{
602 					s = _zrtp_compute_preshared_key( session,
603 													 ZSTR_GV(secrets->rs1->value),
604 													 ZSTR_GV(secrets->auxs->value),
605 													 ZSTR_GV(secrets->pbxs->value),
606 													 ZSTR_GV(presh_key),
607 													 ZSTR_GV(key_id));
608 					if (zrtp_status_ok == s) {
609 						res = zrtp_memcmp(peer_key_id, key_id.buffer, ZRTP_HV_KEY_SIZE);
610 						if (0 == res) {
611 							secrets->matches |= ZRTP_BIT_AUX;
612 							secrets->matches |= ZRTP_BIT_PBX;
613 							break;
614 						}
615 					}
616 				}
617 
618 			} while (0);
619 
620 			if (0 != res) {
621 				ZRTP_LOG(3,(_ZTU_,"\tINFO! Matched Key wasn't found - initate DH exchange.\n"));
622 				secrets->cached = 0;
623 				secrets->rs1->_cachedflag = 0;
624 
625 				_zrtp_machine_start_initiating_secure(stream);
626 				return zrtp_status_ok;
627 			}
628 		}
629 
630 		ZRTP_LOG(3,(_ZTU_,"\tUse RS1, %s, %s in calculations.\n",
631 					   (session->secrets.matches & ZRTP_BIT_AUX) ? "AUX" : "NULL",
632 					   (session->secrets.matches & ZRTP_BIT_PBX) ? "PBX" : "NULL"));
633 
634 		_zrtp_kdf( stream,
635 				   ZSTR_GV(presh_key),
636 				   ZSTR_GV(zrtp_presh_label),
637 				   ZSTR_GV(stream->protocol->cc->kdf_context),
638 				   session->hash->digest_length,
639 				   ZSTR_GV(cc->s0));
640 	} break;
641 
642 
643 	/*
644 	 * For FAST Multistream:
645 	 * s0n = KDF(ZRTPSess, "ZRTP Multistream Key", KDF_Context, negotiated hash length)
646 	 * ========================================================================
647 	 */
648 	case ZRTP_STREAM_MODE_MULT:
649 	{
650 		ZRTP_LOG(3,(_ZTU_,"\tDERIVE S0 for MULTISTREAM from ZRTP Session key... ID=%u\n", stream->id));
651 		_zrtp_kdf( stream,
652 				   ZSTR_GV(session->zrtpsess),
653 				   ZSTR_GV(zrtp_multi_label),
654 				   ZSTR_GV(stream->protocol->cc->kdf_context),
655 				   session->hash->digest_length,
656 				   ZSTR_GV(cc->s0));
657 	} break;
658 
659 	default: break;
660 	}
661 
662 
663 	/*
664 	 * Compute ZRTP session key for FULL streams only:
665 	 * ZRTPSess = KDF(s0, "ZRTP Session Key", KDF_Context, negotiated hash length)
666 	 */
667 	if (!ZRTP_IS_STREAM_MULT(stream)) {
668 		if (session->zrtpsess.length == 0) {
669 			_zrtp_kdf( stream,
670 					   ZSTR_GV(cc->s0),
671 					   ZSTR_GV(zrtp_sess_label),
672 					   ZSTR_GV(stream->protocol->cc->kdf_context),
673 					   session->hash->digest_length,
674 					   ZSTR_GV(session->zrtpsess));
675 		}
676 	}
677 
678 	return zrtp_status_ok;
679 }
680 
681 
682 /*----------------------------------------------------------------------------*/
_zrtp_set_public_value(zrtp_stream_t * stream,int is_initiator)683 zrtp_status_t _zrtp_set_public_value( zrtp_stream_t *stream,
684 									  int is_initiator)
685 {
686 	/*
687 	 * This function performs the following actions according to ZRTP draft 5.6
688 	 * a) Computes total hash;
689 	 * b) Calculates DHResult;
690 	 * c) Computes final stream key S0, based on DHSS and retained secrets;
691 	 * d) Computes HMAC Key and ZRTP key;
692 	 * e) Computes srtp keys and salts and creates srtp session.
693 	 */
694 
695 	zrtp_session_t *session = stream->session;
696 	zrtp_proto_crypto_t* cc = stream->protocol->cc;
697 	void* hash_ctx = NULL;
698 
699 	static const zrtp_string32_t hmac_keyi_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_INITIATOR_HMAKKEY_STR);
700 	static const zrtp_string32_t hmac_keyr_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_RESPONDER_HMAKKEY_STR);
701 
702     static const zrtp_string32_t srtp_mki_label	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_INITIATOR_KEY_STR);
703     static const zrtp_string32_t srtp_msi_label	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_INITIATOR_SALT_STR);
704     static const zrtp_string32_t srtp_mkr_label	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_RESPONDER_KEY_STR);
705     static const zrtp_string32_t srtp_msr_label	= ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_RESPONDER_SALT_STR);
706 
707 	static const zrtp_string32_t zrtp_keyi_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_INITIATOR_ZRTPKEY_STR);
708 	static const zrtp_string32_t zrtp_keyr_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_RESPONDER_ZRTPKEY_STR);
709 
710 	uint32_t cipher_key_length = (ZRTP_CIPHER_AES128 == session->blockcipher->base.id) ? 16 : 32;
711 
712 	const zrtp_string32_t *output_mk_label;
713     const zrtp_string32_t *output_ms_label;
714     const zrtp_string32_t *input_mk_label;
715     const zrtp_string32_t *input_ms_label;
716 	const zrtp_string32_t *hmac_key_label;
717 	const zrtp_string32_t *peer_hmac_key_label;
718 	const zrtp_string32_t *zrtp_key_label;
719 	const zrtp_string32_t *peer_zrtp_key_label;
720 
721     /* Define roles and prepare structures */
722     if (is_initiator) {
723 		output_mk_label		= &srtp_mki_label;
724 		output_ms_label		= &srtp_msi_label;
725 		input_mk_label		= &srtp_mkr_label;
726 		input_ms_label		= &srtp_msr_label;
727 		hmac_key_label		= &hmac_keyi_label;
728 		peer_hmac_key_label	= &hmac_keyr_label;
729 		zrtp_key_label		= &zrtp_keyi_label;
730 		peer_zrtp_key_label	= &zrtp_keyr_label;
731     } else {
732 		output_mk_label		= &srtp_mkr_label;
733 		output_ms_label		= &srtp_msr_label;
734 		input_mk_label		= &srtp_mki_label;
735 		input_ms_label		= &srtp_msi_label;
736 		hmac_key_label		= &hmac_keyr_label;
737 		peer_hmac_key_label	= &hmac_keyi_label;
738 		zrtp_key_label		= &zrtp_keyr_label;
739 		peer_zrtp_key_label	= &zrtp_keyi_label;
740     }
741 
742 	ZRTP_LOG(3, (_ZTU_,"---------------------------------------------------\n"));
743 	ZRTP_LOG(3,(_ZTU_,"\tSWITCHING TO SRTP. ID=%u\n", zrtp_log_mode2str(stream->mode), stream->id));
744 	ZRTP_LOG(3,(_ZTU_,"\tI %s\n", is_initiator ? "Initiator" : "Responder"));
745 
746 	/*
747 	 * Compute total messages hash:
748 	 * total_hash = hash(Hello of responder | Commit | DHPart1 | DHPart2) for DH streams
749 	 * total_hash = hash(Hello of responder | Commit ) for Fast modes.
750 	 */
751 	{
752 		uint8_t* tok	 = NULL;
753 		uint16_t tok_len = 0;
754 
755 		hash_ctx = session->hash->hash_begin(session->hash);
756 		if (0 == hash_ctx) {
757 			return zrtp_status_fail;
758 		}
759 
760 		tok		= is_initiator ? (uint8_t*)&stream->messages.peer_hello : (uint8_t*) &stream->messages.hello;
761 		tok_len = is_initiator ? stream->messages.peer_hello.hdr.length : stream->messages.hello.hdr.length;
762 		tok_len = zrtp_ntoh16(tok_len)*4;
763 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)tok, tok_len);
764 
765 		tok		= is_initiator ? (uint8_t*)&stream->messages.commit : (uint8_t*)&stream->messages.peer_commit;
766 		tok_len	= is_initiator ? stream->messages.commit.hdr.length : stream->messages.peer_commit.hdr.length;
767 		tok_len = zrtp_ntoh16(tok_len)*4;
768 		session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)tok, tok_len);
769 
770 		if (ZRTP_IS_STREAM_DH(stream))
771 		{
772 			tok = (uint8_t*) (is_initiator ? &stream->messages.peer_dhpart : &stream->messages.dhpart);
773 			tok_len	= is_initiator ? stream->messages.peer_dhpart.hdr.length : stream->messages.dhpart.hdr.length;
774 			tok_len = zrtp_ntoh16(tok_len)*4;
775 			session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)tok, tok_len);
776 
777 			tok = (uint8_t*)(is_initiator ? &stream->messages.dhpart :  &stream->messages.peer_dhpart);
778 			tok_len	= is_initiator ? stream->messages.dhpart.hdr.length : stream->messages.peer_dhpart.hdr.length;
779 			tok_len = zrtp_ntoh16(tok_len)*4;
780 			session->hash->hash_update(session->hash, hash_ctx, (const int8_t*)tok, tok_len);
781 		}
782 
783 		session->hash->hash_end(session->hash, hash_ctx, ZSTR_GV(cc->mes_hash));
784 		hash_ctx = NULL;
785 	} /* total hash computing */
786 
787 	/* Total Hash is ready and we can create KDF_Context */
788 	zrtp_zstrcat(ZSTR_GV(cc->kdf_context), is_initiator ? ZSTR_GV(session->zid) : ZSTR_GV(session->peer_zid));
789 	zrtp_zstrcat(ZSTR_GV(cc->kdf_context), is_initiator ? ZSTR_GV(session->peer_zid) : ZSTR_GV(session->zid));
790 	zrtp_zstrcat(ZSTR_GV(cc->kdf_context), ZSTR_GV(cc->mes_hash));
791 
792 	/* Derive stream key S0 according to key exchange scheme */
793 	if (zrtp_status_ok != _derive_s0(stream, is_initiator)) {
794 		return zrtp_status_fail;
795 	}
796 
797     /*
798 	 * Compute HMAC keys. These values will be used after confirmation:
799 	 * hmackeyi = KDF(s0, "Initiator HMAC key", KDF_Context, negotiated hash length)
800 	 * hmackeyr = KDF(s0, "Responder HMAC key", KDF_Context, negotiated hash length)
801 	 */
802 	_zrtp_kdf( stream,
803 			   ZSTR_GV(cc->s0),
804 			   ZSTR_GVP(hmac_key_label),
805 			   ZSTR_GV(stream->protocol->cc->kdf_context),
806 			   session->hash->digest_length,
807 			   ZSTR_GV(stream->cc.hmackey));
808 	_zrtp_kdf( stream,
809 			   ZSTR_GV(cc->s0),
810 			   ZSTR_GVP(peer_hmac_key_label),
811 			   ZSTR_GV(stream->protocol->cc->kdf_context),
812 			   session->hash->digest_length,
813 			   ZSTR_GV(stream->cc.peer_hmackey));
814 
815 	/*
816 	 * Computing ZRTP keys for protection of the Confirm packet:
817 	 * zrtpkeyi = KDF(s0, "Initiator ZRTP key", KDF_Context, negotiated AES key length)
818 	 * zrtpkeyr = KDF(s0, "Responder ZRTP key", KDF_Context, negotiated AES key length)
819 	 */
820 	_zrtp_kdf( stream,
821 			   ZSTR_GV(cc->s0),
822 			   ZSTR_GVP(zrtp_key_label),
823 			   ZSTR_GV(stream->protocol->cc->kdf_context),
824 			   cipher_key_length,
825 			   ZSTR_GV(stream->cc.zrtp_key));
826 	_zrtp_kdf( stream,
827 			   ZSTR_GV(cc->s0),
828 			   ZSTR_GVP(peer_zrtp_key_label),
829 			   ZSTR_GV(stream->protocol->cc->kdf_context),
830 			   cipher_key_length,
831 			   ZSTR_GV(stream->cc.peer_zrtp_key));
832 #if (defined(ZRTP_DEBUG_ZRTP_KEYS) && ZRTP_DEBUG_ZRTP_KEYS == 1)
833 	{
834 	char print_buff[256];
835 	ZRTP_LOG(3,(_ZTU_,"\t  Messages hash:%s\n", hex2str(cc->mes_hash.buffer, cc->mes_hash.length, print_buff, sizeof(print_buff))));
836     ZRTP_LOG(3,(_ZTU_,"\t             S0:%s\n", hex2str(cc->s0.buffer, cc->s0.length, print_buff, sizeof(print_buff))));
837 	ZRTP_LOG(3,(_ZTU_,"\t      ZRTP Sess:%s\n", hex2str(session->zrtpsess.buffer, session->zrtpsess.length, print_buff, sizeof(print_buff))));
838 	ZRTP_LOG(3,(_ZTU_,"\t        hmackey:%s\n", hex2str(stream->cc.hmackey.buffer, stream->cc.hmackey.length, print_buff, sizeof(print_buff))));
839 	ZRTP_LOG(3,(_ZTU_,"\t  peer_hmackeyr:%s\n", hex2str(stream->cc.peer_hmackey.buffer, stream->cc.peer_hmackey.length, print_buff, sizeof(print_buff))));
840 	ZRTP_LOG(3,(_ZTU_,"\t       ZRTP key:%s\n", hex2str(stream->cc.zrtp_key.buffer, stream->cc.zrtp_key.length, print_buff, sizeof(print_buff))));
841 	ZRTP_LOG(3,(_ZTU_,"\t  Peer ZRTP key:%s\n", hex2str(stream->cc.peer_zrtp_key.buffer, stream->cc.peer_zrtp_key.length, print_buff, sizeof(print_buff))));
842 	}
843 #endif
844 	/*
845 	 * Preparing SRTP crypto engine:
846 	 * srtpkeyi = KDF(s0, "Initiator SRTP master key", KDF_Context, negotiated AES key length)
847 	 * srtpsalti = KDF(s0, "Initiator SRTP master salt", KDF_Context, 112)
848 	 * srtpkeyr = KDF(s0, "Responder SRTP master key", KDF_Context, negotiated AES key length)
849 	 * srtpsaltr = KDF(s0, "Responder SRTP master salt", KDF_Context, 112)
850 	 */
851 	{
852 		zrtp_srtp_profile_t iprof;
853 		zrtp_srtp_profile_t oprof;
854 
855 		ZSTR_SET_EMPTY(iprof.salt);
856 		ZSTR_SET_EMPTY(iprof.key);
857 
858 		iprof.rtp_policy.cipher			= session->blockcipher;
859 		iprof.rtp_policy.auth_tag_len	= session->authtaglength;
860 		iprof.rtp_policy.hash			= zrtp_comp_find(ZRTP_CC_HASH, ZRTP_SRTP_HASH_HMAC_SHA1, session->zrtp);
861 		iprof.rtp_policy.auth_key_len	= 20;
862 		iprof.rtp_policy.cipher_key_len = cipher_key_length;
863 
864 		zrtp_memcpy(&iprof.rtcp_policy, &iprof.rtp_policy, sizeof(iprof.rtcp_policy));
865 		iprof.dk_cipher = session->blockcipher;
866 
867 		zrtp_memcpy(&oprof, &iprof, sizeof(iprof));
868 
869 		_zrtp_kdf( stream,
870 				   ZSTR_GV(cc->s0),
871 				   ZSTR_GVP(input_mk_label),
872 				   ZSTR_GV(stream->protocol->cc->kdf_context),
873 				   cipher_key_length,
874 				   ZSTR_GV(iprof.key));
875 		_zrtp_kdf( stream,
876 				   ZSTR_GV(cc->s0),
877 				   ZSTR_GVP(input_ms_label),
878 				   ZSTR_GV(stream->protocol->cc->kdf_context),
879 				   14,
880 				   ZSTR_GV(iprof.salt));
881 		_zrtp_kdf( stream,
882 				   ZSTR_GV(cc->s0),
883 				   ZSTR_GVP(output_mk_label),
884 				   ZSTR_GV(stream->protocol->cc->kdf_context),
885 				   cipher_key_length,
886 				   ZSTR_GV(oprof.key));
887 		_zrtp_kdf( stream,
888 				   ZSTR_GV(cc->s0),
889 				   ZSTR_GVP(output_ms_label),
890 				   ZSTR_GV(stream->protocol->cc->kdf_context),
891 				   14,
892 				   ZSTR_GV(oprof.salt));
893 
894 		stream->protocol->_srtp = zrtp_srtp_create(session->zrtp->srtp_global, &iprof, &oprof);
895 
896 		/* Profiles and keys in them are not needed anymore - clear them */
897 		zrtp_memset(&iprof, 0, sizeof(iprof));
898 		zrtp_memset(&oprof, 0, sizeof(oprof));
899 
900 		if (!stream->protocol->_srtp) {
901 			ZRTP_LOG(1,(_ZTU_,"\tERROR! Can't initialize SRTP engine. ID=%u\n", stream->id));
902 			return zrtp_status_fail;
903 		}
904 	} /* SRTP initialization */
905 
906     return zrtp_status_ok;
907 }
908 
909 /*---------------------------------------------------------------------------*/
_zrtp_machine_enter_secure(zrtp_stream_t * stream)910 zrtp_status_t _zrtp_machine_enter_secure(zrtp_stream_t* stream)
911 {
912 	/*
913      * When switching to SECURE all ZRTP crypto values were already computed by
914 	 * state-machine. Then we need to have logic to manage SAS value and shared
915 	 * secrets only. So: we compute SAS, refresh secrets flags and save the
916 	 * secrets to the cache after RS2 and RS1 swapping.  We don't need any
917 	 * crypto sources any longer - destroy them.
918      */
919 
920 	zrtp_status_t s				= zrtp_status_ok;
921 	zrtp_proto_crypto_t* cc		= stream->protocol->cc;
922 	zrtp_session_t *session		= stream->session;
923 	zrtp_secrets_t *secrets		= &stream->session->secrets;
924 	uint8_t was_exp   = 0;
925 	uint64_t exp_date = 0;
926 
927 	ZRTP_LOG(3,(_ZTU_,"\tEnter state SECURE (%s).\n", zrtp_log_mode2str(stream->mode)));
928 
929 	_zrtp_cancel_send_packet_later(stream, ZRTP_NONE);
930 
931 	/*
932 	 * Compute the SAS value if it isn't computed yet. If there are several
933 	 * streams running in parallel - stream with the biggest hvi should
934 	 * generate the SAS.
935 	 */
936 	if (!session->sas1.length) {
937 		s = session->sasscheme->compute(session->sasscheme, stream, session->hash, 0);
938 		if (zrtp_status_ok != s) {
939 			_zrtp_machine_enter_initiatingerror(stream, zrtp_error_software, 1);
940 			return s;
941 		}
942 
943 
944 		ZRTP_LOG(3,(_ZTU_,"\tThis is the very first stream in sID GENERATING SAS value.\n", session->id));
945 		ZRTP_LOG(3,(_ZTU_,"\tSAS computed: <%.16s> <%.16s>.\n", session->sas1.buffer, session->sas2.buffer));
946 	}
947 
948 	/*
949 	 * Compute a new value for RS1 and store the prevoious one.
950 	 * Compute result secrets' flags.
951 	 */
952 	if (ZRTP_IS_STREAM_DH(stream))
953 	{
954 		ZRTP_LOG(3,(_ZTU_,"\tCheck expiration interval: last_use=%u ttl=%u new_ttl=%u exp=%u now=%u\n",
955 					secrets->rs1->lastused_at,
956 					secrets->rs1->ttl,
957 					stream->cache_ttl,
958 					(secrets->rs1->lastused_at + secrets->rs1->ttl),
959 					zrtp_time_now()/1000));
960 
961 		if (secrets->rs1->ttl != 0xFFFFFFFF) {
962 			exp_date = secrets->rs1->lastused_at;
963 			exp_date += secrets->rs1->ttl;
964 
965 			if (ZRTP_IS_STREAM_DH(stream) && (exp_date < zrtp_time_now()/1000)) {
966 				ZRTP_LOG(3,(_ZTU_,"\tUsing EXPIRED secrets: last_use=%u ttl=%u exp=%u now=%u\n",
967 								secrets->rs1->lastused_at,
968 								secrets->rs1->ttl,
969 								(secrets->rs1->lastused_at + secrets->rs1->ttl),
970 								zrtp_time_now()/1000));
971 				was_exp = 1;
972 			}
973 		}
974 
975 		if (!was_exp) {
976 			secrets->wrongs = secrets->matches ^ secrets->cached;
977 			secrets->wrongs &= ~ZRTP_BIT_RS2;
978 			secrets->wrongs &= ~ZRTP_BIT_PBX;
979 		}
980 	}
981 
982 	/*
983 	 * We going to update RS1 and change appropriate secrets flags. Let's back-up current values.
984 	 * Back-upped values could be used in debug purposes and in the GUI to reflect current state of the call
985 	 */
986 	if (!ZRTP_IS_STREAM_MULT(stream)) {
987 		secrets->cached_curr = secrets->cached;
988 		secrets->matches_curr = secrets->matches;
989 		secrets->wrongs_curr = secrets->wrongs;
990 	}
991 
992 
993 	ZRTP_LOG(3,(_ZTU_,"\tFlags C=%x M=%x W=%x ID=%u\n",
994 				secrets->cached, secrets->matches, secrets->wrongs, stream->id));
995 
996 	_zrtp_change_state(stream, ZRTP_STATE_SECURE);
997 	/*
998 	 * Alarm user if the following condition is TRUE for both RS1 and RS2:
999 	 * "secret is wrong if it has been restored from the cache but hasn't matched
1000 	 * with the remote one".
1001 	 */
1002 	if (session->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1003 		session->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_SECURE);
1004 	}
1005 	if (session->zrtp->cb.event_cb.on_zrtp_secure) {
1006 		session->zrtp->cb.event_cb.on_zrtp_secure(stream);
1007 	}
1008 
1009 	/* Alarm user if possible MiTM attack detected */
1010 	if (secrets->wrongs) {
1011 		session->mitm_alert_detected = 1;
1012 
1013 		if (session->zrtp->cb.event_cb.on_zrtp_security_event) {
1014 			session->zrtp->cb.event_cb.on_zrtp_security_event(stream, ZRTP_EVENT_MITM_WARNING);
1015 		}
1016 	}
1017 
1018 	/* Check for unenrollemnt first */
1019 	if ((secrets->cached & ZRTP_BIT_PBX) && !(secrets->matches & ZRTP_BIT_PBX)) {
1020 		ZRTP_LOG(2,(_ZTU_,"\tINFO! The user requires new un-enrolment - the nedpint may clear"
1021 					" the cache or perform other action. ID=%u\n", stream->id));
1022 
1023 		if (session->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1024 			session->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_USER_UNENROLLED);
1025 		}
1026 	}
1027 
1028     /*
1029 	 * Handle PBX registration, if required: If PBX already had a shared secret
1030 	 * for the ZID it leaves the cache entry unmodified. Else, it computes a new
1031 	 * one. If the PBX detects cache entry for the static shared secret, but the
1032 	 * phone does not have a matching cache entry - the PBX generates a new one.
1033 	 */
1034 	if (ZRTP_MITM_MODE_REG_SERVER == stream->mitm_mode)
1035 	{
1036 		if (secrets->matches & ZRTP_BIT_PBX) {
1037 			ZRTP_LOG(2,(_ZTU_,"\tINFO! User have been already registered - skip enrollment ritual. ID=%u\n", stream->id));
1038 			if (session->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1039 				session->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_USER_ALREADY_ENROLLED);
1040 			}
1041 		} else {
1042 			ZRTP_LOG(2,(_ZTU_,"\tINFO! The user requires new enrolment - generate new MiTM secret. ID=%u\n", stream->id));
1043 			zrtp_register_with_trusted_mitm(stream);
1044 			if (session->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1045 				stream->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_NEW_USER_ENROLLED);
1046 			}
1047 
1048 		}
1049 	}
1050 	else if (ZRTP_MITM_MODE_REG_CLIENT == stream->mitm_mode)
1051 	{
1052 		if (session->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1053 			session->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_CLIENT_ENROLLMENT);
1054 		}
1055 	}
1056 
1057 	/*
1058 	 * Compute new RS for FULL DH streams only. Don't update RS1 if cache TTL is 0
1059 	 */
1060 	if (ZRTP_IS_STREAM_DH(stream))
1061 	{
1062 		static const zrtp_string32_t rss_label = ZSTR_INIT_WITH_CONST_CSTRING(ZRTP_RS_STR);
1063 
1064 		if (stream->cache_ttl > 0) {
1065 			/* Replace RS2 with RS1 */
1066 			zrtp_sys_free(secrets->rs2);
1067 			secrets->rs2 = secrets->rs1;
1068 
1069 			secrets->rs1 = _zrtp_alloc_shared_secret(session);
1070 			if (!secrets->rs1) {
1071 				_zrtp_machine_enter_initiatingerror(stream, zrtp_error_software, 1);
1072 				return zrtp_status_fail;
1073 			}
1074 
1075 			/*
1076 			 * Compute new RS1 based on previous one and S0:
1077 			 * rs1 = KDF(s0, "retained secret", KDF_Context, negotiated hash length)
1078 			 */
1079 			_zrtp_kdf( stream,
1080 					   ZSTR_GV(cc->s0),
1081 					   ZSTR_GV(rss_label),
1082 					   ZSTR_GV(cc->kdf_context),
1083 					   ZRTP_HASH_SIZE,
1084 					   ZSTR_GV(secrets->rs1->value));
1085 
1086 			/*
1087 			 * Mark secrets as cached: RS1 have been just generated and cached;
1088 			 * RS2 is cached if previous secret was cached as well.
1089 			 */
1090 			secrets->rs1->_cachedflag = 1;
1091 			secrets->cached |= ZRTP_BIT_RS1;
1092 			secrets->matches |= ZRTP_BIT_RS1;
1093 			if (secrets->rs2->_cachedflag) {
1094 				secrets->cached |= ZRTP_BIT_RS2;
1095 			}
1096 
1097 			/* Let's update the TTL interval for the new secret */
1098 			secrets->rs1->ttl = stream->cache_ttl;
1099 			secrets->rs1->lastused_at = (uint32_t)(zrtp_time_now()/1000);
1100 
1101 			/* If possible MiTM attach detected - postpone storing the cache until after the user verify the SAS */
1102 			if (!session->mitm_alert_detected) {
1103 				if (session->zrtp->cb.cache_cb.on_put) {
1104 					session->zrtp->cb.cache_cb.on_put( ZSTR_GV(session->zid),
1105 													   ZSTR_GV(session->peer_zid),
1106 													   secrets->rs1);
1107 				}
1108 			}
1109 
1110 			{
1111 			uint32_t verifiedflag = 0;
1112 			char buff[128];
1113 			if (session->zrtp->cb.cache_cb.on_get_verified) {
1114 				session->zrtp->cb.cache_cb.on_get_verified( ZSTR_GV(session->zid),
1115 															ZSTR_GV(session->peer_zid),
1116 															&verifiedflag);
1117 			}
1118 
1119 			ZRTP_LOG(3,(_ZTU_,"\tNew secret was generated:\n"));
1120 			ZRTP_LOG(3,(_ZTU_,"\t\tRS1 value:<%s>\n",
1121 						hex2str(secrets->rs1->value.buffer, secrets->rs1->value.length, buff, sizeof(buff))));
1122 			ZRTP_LOG(3,(_ZTU_,"\t\tTTL=%u, flags C=%x M=%x W=%x V=%d\n",
1123 						secrets->rs1->ttl, secrets->cached, secrets->matches, secrets->wrongs, verifiedflag));
1124 			}
1125 		} /* for TTL > 0 only */
1126 		else {
1127 			if (session->zrtp->cb.cache_cb.on_put) {
1128 				secrets->rs1->ttl = 0;
1129 				session->zrtp->cb.cache_cb.on_put( ZSTR_GV(session->zid),
1130 												   ZSTR_GV(session->peer_zid),
1131 												   secrets->rs1);
1132 			}
1133 		}
1134 	} /* For DH mode only */
1135 
1136 
1137 	if (session->zrtp->cb.event_cb.on_zrtp_protocol_event) {
1138 		session->zrtp->cb.event_cb.on_zrtp_protocol_event(stream, ZRTP_EVENT_IS_SECURE_DONE);
1139 	}
1140 
1141 	/* We have computed all subkeys from S0 and don't need it any longer. */
1142 	zrtp_wipe_zstring(ZSTR_GV(cc->s0));
1143 
1144 	/* Clear DH crypto context */
1145 	if (ZRTP_IS_STREAM_DH(stream)) {
1146 		bnEnd(&stream->dh_cc.peer_pv);
1147 		bnEnd(&stream->dh_cc.pv);
1148 		bnEnd(&stream->dh_cc.sv);
1149 		zrtp_wipe_zstring(ZSTR_GV(stream->dh_cc.dhss));
1150 	}
1151 
1152 	/*
1153 	 * Now, let's check if the transition to CLEAR was caused by Active/Passive rules.
1154 	 * If local endpoint is a MitM and peer MiTM linked stream is Unlimited, we
1155 	 * could break the rules and send commit to Passive endpoint.
1156 	 */
1157 	if (stream->zrtp->is_mitm && stream->peer_super_flag) {
1158 		if (stream->linked_mitm && stream->linked_mitm->peer_passive) {
1159 			if (stream->linked_mitm->state == ZRTP_STATE_CLEAR) {
1160 				ZRTP_LOG(2,(_ZTU_,"INFO: Linked Peer stream id=%u suspended in CLEAR-state due to"
1161 							" Active/Passive restrictions, but we are running in MiTM mode and "
1162 							"current peer endpoint is Super-Active. Let's Go Secure for the linked stream.\n", stream->id));
1163 
1164 				/* @note: don't use zrtp_secure_stream() wrapper as it checks for Active/Passive stuff. */
1165 				_zrtp_machine_start_initiating_secure(stream->linked_mitm);
1166 			}
1167 		}
1168 	}
1169 
1170 	/*
1171 	 * Increase calls counter for Preshared mode and reset it on DH
1172 	 */
1173 	if (session->zrtp->cb.cache_cb.on_presh_counter_get && session->zrtp->cb.cache_cb.on_presh_counter_set) {
1174 		uint32_t calls_counter = 0;
1175 		session->zrtp->cb.cache_cb.on_presh_counter_get( ZSTR_GV(session->zid),
1176 														ZSTR_GV(session->peer_zid),
1177 														&calls_counter);
1178 		if (ZRTP_IS_STREAM_DH(stream)) {
1179 			session->zrtp->cb.cache_cb.on_presh_counter_set( ZSTR_GV(session->zid),
1180 															ZSTR_GV(session->peer_zid),
1181 															0);
1182 		} else if ZRTP_IS_STREAM_PRESH(stream) {
1183 			session->zrtp->cb.cache_cb.on_presh_counter_set( ZSTR_GV(session->zid),
1184 															ZSTR_GV(session->peer_zid),
1185 															++calls_counter);
1186 		}
1187 	}
1188 
1189 	clear_crypto_sources(stream);
1190 
1191 	return zrtp_status_ok;
1192 }
1193 
1194 
1195 /*===========================================================================*/
1196 /*		Shared functions													 */
1197 /*===========================================================================*/
1198 
1199 /*----------------------------------------------------------------------------*/
_zrtp_machine_create_confirm(zrtp_stream_t * stream,zrtp_packet_Confirm_t * confirm)1200 zrtp_status_t _zrtp_machine_create_confirm( zrtp_stream_t *stream,
1201 										    zrtp_packet_Confirm_t* confirm)
1202 {
1203 	void* cipher_ctx = NULL;
1204 	zrtp_status_t s = zrtp_status_fail;
1205 	zrtp_session_t *session = stream->session;
1206 	uint32_t verifiedflag = 0;
1207 
1208 	/* hash + (padding + sig_len + flags) + ttl */
1209 	const uint8_t encrypted_body_size = ZRTP_MESSAGE_HASH_SIZE + (2 + 1 + 1) + 4;
1210 
1211 	/*
1212 	 * Create the Confirm packet according to draft 6.7
1213 	 * AES CFB vector at first, SIG length and flags octet and cache TTL at the end
1214 	 * This version doesn't support signatures so sig_length=0
1215 	 */
1216 	if (ZRTP_CFBIV_SIZE != zrtp_randstr(session->zrtp, confirm->iv, ZRTP_CFBIV_SIZE)) {
1217 		return zrtp_status_fail;
1218 	}
1219 
1220 	zrtp_memcpy(confirm->hash, stream->messages.h0.buffer, ZRTP_MESSAGE_HASH_SIZE);
1221 
1222 	if (session->zrtp->cb.cache_cb.on_get_verified) {
1223 		session->zrtp->cb.cache_cb.on_get_verified( ZSTR_GV(session->zid),
1224 												    ZSTR_GV(session->peer_zid),
1225 												    &verifiedflag);
1226 	}
1227 
1228 	confirm->expired_interval = zrtp_hton32(session->profile.cache_ttl);
1229 	confirm->flags = 0;
1230 	confirm->flags |= session->profile.disclose_bit ? 0x01 : 0x00;
1231 	confirm->flags |= session->profile.allowclear ? 0x02 : 0x00;
1232 	confirm->flags |= verifiedflag ? 0x04 : 0x00;
1233 	confirm->flags |= (ZRTP_MITM_MODE_REG_SERVER == stream->mitm_mode) ? 0x08 : 0x00;
1234 
1235 	/* Then we need to encrypt Confirm before Hmac computing. Use AES CFB */
1236 	do
1237 	{
1238 		cipher_ctx = session->blockcipher->start( session->blockcipher,
1239 												  (uint8_t*)stream->cc.zrtp_key.buffer,
1240 												  NULL,
1241 												  ZRTP_CIPHER_MODE_CFB);
1242 		if (!cipher_ctx) {
1243 			break;
1244 		}
1245 
1246 		s = session->blockcipher->set_iv(session->blockcipher, cipher_ctx, (zrtp_v128_t*)confirm->iv);
1247 		if (zrtp_status_ok != s) {
1248 			break;
1249 		}
1250 
1251 		s = session->blockcipher->encrypt( session->blockcipher,
1252 										    cipher_ctx,
1253 										    (uint8_t*)&confirm->hash,
1254 										    encrypted_body_size );
1255 	} while(0);
1256 	if (cipher_ctx) {
1257 		session->blockcipher->stop(session->blockcipher, cipher_ctx);
1258 	}
1259 	if (zrtp_status_ok != s) {
1260 		ZRTP_LOG(1,(_ZTU_,"ERROR! failed to encrypt Confirm. s=%d ID=%u\n", s, stream->id));
1261 		return s;
1262 	}
1263 
1264 	/* Compute Hmac over encrypted part of Confirm */
1265 	{
1266 		zrtp_string128_t hmac = ZSTR_INIT_EMPTY(hmac);
1267 		s = session->hash->hmac_c( session->hash,
1268 								    stream->cc.hmackey.buffer,
1269 								    stream->cc.hmackey.length,
1270 								    (const char*)&confirm->hash,
1271 								    encrypted_body_size,
1272 								    ZSTR_GV(hmac) );
1273 		if (zrtp_status_ok != s) {
1274 			ZRTP_LOG(1,(_ZTU_,"ERROR! failed to compute Confirm hmac. s=%d ID=%u\n", s, stream->id));
1275 			return s;
1276 		}
1277 
1278         zrtp_memcpy(confirm->hmac, hmac.buffer, ZRTP_HMAC_SIZE);
1279 
1280         {
1281             char buff[512];
1282             ZRTP_LOG(3,(_ZTU_,"HMAC TRACE. COMPUTE.\n"));
1283             ZRTP_LOG(3,(_ZTU_,"\tcipher text:%s. size=%u\n",
1284                         hex2str((const char*)&confirm->hash, encrypted_body_size, buff, sizeof(buff)), encrypted_body_size));
1285             ZRTP_LOG(3,(_ZTU_,"\t        key:%s.\n",
1286                         hex2str(stream->cc.hmackey.buffer, stream->cc.hmackey.length, buff, sizeof(buff))));
1287             ZRTP_LOG(3,(_ZTU_,"\t comp hmac:%s.\n",
1288                         hex2str(hmac.buffer, hmac.length, buff, sizeof(buff))));
1289             ZRTP_LOG(3,(_ZTU_,"\t      hmac:%s.\n",
1290                         hex2str((const char*)confirm->hmac, ZRTP_HMAC_SIZE, buff, sizeof(buff))));
1291         }
1292 	}
1293 
1294 	return zrtp_status_ok;
1295 }
1296 
1297 /*----------------------------------------------------------------------------*/
_zrtp_machine_process_confirm(zrtp_stream_t * stream,zrtp_packet_Confirm_t * confirm)1298 zrtp_status_t _zrtp_machine_process_confirm( zrtp_stream_t *stream,
1299 											 zrtp_packet_Confirm_t *confirm)
1300 {
1301 	/* Compute Hmac over encrypted part of Confirm and reject malformed packets */
1302 	void* cipher_ctx = NULL;
1303 	zrtp_status_t s = zrtp_status_fail;
1304 	zrtp_session_t *session = stream->session;
1305 	zrtp_string128_t hmac = ZSTR_INIT_EMPTY(hmac);
1306 
1307 	/* hash + (padding + sig_len + flags) + ttl */
1308 	const uint8_t encrypted_body_size = ZRTP_MESSAGE_HASH_SIZE + (2 + 1 + 1) + 4;
1309 	s = session->hash->hmac_c( session->hash,
1310 							    stream->cc.peer_hmackey.buffer,
1311 							    stream->cc.peer_hmackey.length,
1312 							    (const char*)&confirm->hash,
1313 							    encrypted_body_size,
1314 							    ZSTR_GV(hmac) );
1315 	if (zrtp_status_ok != s) {
1316 		ZRTP_LOG(1,(_ZTU_,"\tERROR! failed to compute Incoming Confirm hmac. s=%d ID=%u\n", s, stream->id));
1317 		return zrtp_status_fail;
1318 	}
1319 
1320 
1321     // MARK: TRACE CONFIRM HMAC ERROR
1322 #if 0
1323     {
1324         char buff[512];
1325         ZRTP_LOG(3,(_ZTU_,"HMAC TRACE. VERIFY\n"));
1326         ZRTP_LOG(3,(_ZTU_,"\tcipher text:%s. size=%u\n",
1327                     hex2str((const char*)&confirm->hash, encrypted_body_size, buff, sizeof(buff)), encrypted_body_size));
1328         ZRTP_LOG(3,(_ZTU_,"\t        key:%s.\n",
1329                     hex2str(stream->cc.peer_hmackey.buffer, stream->cc.peer_hmackey.length, buff, sizeof(buff))));
1330         ZRTP_LOG(3,(_ZTU_,"\t comp hmac:%s.\n",
1331                     hex2str(hmac.buffer, hmac.length, buff, sizeof(buff))));
1332         ZRTP_LOG(3,(_ZTU_,"\t      hmac:%s.\n",
1333                     hex2str((const char*)confirm->hmac, ZRTP_HMAC_SIZE, buff, sizeof(buff))));
1334     }
1335 #endif
1336 
1337 
1338 	if (0 != zrtp_memcmp(confirm->hmac, hmac.buffer, ZRTP_HMAC_SIZE)) {
1339 		/*
1340 		 * Weird. Perhaps a bug in our code or our peer's code. Or it could be an attacker
1341 		 * who doesn't realize that Man-In-The-Middling the Diffie-Hellman key generation
1342 		 * but allowing the correct rsIds to pass through accomplishes nothing more than
1343 		 * forcing us to fallback to cleartext mode. If this attacker had gone ahead and deleted
1344 		 * or replaced the rsIds, then he would have been able to stay in the middle (although
1345 		 * he would of course still face the threat of a Voice Authentication Check).  On the
1346 		 * other hand if this attacker wanted to force us to fallback to cleartext mode, he could
1347 		 * have done that more simply, for example by intercepting our ZRTP HELLO packet and
1348 		 * replacing it with a normal non-ZRTP comfort noise packet.  In any case, we'll do our
1349 		 * "switch to cleartext fallback" behavior.
1350 		 */
1351 
1352 		ZRTP_LOG(2,(_ZTU_,"\tWARNING!" ZRTP_VERIFIED_RESP_WARNING_STR "ID=%u\n", stream->id));
1353 
1354 		_zrtp_machine_enter_initiatingerror(stream, zrtp_error_auth_decrypt, 1);
1355 		return zrtp_status_fail;
1356 	}
1357 
1358 	/* Then we need to decrypt Confirm body */
1359 	do {
1360 		cipher_ctx = session->blockcipher->start( session->blockcipher,
1361 												   (uint8_t*)stream->cc.peer_zrtp_key.buffer,
1362 												   NULL,
1363 												   ZRTP_CIPHER_MODE_CFB);
1364 		if (!cipher_ctx) {
1365 			break;
1366 		}
1367 
1368 		s = session->blockcipher->set_iv( session->blockcipher,
1369 										   cipher_ctx,
1370 										   (zrtp_v128_t*)confirm->iv);
1371 		if (zrtp_status_ok != s) {
1372 			break;
1373 		}
1374 
1375 		s = session->blockcipher->decrypt( session->blockcipher,
1376 										    cipher_ctx,
1377 										    (uint8_t*)&confirm->hash,
1378 										    encrypted_body_size);
1379 	} while(0);
1380 	if (cipher_ctx) {
1381 		session->blockcipher->stop(session->blockcipher, cipher_ctx);
1382 	}
1383 	if (zrtp_status_ok != s) {
1384 		ZRTP_LOG(3,(_ZTU_,"\tERROR! failed to decrypt incoming  Confirm. s=%d ID=%u\n", s, stream->id));
1385 		return s;
1386 	}
1387 
1388 	/* We have access to hash field and can check hmac of the previous message */
1389 	{
1390 		zrtp_msg_hdr_t *hdr = NULL;
1391 		char *key=NULL;
1392 		zrtp_string32_t tmphash_str = ZSTR_INIT_EMPTY(tmphash_str);
1393 		zrtp_hash_t *hash = zrtp_comp_find( ZRTP_CC_HASH, ZRTP_HASH_SHA256, stream->zrtp);
1394 
1395 		if (ZRTP_IS_STREAM_DH(stream)) {
1396 			hdr = &stream->messages.peer_dhpart.hdr;
1397 			key = (char*)confirm->hash;
1398 		} else {
1399 			hash->hash_c(hash, (char*)confirm->hash, ZRTP_MESSAGE_HASH_SIZE, ZSTR_GV(tmphash_str));
1400 
1401 			if (ZRTP_STATEMACHINE_INITIATOR == stream->protocol->type) {
1402 				hdr = &stream->messages.peer_hello.hdr;
1403 				hash->hash_c( hash,
1404 							  tmphash_str.buffer,
1405 						      ZRTP_MESSAGE_HASH_SIZE,
1406 							  ZSTR_GV(tmphash_str) );
1407 			} else {
1408 				hdr = &stream->messages.peer_commit.hdr;
1409 			}
1410 			key = tmphash_str.buffer;
1411 		}
1412 
1413 		if (0 != _zrtp_validate_message_hmac(stream, hdr, key)) {
1414 			return zrtp_status_fail;
1415 		}
1416 	}
1417 
1418 	/* Set evil bit if other-side shared session key */
1419 	stream->peer_disclose_bit = (confirm->flags & 0x01);
1420 
1421 	/* Enable ALLOWCLEAR option if only both sides support it */
1422 	stream->allowclear = (confirm->flags & 0x02) && session->profile.allowclear;
1423 
1424 	/* Drop RS1 VERIFIED flag if other side didn't verified key exchange */
1425 	if (0 == (confirm->flags & 0x04)) {
1426 		ZRTP_LOG(2,(_ZTU_,"\tINFO: Other side Confirm V=0 - set verified to 0! ID=%u\n", stream->id));
1427 		zrtp_verified_set(session->zrtp, &session->zid, &session->peer_zid, 0);
1428 	}
1429 
1430     /* Look for Enrollment replay flag */
1431 	if (confirm->flags & 0x08)
1432 	{
1433 		ZRTP_LOG(2,(_ZTU_,"\tINFO: Confirm PBX Enrolled flag is set - it is a Registration call! ID=%u\n", stream->id));
1434 
1435 		if (stream->mitm_mode != ZRTP_MITM_MODE_CLIENT) {
1436 			ZRTP_LOG(2,(_ZTU_,"\tERROR: PBX enrollment flag was received in wrong MiTM mode %s."
1437 						" ID=%u\n", zrtp_log_mode2str(stream->mode), stream->id));
1438 			_zrtp_machine_enter_initiatingerror(stream, zrtp_error_invalid_packet, 1);
1439 			return zrtp_status_fail;
1440 		}
1441 
1442 		/* Passive endpoint should ignore PBX Enrollment. */
1443 		if (ZRTP_LICENSE_MODE_PASSIVE != stream->zrtp->lic_mode) {
1444 			stream->mitm_mode = ZRTP_MITM_MODE_REG_CLIENT;
1445 		} else {
1446 			ZRTP_LOG(2,(_ZTU_,"\tINFO: Ignore PBX Enrollment flag as we are Passive ID=%u\n", stream->id));
1447 		}
1448 	}
1449 
1450 	stream->cache_ttl = ZRTP_MIN(session->profile.cache_ttl, zrtp_ntoh32(confirm->expired_interval));
1451 
1452 	/* Copy packet for future hashing */
1453 	zrtp_memcpy(&stream->messages.peer_confirm, confirm, zrtp_ntoh16(confirm->hdr.length)*4);
1454 
1455 	return zrtp_status_ok;
1456 }
1457