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  * Vitaly Rozhkov <v.rozhkov at soft-industry.com>
8  */
9 
10 #include "zrtp.h"
11 
12 #define _ZTU_ "zrtp srtp"
13 
14 #if (!defined(ZRTP_USE_EXTERN_SRTP)) || (ZRTP_USE_EXTERN_SRTP == 0)
15 
16 
17 /* constants that are used for packet's parsing */
18 #define octets_in_rtp_header   12
19 #define uint32s_in_rtp_header  3
20 #define octets_in_rtcp_header  8
21 #define uint32s_in_rtcp_header 2
22 
23 
24 /*
25   defines to make work with cipher component little bit easy
26 */
27 #define zrtp_cipher_init(self)						\
28 	( ((self)->cipher)->init(((self)->cipher)) )
29 
30 #define zrtp_cipher_start(self, key, extra_data, mode)					\
31 	( ((self)->cipher)->start(((self)->cipher),  (key), (extra_data), (mode)) )
32 
33 #define zrtp_cipher_set_iv(self, iv)									\
34 	( ((self)->cipher)->set_iv( ((self)->cipher), ((self)->ctx), (iv)) )
35 
36 #define zrtp_cipher_encrypt(self, buf, len)								\
37 	( ((self)->cipher)->encrypt( ((self)->cipher), ((self)->ctx), (buf), (len)) )
38 
39 #define zrtp_cipher_decrypt(self, buf, len)								\
40 	( ((self)->cipher)->decrypt( ((self)->cipher), ((self)->ctx), (buf), (len)) )
41 
42 #define zrtp_cipher_self_test(self)						\
43 	( ((self)->cipher)->self_test(((self)->cipher)) )
44 
45 #define zrtp_cipher_stop(self)									\
46 	( ((self)->cipher)->stop(((self)->cipher), ((self)->ctx)) )
47 
48 #define zrtp_cipher_free(self)						\
49 	( ((self)->cipher)->free(((self)->cipher)) )
50 
51 
52 
53 
54 /*===========================================================================*/
55 /*  Replay protection serve functions set									 */
56 /*===========================================================================*/
57 
58 
59 /*! \brief Allocates and initializes replay protection context. Initialize
60  * mutexes and linked lists.
61  * \return
62  * - allocated replay protection context
63  * - NULL if error
64  */
65 /*---------------------------------------------------------------------------*/
rp_init()66 zrtp_rp_ctx_t* rp_init()
67 {
68 	zrtp_rp_ctx_t *ctx = zrtp_sys_alloc(sizeof(zrtp_rp_ctx_t));
69 	if(NULL == ctx){
70 		return NULL;
71 	}
72 
73 	if(zrtp_status_ok != zrtp_mutex_init(&ctx->inc_sync)){
74 		zrtp_sys_free(ctx);
75 		return NULL;
76 	}
77 
78 	if(zrtp_status_ok != zrtp_mutex_init(&ctx->out_sync)){
79 		zrtp_mutex_destroy(ctx->inc_sync);
80 		zrtp_sys_free(ctx);
81 		return NULL;
82 	}
83 
84 	init_mlist(&ctx->inc_head.mlist);
85 	init_mlist(&ctx->out_head.mlist);
86 
87 	return ctx;
88 }
89 
90 
91 /*! \brief Deinitializes and deallocates replay protection context.
92  *	\param ctx - replay protection context
93  *	\return
94  *	- zrtp_status_ok
95  */
96 /*---------------------------------------------------------------------------*/
rp_destroy(zrtp_rp_ctx_t * ctx)97 zrtp_status_t rp_destroy(zrtp_rp_ctx_t *ctx)
98 {
99 	mlist_t *pos, *n;
100 	zrtp_rp_node_t *node = NULL;
101 
102 	/*free all existing replay protection nodes in the incoming list*/
103 	zrtp_mutex_lock(ctx->inc_sync);
104 	mlist_for_each_safe(pos, n, &ctx->inc_head.mlist){
105 		node = mlist_get_struct(zrtp_rp_node_t, mlist, pos);
106 		mlist_del(&node->mlist);
107 		zrtp_sys_free(node);
108 	}
109 	zrtp_mutex_unlock(ctx->inc_sync);
110 
111 	zrtp_mutex_destroy(ctx->inc_sync);
112 
113 	/*free all existing replay protection nodes in the outgoing list*/
114 	zrtp_mutex_lock(ctx->out_sync);
115 	mlist_for_each_safe(pos, n, &ctx->out_head.mlist){
116 		node = mlist_get_struct(zrtp_rp_node_t, mlist, pos);
117 		mlist_del(&node->mlist);
118 		zrtp_sys_free(node);
119 	}
120 	zrtp_mutex_unlock(ctx->out_sync);
121 
122 	zrtp_mutex_destroy(ctx->out_sync);
123 
124 	zrtp_sys_free(ctx);
125 	return zrtp_status_ok;
126 }
127 
128 
129 /*! \brief Finds replay protection node by given ssrc. Which linked list to search is
130  * determined by the direction param.
131  * \warning This function doesn't lock the linked list before search and is for internal usage.
132  * To find necessary replay protection node use get_rp_node() function.
133  * \param ctx - pointer to replay protection context
134  * \param direction - defines what list to search. It may have values:
135  * - RP_INCOMING_DIRECTION
136  * - RP_OUTGOING_DIRECTION
137  * \return
138  * - pointer to found replay protection node
139  * - NULL if node hasn't been found or if error
140  */
141 /*---------------------------------------------------------------------------*/
get_rp_node_non_lock(zrtp_rp_ctx_t * ctx,uint8_t direction,uint32_t ssrc)142 zrtp_rp_node_t *get_rp_node_non_lock( zrtp_rp_ctx_t *ctx,
143 									  uint8_t direction,
144 									  uint32_t ssrc)
145 {
146 	zrtp_rp_node_t *node = NULL;
147 	mlist_t *pos;
148 	mlist_t *head = NULL;
149 
150 	switch(direction){
151 	case RP_INCOMING_DIRECTION:
152 		head = &ctx->inc_head.mlist;
153 		break;
154 	case RP_OUTGOING_DIRECTION:
155 		head = &ctx->out_head.mlist;
156 		break;
157 	default:
158 		head = NULL;
159 		break;
160 	};
161 
162 	if(NULL != head){
163 		mlist_for_each(pos, head){
164 			node = mlist_get_struct(zrtp_rp_node_t, mlist, pos);
165 			if(ssrc == node->ssrc){
166 				break;
167 			}else{
168 				node = NULL;
169 			}
170 		}
171 	}
172 
173 	return node;
174 }
175 
176 
177 ///*! \brief Finds replay protection node by given ssrc. Linked list to search is
178 // *  determined by direction param.  This function locks the linked list to
179 // *  ensure exclusive access.
180 // *
181 // * \param ctx - pointer to replay protection context
182 // * \param direction - defines what list to search. It may have values:
183 // * - RP_INCOMING_DIRECTION
184 // * - RP_OUTGOING_DIRECTION
185 // * \param ssrc - value by which search will be made
186 // * \return
187 // * - pointer to found replay protection node
188 // * - NULL if node hasn't been found or if error
189 // */
190 ///*---------------------------------------------------------------------------*/
191 //zrtp_rp_node_t *get_rp_node(zrtp_rp_ctx_t *ctx, uint8_t direction, uint32_t ssrc)
192 //{
193 //	zrtp_rp_node_t *node = NULL;
194 //	zrtp_mutex_t *sync = NULL;
195 //
196 //	switch(direction){
197 //	case RP_INCOMING_DIRECTION:
198 //		sync = ctx->inc_sync;
199 //		break;
200 //	case RP_OUTGOING_DIRECTION:
201 //		sync = ctx->out_sync;
202 //		break;
203 //	default:
204 //		sync = NULL;
205 //		break;
206 //	};
207 //
208 //	if(NULL != sync){
209 //		zrtp_mutex_lock(sync);
210 //		node = get_rp_node_non_lock(ctx, direction, ssrc);
211 //		zrtp_mutex_unlock(sync);
212 //	}
213 //
214 //	return node;
215 //}
216 
217 /*! \brief Allocates new replay protection node for given direction and ssrc and adds it into
218  * appropriate linked list.
219  * \warning This function is for internal usage. Use add_rp_node() and add_rp_node_unique().
220  * \param srtp_ctx - pointer to SRTP ctx related with created node. Used for removing node on SRTP session destruction.
221  * \param ctx - pointer to replay protection context
222  * \param direction - defines in which list newly created node will be inserted. It may have values:
223  * - RP_INCOMING_DIRECTION
224  * - RP_OUTGOING_DIRECTION
225  * \param ssrc - newly created replay protection node key value.
226  * \param is_unique - defines what should be returned when replay protection node
227  * with given direction and ssrc values already exists:
228  * - pointer to existing node if is_unique == 0
229  * - NULL if is_unique == 1
230  * \return
231  * - pointer to newly created replay protection node
232  * - pointer to existing replay protection node
233  * - NULL if is_unique == 1 and needed replay protection node already exists or if error
234  */
235 /*---------------------------------------------------------------------------*/
add_rp_node_ex(zrtp_srtp_ctx_t * srtp_ctx,zrtp_rp_ctx_t * ctx,uint8_t direction,uint32_t ssrc,uint8_t is_unique)236 zrtp_rp_node_t *add_rp_node_ex( zrtp_srtp_ctx_t *srtp_ctx,
237 								zrtp_rp_ctx_t *ctx,
238 							    uint8_t direction,
239 								uint32_t ssrc,
240 								uint8_t is_unique)
241 {
242 	zrtp_rp_node_t *node = NULL;
243 	zrtp_mutex_t *sync = NULL;
244 	mlist_t *head = NULL;
245 
246 	switch(direction){
247 	case RP_INCOMING_DIRECTION:
248 		sync = ctx->inc_sync;
249 		head = &ctx->inc_head.mlist;
250 		break;
251 	case RP_OUTGOING_DIRECTION:
252 		sync = ctx->out_sync;
253 		head = &ctx->out_head.mlist;
254 		break;
255 	default:
256 		sync = NULL;
257 		head = NULL;
258 		break;
259 	};
260 
261 	if(NULL != sync && NULL != head){
262 		zrtp_mutex_lock(sync);
263 		do{
264 			node = get_rp_node_non_lock(ctx, direction, ssrc);
265 
266 			/*create new node if not found*/
267 			if(NULL == node){
268 				node = zrtp_sys_alloc(sizeof(zrtp_rp_node_t));
269 				if(NULL == node){
270 					break;
271 				}
272 				/*clean sliding window and on-top sequence number value*/
273 				zrtp_memset(node, 0, sizeof(zrtp_rp_node_t));
274 				node->ssrc = ssrc;
275 				node->srtp_ctx = srtp_ctx;
276 				mlist_add_tail(head, &node->mlist);
277 #if ZRTP_DEBUG_SRTP_KEYS
278 				ZRTP_LOG(3,(_ZTU_,"\tadd %s rp node. ssrc[%u] srtp_ctx[0x%08x]",
279 							direction==RP_INCOMING_DIRECTION?"incoming":"outgoing\n",
280 							zrtp_ntoh32(node->ssrc), node->srtp_ctx));
281 #endif
282 			}else if(is_unique){
283 				// ???: why do we need unique mode at all?
284 				node = NULL;
285 			}
286 
287 		}while(0);
288 		zrtp_mutex_unlock(sync);
289 	}
290 
291 	return node;
292 }
293 
294 /*! \brief Allocates new replay protection node for given direction and ssrc and adds it into
295  * appropriate linked list. This function is based on add_rp_node_ex().
296  * \param srtp_ctx - pointer to SRTP ctx related with created node. Used for removing node on SRTP session destruction.
297  * \param ctx - pointer to replay protection context
298  * \param direction - defines in which list newly created node will be inserted. It may have values:
299  * - RP_INCOMING_DIRECTION
300  * - RP_OUTGOING_DIRECTION
301  * \param ssrc - newly created replay protection node key value.
302  * \return
303  * - pointer to newly created replay protection node
304  * - pointer to existing replay protection node
305  * - NULL if error
306  */
add_rp_node(zrtp_srtp_ctx_t * srtp_ctx,zrtp_rp_ctx_t * ctx,uint8_t direction,uint32_t ssrc)307 zrtp_rp_node_t *add_rp_node(zrtp_srtp_ctx_t *srtp_ctx, zrtp_rp_ctx_t *ctx, uint8_t direction, uint32_t ssrc){
308 	/*not-unique mode*/
309 	// ???: why do we need unique mode at all?
310 	return add_rp_node_ex(srtp_ctx, ctx, direction, ssrc, 0);
311 }
312 
313 ///*! \brief Allocates new replay protection node for given direction and ssrc and adds it into
314 // * appropriate linked list. This function is based on add_rp_node_ex().
315 // * \param srtp_ctx - pointer to SRTP ctx related with created node. Used for removing node on SRTP session destruction.
316 // * \param ctx - pointer to replay protection context
317 // * \param direction - defines in which list newly created node will be inserted. It may have values:
318 // * - RP_INCOMING_DIRECTION
319 // * - RP_OUTGOING_DIRECTION
320 // * \param ssrc - newly created replay protection node key value.
321 // * \return
322 // * - pointer to newly created replay protection node
323 // * - NULL if error or if needed node already exists
324 // */
325 //zrtp_rp_node_t *add_rp_node_unique(zrtp_srtp_ctx_t *srtp_ctx, zrtp_rp_ctx_t *ctx, uint8_t direction, uint32_t ssrc){
326 //	/*unique mode*/
327 //	return add_rp_node_ex(srtp_ctx, ctx, direction, ssrc, 1);
328 //}
329 
330 /*! \brief Removes replay protection node with given ssrc from linked list defined by direction value.
331  * \param ctx - pointer to replay protection context
332  * \param direction - defines from which list replay protection node will be removed. It may have values:
333  * - RP_INCOMING_DIRECTION
334  * - RP_OUTGOING_DIRECTION
335  * \param ssrc - key value of replay protection node to remove
336  * \return
337  * - zrtp_status_ok if replay protection node has been removed successfully
338  * - zrtp_status_fail if node hasn't been found
339  */
340 /*---------------------------------------------------------------------------*/
remove_rp_node(zrtp_rp_ctx_t * ctx,uint8_t direction,uint32_t ssrc)341 zrtp_status_t remove_rp_node(zrtp_rp_ctx_t *ctx, uint8_t direction, uint32_t ssrc){
342 	zrtp_rp_node_t *node = NULL;
343 	zrtp_mutex_t *sync = NULL;
344 	zrtp_status_t res = zrtp_status_fail;
345 
346 	switch(direction){
347 	case RP_INCOMING_DIRECTION:
348 		sync = ctx->inc_sync;
349 		break;
350 	case RP_OUTGOING_DIRECTION:
351 		sync = ctx->out_sync;
352 		break;
353 	default:
354 		sync = NULL;
355 		break;
356 	};
357 
358 	if(NULL != sync){
359 		zrtp_mutex_lock(sync);
360 		node = get_rp_node_non_lock(ctx, direction, ssrc);
361 		if(NULL != node){
362 			mlist_del(&node->mlist);
363 			zrtp_sys_free(node);
364 			res = zrtp_status_ok;
365 		}
366 		zrtp_mutex_unlock(sync);
367 	}
368 
369 	return res;
370 }
371 
372 
remove_rp_nodes_by_srtp_ctx(zrtp_srtp_ctx_t * srtp_ctx,zrtp_rp_ctx_t * ctx)373 zrtp_status_t remove_rp_nodes_by_srtp_ctx(zrtp_srtp_ctx_t *srtp_ctx, zrtp_rp_ctx_t *ctx){
374 	zrtp_status_t res = zrtp_status_ok;
375 	zrtp_rp_node_t *node = NULL;
376 	mlist_t *pos, *n;
377 
378 	if((NULL == srtp_ctx) || (NULL == ctx)){
379 		return zrtp_status_bad_param;
380 	}
381 
382 	/* Walk over incoming nodes list */
383 	zrtp_mutex_lock(ctx->inc_sync);
384 	mlist_for_each_safe(pos, n, &ctx->inc_head.mlist){
385 		node = mlist_get_struct(zrtp_rp_node_t, mlist, pos);
386 		if((NULL != node->srtp_ctx) && (node->srtp_ctx == srtp_ctx)){
387 #if ZRTP_DEBUG_SRTP_KEYS
388 			ZRTP_LOG(3,(_ZTU_,"\tremove incoming rp node. ssrc[%u] srtp_ctx[0x%08x]\n",
389 						zrtp_ntoh32(node->ssrc), node->srtp_ctx));
390 #endif
391 			mlist_del(&node->mlist);
392 			zrtp_sys_free(node);
393 		}
394 	}
395 	zrtp_mutex_unlock(ctx->inc_sync);
396 
397 	/* Walk over outgoing nodes list */
398 	zrtp_mutex_lock(ctx->out_sync);
399 	mlist_for_each_safe(pos, n, &ctx->out_head.mlist){
400 		node = mlist_get_struct(zrtp_rp_node_t, mlist, pos);
401 		if((NULL != node->srtp_ctx) && (node->srtp_ctx == srtp_ctx)){
402 #if ZRTP_DEBUG_SRTP_KEYS
403 			ZRTP_LOG(3,(_ZTU_,"\tremove outgoing rp node. ssrc[%u] srtp_ctx[0x%08x]\n",
404 						zrtp_ntoh32(node->ssrc), node->srtp_ctx));
405 #endif
406 			mlist_del(&node->mlist);
407 			zrtp_sys_free(node);
408 		}
409 	}
410 	zrtp_mutex_unlock(ctx->out_sync);
411 
412 	return res;
413 }
414 
415 
416 /*===========================================================================*/
417 /*  Replay protection mechanism functions set								 */
418 /*===========================================================================*/
419 
420 
421 /*! \brief This function is used for RTCP replay protection to generate next sequence number
422  * of outgoing RTCP packet. If the sequence number is too large it returns zrtp_status_key_expired.
423  * See RFC3711 for more details.
424  * \param srtp_rp - pointer to replay protection engine data
425  * \return
426  * - zrtp_status_key_expired if next sequence number is too large
427  * - zrtp_status_ok otherwise
428  */
zrtp_srtp_rp_increment(zrtp_srtp_rp_t * srtp_rp)429 zrtp_status_t zrtp_srtp_rp_increment(zrtp_srtp_rp_t *srtp_rp){
430 
431 	if(srtp_rp->seq++ > 0x7fffffff){
432 		return zrtp_status_key_expired;
433 	}else{
434 		return zrtp_status_ok;
435 	}
436 }
437 
438 /*! \brief Returns current on-top sequence number. This function is used for RTCP
439  * replay protection.
440  * \param srtp_rp - pointer to replay protection engine data
441  * \return current on-top sequence number
442  */
zrtp_srtp_rp_get_value(zrtp_srtp_rp_t * srtp_rp)443 uint32_t zrtp_srtp_rp_get_value(zrtp_srtp_rp_t *srtp_rp){
444 	return srtp_rp->seq;
445 }
446 
447 
448 /*! \brief This function checks packet sequence number position relative to
449  * sliding window current position and makes the decision to accept or discard packet.
450  * \param srtp_rp - pointer to replay protection engine data
451  * \param packet - pointer to packet structure
452  * \return
453  * - zrtp_status_ok if packet must be accepted
454  * - zrtp_status_old_pkt if packet sequence number is lower than lowest sequence number
455  * which can be into the sliding window at the current time. In this case packet must be discarded.
456  * - zrtp_status_fail if packet must be discarded
457  */
458 /*---------------------------------------------------------------------------*/
zrtp_srtp_rp_check(zrtp_srtp_rp_t * srtp_rp,zrtp_rtp_info_t * packet)459 zrtp_status_t zrtp_srtp_rp_check(zrtp_srtp_rp_t *srtp_rp, zrtp_rtp_info_t *packet)
460 {
461 	int32_t delta = packet->seq - srtp_rp->seq;
462 	if(delta > 0){
463 		/*if delta is positive, it's good*/
464 		return zrtp_status_ok;
465 	}else if(ZRTP_SRTP_WINDOW_WIDTH-1 + delta < 0){
466 		/*if delta is lower than the bitmask, it's bad*/
467 		return zrtp_status_old_pkt;
468 	}else{
469 		if(1 == zrtp_bitmap_get_bit(srtp_rp->window, ZRTP_SRTP_WINDOW_WIDTH-1 + delta)){
470 			/*delta is within the window, so check the bitmask*/
471 			return zrtp_status_fail;
472 		}
473 	}
474 	return zrtp_status_ok;
475 }
476 
477 /*! \brief This function updates the sliding window state by setting appropriate bit and
478  * shifting the sliding window if needed.
479  * \param srtp_rp - pointer to replay protection engine data
480  * \param packet - pointer to packet structure
481  * \return
482  * - zrtp_status_ok
483  */
484 /*---------------------------------------------------------------------------*/
zrtp_srtp_rp_add(zrtp_srtp_rp_t * srtp_rp,zrtp_rtp_info_t * packet)485 zrtp_status_t zrtp_srtp_rp_add(zrtp_srtp_rp_t *srtp_rp, zrtp_rtp_info_t *packet)
486 {
487 	int32_t delta = packet->seq - srtp_rp->seq;
488 	if(delta > 0){
489 		/*	packet sequence nubmer is larger than current on-top sequence number.
490 			shift the window, set top bit and update on-top sequence number value */
491 		srtp_rp->seq = packet->seq;
492 		zrtp_bitmap_left_shift(srtp_rp->window, ZRTP_SRTP_WINDOW_WIDTH_BYTES, delta);
493 		zrtp_bitmap_set_bit(srtp_rp->window, ZRTP_SRTP_WINDOW_WIDTH-1);
494 	}else
495 
496 		/*	commented by book, 19.07.07:
497 			we need not consider case when delta == 0
498 			if(0 == delta){
499 			zrtp_bitmap_set_bit(srtp_rp->window, ZRTP_SRTP_WINDOW_WIDTH-1);
500 			}else*/
501 
502 	{
503 		/*
504 		  packet sequence number is into the sliding window.
505 		  set appropriate bit
506 		*/
507 		zrtp_bitmap_set_bit(srtp_rp->window, ZRTP_SRTP_WINDOW_WIDTH-1 + delta);
508 	}
509 
510 	return zrtp_status_ok;
511 }
512 
513 
514 /*===========================================================================*/
515 /*  Key derivation mechanism functions set									 */
516 /*===========================================================================*/
517 
518 
519 /*! \brief This function allocates key derivation context and initializes it with
520  * given master key, master salt and cipher.
521  * \param cipher - pointer to cipher that is used for key derivation
522  * \param key - pointer to master key
523  * \param salt - pointer to master salt
524  * \return
525  * - allocated key derivation context
526  * - NULL if error
527  */
528 /*---------------------------------------------------------------------------*/
zrtp_dk_init(zrtp_cipher_t * cipher,zrtp_stringn_t * key,zrtp_stringn_t * salt)529 zrtp_dk_ctx *zrtp_dk_init( zrtp_cipher_t *cipher,
530 						   zrtp_stringn_t *key,
531 						   zrtp_stringn_t *salt)
532 {
533 	zrtp_dk_ctx *ctx = NULL;
534 #if ZRTP_DEBUG_SRTP_KEYS
535 	ZRTP_LOG(3,(_ZTU_,"\tzrtp_dk_init():\n"));
536 	ZRTP_LOG(3,(_ZTU_,"\tcipher ID[%i]\n", cipher->base.id));
537 #endif
538 	do{
539 		ctx = zrtp_sys_alloc(sizeof(zrtp_dk_ctx));
540 		if(NULL == ctx){
541 			break;
542 		}
543 
544 		ctx->ctx = cipher->start(cipher, key->buffer, salt->buffer, ZRTP_CIPHER_MODE_CTR);
545 		if(NULL == ctx->ctx){
546 			zrtp_sys_free(ctx);
547 			ctx = NULL;
548 			break;
549 		}
550 
551 		ctx->cipher = cipher;
552 	}while(0);
553 
554 	return ctx;
555 }
556 
557 /*! \brief This function derives key for different purposes like SRTP encryption,
558  *	SRTP message authentication, etc. See RFC3711, "4.3.  Key Derivation" for more details.
559  * \warning This function may change length field value in the result_key variable when
560  * length is larger than max_length field value.
561  * \param ctx - pointer to key derivation context
562  * \param label - defines purpose of key to derive
563  * \param result_key - out parameter. It contains derived key on success.
564  * \return
565  * - actually derived key length
566  * - -1 if error
567  */
568 /*---------------------------------------------------------------------------*/
zrtp_derive_key(zrtp_dk_ctx * ctx,zrtp_srtp_prf_label label,zrtp_stringn_t * result_key)569 uint16_t zrtp_derive_key( zrtp_dk_ctx *ctx,
570 						  zrtp_srtp_prf_label label,
571 						  zrtp_stringn_t *result_key )
572 {
573 	zrtp_v128_t nonce;
574 	uint16_t length;
575 #if ZRTP_DEBUG_SRTP_KEYS
576 	char buffer[256];
577 	ZRTP_LOG(3,(_ZTU_,"\tzrtp_derive_key():\n"));
578 #endif
579 
580 	/* set eigth octet of nonce to <label>, set the rest of it to zero */
581 	zrtp_memset(&nonce, 0, sizeof(zrtp_v128_t));
582 	nonce.v8[7] = label;
583 #if ZRTP_DEBUG_SRTP_KEYS
584 	ZRTP_LOG(3,(_ZTU_, "\t\tcipher IV[%s]\n",
585 				   hex2str((const char*)nonce.v8, sizeof(zrtp_v128_t), (char*)buffer, sizeof(buffer))));
586 #endif
587 	zrtp_cipher_set_iv(ctx, &nonce);
588 
589 	length = (uint16_t) ZRTP_MIN(result_key->length, result_key->max_length);
590 #if ZRTP_DEBUG_SRTP_KEYS
591 	ZRTP_LOG(3,(_ZTU_, "\t\texcepced key length[%i] result key length[%i]\n", result_key->length, length));
592 #endif
593 	zrtp_memset(result_key->buffer, 0, length);
594 
595 	if(zrtp_status_ok == zrtp_cipher_encrypt(ctx, (uint8_t*)result_key->buffer, length)){
596 		result_key->length = length;
597 		return length;
598 	}else{
599 		return -1;
600 	}
601 }
602 
603 
604 /*! \brief This function deallocates key derivation context allocated by \ref zrtp_dk_init() call.
605  * \param ctx - pointer to key derivation context to deallocate
606  */
zrtp_dk_deinit(zrtp_dk_ctx * ctx)607 void zrtp_dk_deinit(zrtp_dk_ctx *ctx)
608 {
609 	zrtp_cipher_stop(ctx);
610 	zrtp_memset(ctx, 0, sizeof(zrtp_dk_ctx));
611 	zrtp_sys_free(ctx);
612 }
613 
614 
615 /*! \brief This function allocates SRTP session and two stream contexts.
616  * \return
617  * - pointer to allocated SRTP session structure
618  * - NULL if error
619  */
620 /*---------------------------------------------------------------------------*/
zrtp_srtp_alloc()621 zrtp_srtp_ctx_t * zrtp_srtp_alloc()
622 {
623 	zrtp_srtp_ctx_t *srtp_ctx = NULL;
624 
625 	do{
626 		srtp_ctx = zrtp_sys_alloc(sizeof(zrtp_srtp_ctx_t));
627 		if(NULL == srtp_ctx){
628 			break;
629 		}
630 
631 		srtp_ctx->incoming_srtp = zrtp_sys_alloc(sizeof(zrtp_srtp_stream_ctx_t));
632 		if(NULL == srtp_ctx->incoming_srtp){
633 			/*deallocate everything previously allocated on failure*/
634 			zrtp_sys_free(srtp_ctx);
635 			srtp_ctx = NULL;
636 			break;
637 		}
638 
639 		srtp_ctx->outgoing_srtp = zrtp_sys_alloc(sizeof(zrtp_srtp_stream_ctx_t));
640 		if(NULL == srtp_ctx->outgoing_srtp){
641 			/*deallocate everything previously allocated on failure*/
642 			zrtp_sys_free(srtp_ctx->incoming_srtp);
643 			zrtp_sys_free(srtp_ctx);
644 			srtp_ctx = NULL;
645 			break;
646 		}
647 
648 	}while(0);
649 
650 	return srtp_ctx;
651 }
652 
653 /*! \brief This function deallocates SRTP session structure allocated by zrtp_srtp_alloc() call.
654  * \param srtp_ctx - pointer to SRTP session structure.
655  */
zrtp_srtp_free(zrtp_srtp_ctx_t * srtp_ctx)656 void zrtp_srtp_free(zrtp_srtp_ctx_t * srtp_ctx)
657 {
658 	if (srtp_ctx)
659 	{
660 		if (srtp_ctx->incoming_srtp)
661 			zrtp_sys_free(srtp_ctx->incoming_srtp);
662 		if (srtp_ctx->outgoing_srtp)
663 			zrtp_sys_free(srtp_ctx->outgoing_srtp);
664 		zrtp_sys_free(srtp_ctx);
665 	}
666 }
667 
668 /*! \brief This function initializes stream context based on given profile.
669  * \param srtp_global - pointer to SRTP engine global context
670  * \param srtp_stream - pointer to stream context to initialize
671  * \param profile - pointer to profile for stream initialization
672  * \return
673  * - zrtp_status_ok if stream has been initialized successfully
674  * - one of \ref zrtp_status_t errors - if error
675  */
676 /*---------------------------------------------------------------------------*/
zrtp_srtp_stream_init(zrtp_srtp_global_t * srtp_global,zrtp_srtp_stream_ctx_t * srtp_stream,zrtp_srtp_profile_t * profile)677 zrtp_status_t zrtp_srtp_stream_init( zrtp_srtp_global_t *srtp_global,
678 									 zrtp_srtp_stream_ctx_t *srtp_stream,
679 									 zrtp_srtp_profile_t *profile )
680 {
681 #if ZRTP_DEBUG_SRTP_KEYS
682 	char buffer[256];
683 #endif
684 	zrtp_status_t res = zrtp_status_ok;
685 
686 	/*
687 	  TODO: use dynamic buffers for temoprary keys storing
688 
689 	  NOTE!: be sure that tmp_key contains enought buffer length to store all
690 	  of derived keys. Authentication keys may be large.
691 	*/
692 	zrtp_string128_t tmp_key = ZSTR_INIT_EMPTY(tmp_key);
693 	/*salt length is 16 bytes always*/
694 	zrtp_string16_t	tmp_salt = ZSTR_INIT_EMPTY(tmp_salt);
695 
696 	do{
697 		zrtp_dk_ctx *dk_ctx = NULL;
698 #if ZRTP_DEBUG_SRTP_KEYS
699 		ZRTP_LOG(3,(_ZTU_, "\tzrtp_srtp_stream_init():\n"));
700 #endif
701 		if(NULL == srtp_stream || NULL == profile){
702 			res = zrtp_status_bad_param;
703 			break;
704 		}
705 
706 		dk_ctx = zrtp_dk_init( profile->dk_cipher,
707 							   (zrtp_stringn_t*)&profile->key,
708 							   (zrtp_stringn_t*)&profile->salt );
709 		if(NULL == dk_ctx)
710 		{
711 			res = zrtp_status_fail;
712 			break;
713 		}
714 #if ZRTP_DEBUG_SRTP_KEYS
715 		ZRTP_LOG(3,(_ZTU_, "\t\tmaster_key[%s]\n",
716 					   hex2str(profile->key.buffer, profile->key.length, buffer, sizeof(buffer))));
717 		ZRTP_LOG(3,(_ZTU_, "\t\tmaster_salt[%s]\n",
718 					   hex2str(profile->salt.buffer, profile->salt.length, buffer, sizeof(buffer))));
719 #endif
720 
721 		/*------------ init RTP-items ----------------*/
722 		srtp_stream->rtp_cipher.cipher = profile->rtp_policy.cipher;
723 
724 		tmp_key.length = (uint16_t) profile->rtp_policy.cipher_key_len;
725 		tmp_salt.length = profile->salt.length;
726 
727 
728 		zrtp_derive_key(dk_ctx, label_rtp_encryption, (zrtp_stringn_t*)&tmp_key);
729 #if ZRTP_DEBUG_SRTP_KEYS
730 		ZRTP_LOG(3,(_ZTU_, "\t\tderive RTP encryption key[%s] label:%i\n",
731 					hex2str(tmp_key.buffer, tmp_key.length, buffer, sizeof(buffer)), label_rtp_encryption));
732 
733 #endif
734 		zrtp_derive_key(dk_ctx, label_rtp_salt, (zrtp_stringn_t*)&tmp_salt);
735 #if ZRTP_DEBUG_SRTP_KEYS
736 		ZRTP_LOG(3,(_ZTU_, "\t\tderive RTP encryption salt[%s] label:%i\n",
737 					hex2str(tmp_salt.buffer, tmp_salt.length, buffer, sizeof(buffer)), label_rtp_salt));
738 #endif
739 		srtp_stream->rtp_cipher.ctx = zrtp_cipher_start(&srtp_stream->rtp_cipher,
740 														tmp_key.buffer,
741 														tmp_salt.buffer,
742 														ZRTP_CIPHER_MODE_CTR );
743 		if(NULL == srtp_stream->rtp_cipher.ctx){
744 			zrtp_dk_deinit(dk_ctx);
745 			res = zrtp_status_fail;
746 			break;
747 		}
748 
749 		srtp_stream->rtp_auth.hash = profile->rtp_policy.hash;
750 		srtp_stream->rtp_auth.key_len = profile->rtp_policy.auth_key_len;
751 		srtp_stream->rtp_auth.tag_len = profile->rtp_policy.auth_tag_len;
752 
753 		srtp_stream->rtp_auth.key = zrtp_sys_alloc(srtp_stream->rtp_auth.key_len);
754 		if(NULL == srtp_stream->rtp_auth.key){
755 			zrtp_dk_deinit(dk_ctx);
756 			zrtp_cipher_stop(&srtp_stream->rtp_cipher);
757 			res = zrtp_status_fail;
758 			break;
759 		}
760 
761 		tmp_key.length = (uint16_t)srtp_stream->rtp_auth.key_len;
762 		zrtp_derive_key(dk_ctx, label_rtp_msg_auth, (zrtp_stringn_t*)&tmp_key);
763 		zrtp_memcpy(srtp_stream->rtp_auth.key, tmp_key.buffer, tmp_key.length);
764 #if ZRTP_DEBUG_SRTP_KEYS
765 		ZRTP_LOG(3,(_ZTU_, "\t\tderive RTP auth key[%s]\n",
766 					hex2str(tmp_key.buffer, tmp_key.length, buffer, sizeof(buffer))));
767 #endif
768 		/*--------- init RTCP-items ----------------*/
769 		srtp_stream->rtcp_cipher.cipher = profile->rtcp_policy.cipher;
770 		tmp_key.length = (uint16_t) profile->rtcp_policy.cipher_key_len;
771 
772 		tmp_salt.length = profile->salt.length;
773 		zrtp_derive_key(dk_ctx, label_rtcp_encryption, (zrtp_stringn_t*)&tmp_key);
774 		zrtp_derive_key(dk_ctx, label_rtcp_salt, (zrtp_stringn_t*)&tmp_salt);
775 
776 #if ZRTP_DEBUG_SRTP_KEYS
777 		ZRTP_LOG(3,(_ZTU_, "\t\tderive RTCP encryption key[%s]\n",
778 					hex2str(tmp_key.buffer, tmp_key.length, buffer, sizeof(buffer))));
779 		ZRTP_LOG(3,(_ZTU_, "\t\tderive RTCP encryption salt[%s]\n",
780 					   hex2str(tmp_salt.buffer, tmp_salt.length, buffer, sizeof(buffer))));
781 #endif
782 		srtp_stream->rtcp_cipher.ctx = zrtp_cipher_start(&srtp_stream->rtcp_cipher,
783 														 tmp_key.buffer,
784 														 tmp_salt.buffer,
785 														 ZRTP_CIPHER_MODE_CTR );
786 
787 		if(NULL == srtp_stream->rtcp_cipher.ctx){
788 			zrtp_dk_deinit(dk_ctx);
789 			zrtp_cipher_stop(&srtp_stream->rtp_cipher);
790 			zrtp_sys_free(srtp_stream->rtp_auth.key);
791 			res = zrtp_status_fail;
792 			break;
793 		}
794 
795 		srtp_stream->rtcp_auth.hash = profile->rtcp_policy.hash;
796 		srtp_stream->rtcp_auth.key_len = profile->rtcp_policy.auth_key_len;
797 		srtp_stream->rtcp_auth.tag_len = profile->rtcp_policy.auth_tag_len;
798 
799 		srtp_stream->rtcp_auth.key = zrtp_sys_alloc(srtp_stream->rtcp_auth.key_len);
800 		if(NULL == srtp_stream->rtcp_auth.key){
801 			zrtp_dk_deinit(dk_ctx);
802 			zrtp_cipher_stop(&srtp_stream->rtp_cipher);
803 			zrtp_sys_free(srtp_stream->rtp_auth.key);
804 			zrtp_cipher_stop(&srtp_stream->rtcp_cipher);
805 			res = zrtp_status_fail;
806 			break;
807 		}
808 
809 		tmp_key.length = (uint16_t)srtp_stream->rtcp_auth.key_len;
810 		zrtp_derive_key(dk_ctx, label_rtcp_msg_auth, (zrtp_stringn_t*)&tmp_key);
811 #if ZRTP_DEBUG_SRTP_KEYS
812 		ZRTP_LOG(3,(_ZTU_, "\t\tderive RTCP auth key[%s]\n",
813 				   hex2str(tmp_key.buffer, tmp_key.length, buffer, sizeof(buffer))));
814 #endif
815 
816 		zrtp_memcpy(srtp_stream->rtcp_auth.key, tmp_key.buffer, tmp_key.length);
817 		zrtp_dk_deinit(dk_ctx);
818 
819 		zrtp_wipe_zstring(ZSTR_GV(tmp_key));
820 		zrtp_wipe_zstring(ZSTR_GV(tmp_salt));
821 
822 	}while(0);
823 	return res;
824 }
825 
826 
827 /*! \brief This function deinitializes stream context.
828  * \param srtp_global - pointer to SRTP engine global context
829  * \param srtp_stream - pointer to steam to deinitialize
830  */
831 /*---------------------------------------------------------------------------*/
zrtp_srtp_stream_deinit(zrtp_srtp_global_t * srtp_global,zrtp_srtp_stream_ctx_t * srtp_stream)832 void zrtp_srtp_stream_deinit( zrtp_srtp_global_t *srtp_global,
833 							  zrtp_srtp_stream_ctx_t *srtp_stream )
834 {
835 	zrtp_cipher_stop(&srtp_stream->rtp_cipher);
836 	zrtp_memset(srtp_stream->rtp_auth.key, 0, srtp_stream->rtp_auth.key_len);
837 	zrtp_sys_free(srtp_stream->rtp_auth.key);
838 
839 	zrtp_cipher_stop(&srtp_stream->rtcp_cipher);
840 	zrtp_memset(srtp_stream->rtcp_auth.key, 0, srtp_stream->rtcp_auth.key_len);
841 	zrtp_sys_free(srtp_stream->rtcp_auth.key);
842 }
843 
844 
845 /*! \brief This function initializes SRTP session context.
846  * \param srtp_global - pointer to SRTP engine global context
847  * \param srtp_ctx - pointer to SRTP session context to initialize
848  * \param inc_profile - profile for incoming stream configuration;
849  * \param out_profile - profile for outgoing stream configuration.
850  * \return
851  * - zrtp_status_ok if stream has been initialized successfully
852  * - one of \ref zrtp_status_t errors - if error
853  */
854 /*---------------------------------------------------------------------------*/
zrtp_srtp_init_ctx(zrtp_srtp_global_t * srtp_global,zrtp_srtp_ctx_t * srtp_ctx,zrtp_srtp_profile_t * inc_profile,zrtp_srtp_profile_t * out_profile)855 zrtp_status_t zrtp_srtp_init_ctx(	zrtp_srtp_global_t *srtp_global,
856 									zrtp_srtp_ctx_t *srtp_ctx,
857 									zrtp_srtp_profile_t *inc_profile,
858 									zrtp_srtp_profile_t *out_profile)
859 {
860 	zrtp_status_t res = zrtp_status_ok;
861 	do{
862 		if(NULL == srtp_ctx || NULL == inc_profile || NULL == out_profile){
863 			res = zrtp_status_bad_param;
864 			break;
865 		}
866 
867 		if(zrtp_status_ok != zrtp_srtp_stream_init(srtp_global, srtp_ctx->incoming_srtp, inc_profile)){
868 			res = zrtp_status_fail;
869 			break;
870 		}
871 
872 		if(zrtp_status_ok != zrtp_srtp_stream_init(srtp_global, srtp_ctx->outgoing_srtp, out_profile)){
873 			zrtp_srtp_stream_deinit(srtp_global, srtp_ctx->incoming_srtp);
874 			res = zrtp_status_fail;
875 			break;
876 		}
877 
878 	}while(0);
879 	return res;
880 }
881 
882 
883 /*===========================================================================*/
884 /*  Public interface														 */
885 /*===========================================================================*/
886 
887 
888 /*---------------------------------------------------------------------------*/
zrtp_srtp_init(zrtp_global_t * zrtp)889 zrtp_status_t zrtp_srtp_init(zrtp_global_t *zrtp){
890 
891 	zrtp_srtp_global_t *srtp_global;
892 	zrtp->srtp_global = NULL;
893 
894 	if(EXIT_SUCCESS != zrtp_bg_gen_tabs())
895 		return zrtp_status_fail;
896 
897 	srtp_global = zrtp_sys_alloc(sizeof(zrtp_srtp_global_t));
898 	if(NULL == srtp_global){
899 		return zrtp_status_fail;
900 	}
901 	srtp_global->rp_ctx = rp_init();
902 	if(NULL == srtp_global->rp_ctx){
903 		zrtp_sys_free(srtp_global);
904 		return zrtp_status_fail;
905 	}
906 
907 	zrtp->srtp_global = srtp_global;
908 
909 	return zrtp_status_ok;
910 }
911 
zrtp_srtp_down(zrtp_global_t * zrtp)912 zrtp_status_t zrtp_srtp_down(zrtp_global_t *zrtp){
913 	zrtp_srtp_global_t *srtp_global = zrtp->srtp_global;
914 
915 	rp_destroy(srtp_global->rp_ctx);
916 	zrtp_sys_free(srtp_global);
917 	zrtp->srtp_global = NULL;
918 	return zrtp_status_ok;
919 }
920 
zrtp_srtp_create(zrtp_srtp_global_t * srtp_global,zrtp_srtp_profile_t * inc_profile,zrtp_srtp_profile_t * out_profile)921 zrtp_srtp_ctx_t * zrtp_srtp_create(	zrtp_srtp_global_t *srtp_global,
922 									zrtp_srtp_profile_t *inc_profile,
923 									zrtp_srtp_profile_t *out_profile)
924 {
925 	zrtp_srtp_ctx_t *srtp_ctx = NULL;
926 	if(NULL == inc_profile || NULL == out_profile){
927 		return NULL;
928 	}
929 
930 	do{
931 		srtp_ctx = zrtp_srtp_alloc();
932 		if(NULL == srtp_ctx){
933 			break;
934 		}
935 
936 		if(zrtp_status_ok != zrtp_srtp_init_ctx(srtp_global, srtp_ctx, inc_profile, out_profile)){
937 			zrtp_srtp_free(srtp_ctx);
938 			srtp_ctx = NULL;
939 			break;
940 		}
941 
942 	}while(0);
943 
944 	return srtp_ctx;
945 }
946 
zrtp_srtp_destroy(zrtp_srtp_global_t * srtp_global,zrtp_srtp_ctx_t * srtp_ctx)947 zrtp_status_t zrtp_srtp_destroy(zrtp_srtp_global_t *srtp_global, zrtp_srtp_ctx_t * srtp_ctx){
948 	zrtp_status_t res = zrtp_status_ok;
949 
950 	remove_rp_nodes_by_srtp_ctx(srtp_ctx, srtp_global->rp_ctx);
951 
952 	zrtp_srtp_stream_deinit(srtp_global, srtp_ctx->incoming_srtp);
953 	zrtp_srtp_stream_deinit(srtp_global, srtp_ctx->outgoing_srtp);
954 	zrtp_srtp_free(srtp_ctx);
955 
956 	return res;
957 }
958 
959 
960 /*---------------------------------------------------------------------------*/
zrtp_srtp_protect(zrtp_srtp_global_t * srtp_global,zrtp_srtp_ctx_t * srtp_ctx,zrtp_rtp_info_t * packet)961 zrtp_status_t zrtp_srtp_protect(	zrtp_srtp_global_t *srtp_global,
962 									zrtp_srtp_ctx_t *srtp_ctx,
963 									zrtp_rtp_info_t *packet)
964 {
965 	zrtp_srtp_stream_ctx_t *srtp_stream_ctx = srtp_ctx->outgoing_srtp;
966 	zrtp_rp_node_t *rp_node;
967 
968 	uint32_t *enc_start;        /* pointer to start of encrypted portion  */
969 	uint32_t *auth_start;       /* pointer to start of auth. portion      */
970 	unsigned enc_octet_len = 0; /* number of octets in encrypted portion  */
971 	uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
972 	zrtp_status_t status;
973 	ZRTP_UNALIGNED(zrtp_rtp_hdr_t) *hdr;
974 
975 	zrtp_v128_t iv;
976 	uint64_t packet_seq = 0;
977 	zrtp_string64_t	auth_tag_str = ZSTR_INIT_EMPTY(auth_tag_str);
978 	void *hash_ctx = NULL;
979 
980 	/* add new replay protection node or get existing one */
981 	rp_node = add_rp_node(srtp_ctx, srtp_global->rp_ctx, RP_OUTGOING_DIRECTION, packet->ssrc);
982 	if(NULL == rp_node){
983 		return zrtp_status_rp_fail;
984 	}
985 
986 	/* check the packet length - it must at least contain a full header */
987 	if (*(packet->length) < octets_in_rtp_header){
988 		return zrtp_status_bad_param;
989 	}
990 
991 	hdr = (zrtp_rtp_hdr_t*)(packet->packet);
992 	enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc;
993 	if (1 == hdr->x) {
994 		zrtp_rtp_hdr_xtnd_t *xtn_hdr = (zrtp_rtp_hdr_xtnd_t *)enc_start;
995 		enc_start += (zrtp_ntoh16(xtn_hdr->length) + 1);
996 	}
997 	//WIN64
998 	enc_octet_len = *(packet->length) - (uint32_t)((enc_start - (uint32_t *)hdr) << 2);
999 
1000 	auth_start = (uint32_t *)hdr;
1001 	auth_tag = (uint8_t *)hdr + *(packet->length);
1002 
1003 	status = zrtp_srtp_rp_check(&rp_node->rtp_rp, packet);
1004 	if(zrtp_status_ok != status){
1005 		return zrtp_status_rp_fail;
1006 	}
1007 	zrtp_srtp_rp_add(&rp_node->rtp_rp, packet);
1008 
1009 	iv.v32[0] = 0;
1010 	iv.v32[1] = hdr->ssrc;
1011 
1012 #ifdef ZRTP_NO_64BIT_MATH
1013 	iv.v64[1] = zrtp_hton64(make64((packet->seq) >> 16, (packet->seq) << 16));
1014 #else
1015 	iv.v64[1] = zrtp_hton64(((uint64_t)(packet->seq)) << 16);
1016 #endif
1017 	status = zrtp_cipher_set_iv(&srtp_stream_ctx->rtp_cipher, &iv);
1018 	if(status){
1019 		return zrtp_status_cipher_fail;
1020 	}
1021 
1022 	status = zrtp_cipher_encrypt(&srtp_stream_ctx->rtp_cipher, (unsigned char*)enc_start, enc_octet_len);
1023 	if(status){
1024 		return zrtp_status_cipher_fail;
1025 	}
1026 
1027 
1028 	/* shift est, put into network byte order */
1029 	packet_seq = packet->seq;
1030 #ifdef ZRTP_NO_64BIT_MATH
1031 	packet_seq = zrtp_hton64(make64((high32(packet_seq) << 16) |
1032 									(low32(packet_seq) >> 16),
1033 									low32(packet_seq) << 16));
1034 #else
1035 	packet_seq = zrtp_hton64(packet_seq << 16);
1036 #endif
1037 
1038 	hash_ctx = srtp_stream_ctx->rtp_auth.hash->hmac_begin_c( srtp_stream_ctx->rtp_auth.hash,
1039 															 (const char*)srtp_stream_ctx->rtp_auth.key,
1040 															 srtp_stream_ctx->rtp_auth.key_len );
1041 	if(NULL == hash_ctx)
1042 	{
1043 		return zrtp_status_auth_fail;
1044 	}
1045 	status = srtp_stream_ctx->rtp_auth.hash->hmac_update(	srtp_stream_ctx->rtp_auth.hash,
1046 															hash_ctx,
1047 															(const char*)auth_start,
1048 															*packet->length);
1049 	if(status)
1050 	{
1051 		return zrtp_status_auth_fail;
1052 	}
1053 	status = srtp_stream_ctx->rtp_auth.hash->hmac_update(	srtp_stream_ctx->rtp_auth.hash,
1054 															hash_ctx,
1055 															(const char*)&packet_seq,
1056 															4);
1057 	if(status)
1058 	{
1059 		return zrtp_status_auth_fail;
1060 	}
1061 	status = srtp_stream_ctx->rtp_auth.hash->hmac_end(	srtp_stream_ctx->rtp_auth.hash,
1062 														hash_ctx,
1063 														(zrtp_stringn_t*) &auth_tag_str,
1064 														srtp_stream_ctx->rtp_auth.tag_len->tag_length);
1065 	if(status)
1066 	{
1067 		return zrtp_status_auth_fail;
1068 	}
1069 
1070 	/* uncomment this for authentication debug */
1071 #if ZRTP_DEBUG_SRTP_KEYS
1072 	{
1073 		char buff[256];
1074 		ZRTP_LOG(3,(_ZTU_,
1075 					"\tzrtp_srtp_protect authentication make: npacket_seq[%s] expected auth length[%i] result auth length[%i]\n",
1076 					  hex2str((char*)&packet_seq, sizeof(packet_seq), buff, sizeof(buff)),
1077 					  srtp_stream_ctx->rtp_auth.tag_len->tag_length,
1078 					  auth_tag_str.length));
1079 		ZRTP_LOG(3,(_ZTU_, "\tauth tag[%s]\n",
1080 					hex2str(auth_tag_str.buffer, auth_tag_str.length, buff, sizeof(buff))));
1081 	}
1082 #endif
1083 	zrtp_memcpy(auth_tag, auth_tag_str.buffer, auth_tag_str.length);
1084 	*packet->length += auth_tag_str.length;
1085 
1086 	return status;
1087 }
1088 
1089 
1090 /*---------------------------------------------------------------------------*/
zrtp_srtp_unprotect(zrtp_srtp_global_t * srtp_global,zrtp_srtp_ctx_t * srtp_ctx,zrtp_rtp_info_t * packet)1091 zrtp_status_t zrtp_srtp_unprotect(	zrtp_srtp_global_t *srtp_global,
1092 									zrtp_srtp_ctx_t *srtp_ctx,
1093 									zrtp_rtp_info_t *packet)
1094 {
1095 	zrtp_srtp_stream_ctx_t *srtp_stream_ctx = srtp_ctx->incoming_srtp;
1096 	zrtp_rp_node_t *rp_node;
1097 
1098 
1099 	uint32_t *enc_start;        /* pointer to start of encrypted portion  */
1100 	uint32_t *auth_start;       /* pointer to start of auth. portion      */
1101 	unsigned enc_octet_len = 0; /* number of octets in encrypted portion  */
1102 	uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
1103 	zrtp_status_t status;
1104 	ZRTP_UNALIGNED(zrtp_rtp_hdr_t)  *hdr = NULL;
1105 
1106 
1107 	void *hash_ctx = NULL;
1108 	zrtp_v128_t iv;
1109 	int tag_len = 0;
1110 
1111 	/*add new replay protection node or get existing one*/
1112 	rp_node = add_rp_node(srtp_ctx, srtp_global->rp_ctx, RP_INCOMING_DIRECTION, packet->ssrc);
1113 	if(NULL == rp_node){
1114 		return zrtp_status_rp_fail;
1115 	}
1116 
1117 	/* check the packet length - it must at least contain a full header */
1118 	if (*(packet->length) < octets_in_rtp_header)
1119 	{
1120 		return zrtp_status_bad_param;
1121 	}
1122 
1123 	hdr = (zrtp_rtp_hdr_t*)(packet->packet);
1124 
1125 	status = zrtp_srtp_rp_check(&rp_node->rtp_rp, packet);
1126 	if(zrtp_status_ok != status){
1127 		return zrtp_status_rp_fail;
1128 	}
1129 
1130 	iv.v32[0] = 0;
1131 	iv.v32[1] = hdr->ssrc;
1132 
1133 #ifdef ZRTP_NO_64BIT_MATH
1134 	iv.v64[1] = zrtp_hton64(make64((packet->seq) >> 16, (packet->seq) << 16));
1135 #else
1136 	iv.v64[1] = zrtp_hton64((uint64_t)(packet->seq) << 16);
1137 #endif
1138 
1139 	status = zrtp_cipher_set_iv(&srtp_stream_ctx->rtp_cipher, &iv);
1140 	if(status){
1141 		return zrtp_status_cipher_fail;
1142 	}
1143 
1144 	tag_len = srtp_stream_ctx->rtp_auth.tag_len->tag_length;
1145 	hdr = (zrtp_rtp_hdr_t*)(packet->packet);
1146 
1147 	enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc;
1148 	if (1 == hdr->x) {
1149 		zrtp_rtp_hdr_xtnd_t *xtn_hdr = (zrtp_rtp_hdr_xtnd_t *)enc_start;
1150 		enc_start += (zrtp_ntoh16(xtn_hdr->length) + 1);
1151 	}
1152 	//WIN64
1153 	enc_octet_len = *(packet->length) - tag_len - (uint32_t)((enc_start - (uint32_t *)hdr) << 2);
1154 
1155 
1156 	auth_start = (uint32_t *)hdr;
1157 	auth_tag = (uint8_t *)hdr + *(packet->length) - tag_len;
1158 
1159 	if(tag_len>0){
1160 		zrtp_string64_t	auth_tag_str = ZSTR_INIT_EMPTY(auth_tag_str);
1161 
1162 		/* shift est, put into network byte order */
1163 		uint64_t packet_seq = packet->seq;
1164 #ifdef ZRTP_NO_64BIT_MATH
1165 		packet_seq = zrtp_hton64( make64((high32(packet_seq) << 16) |
1166 								  (low32(packet_seq) >> 16),
1167 								  low32(packet_seq) << 16));
1168 #else
1169 		packet_seq = zrtp_hton64(packet_seq << 16);
1170 #endif
1171 
1172 		hash_ctx = srtp_stream_ctx->rtp_auth.hash->hmac_begin_c( srtp_stream_ctx->rtp_auth.hash,
1173 																 (const char*)srtp_stream_ctx->rtp_auth.key,
1174 																 srtp_stream_ctx->rtp_auth.key_len);
1175 		if(NULL == hash_ctx){
1176 			return zrtp_status_auth_fail;
1177 		}
1178 		status = srtp_stream_ctx->rtp_auth.hash->hmac_update(	srtp_stream_ctx->rtp_auth.hash,
1179 																hash_ctx,
1180 																(const char*)auth_start,
1181 																*packet->length - tag_len);
1182 		if(status){
1183 			return zrtp_status_auth_fail;
1184 		}
1185 
1186 		status = srtp_stream_ctx->rtp_auth.hash->hmac_update(	srtp_stream_ctx->rtp_auth.hash,
1187 																hash_ctx,
1188 																(const char*)&packet_seq,
1189 																4);
1190 		if(status){
1191 			return zrtp_status_auth_fail;
1192 		}
1193 
1194 		status = srtp_stream_ctx->rtp_auth.hash->hmac_end(	srtp_stream_ctx->rtp_auth.hash,
1195 															hash_ctx,
1196 															(zrtp_stringn_t*) &auth_tag_str,
1197 															srtp_stream_ctx->rtp_auth.tag_len->tag_length);
1198 #if ZRTP_DEBUG_SRTP_KEYS
1199 		{
1200 			char buff[256];
1201 			ZRTP_LOG(3,(_ZTU_,
1202 						   "\tzrtp_srtp_unprotect authentication check. packet_seq[%s] expected auth length[%i] result auth length[%i]\n",
1203 						   hex2str((char*)&packet_seq, sizeof(packet_seq), buff, sizeof(buff)),
1204 						   srtp_stream_ctx->rtp_auth.tag_len->tag_length,
1205 						   auth_tag_str.length));
1206 			ZRTP_LOG(3,(_ZTU_, "\tauth tag[%s]\n",
1207 						   hex2str(auth_tag_str.buffer, auth_tag_str.length, buff, sizeof(buff))));
1208 		}
1209 #endif
1210 		if(status || tag_len != auth_tag_str.length){
1211 #if ZRTP_DEBUG_SRTP_KEYS
1212 			ZRTP_LOG(3,(_ZTU_, "\tAuthentication fail1: status[%i] auth_tag_length[%i] result auth_tag_len[%i]\n",
1213 						status, tag_len, auth_tag_str.length));
1214 #endif
1215 			return zrtp_status_auth_fail;
1216 		}
1217 
1218 		if(0 != zrtp_memcmp((uint8_t *)auth_tag_str.buffer, (uint8_t *)auth_tag, tag_len)){
1219 #if ZRTP_DEBUG_SRTP_KEYS
1220 			char buff[256], buff2[256];
1221 			ZRTP_LOG(3,(_ZTU_, "\tAuthentication fail2: tag[%s] computed_tag[%s]\n",
1222 						hex2str((uint8_t *)auth_tag, tag_len, buff, sizeof(buff)),
1223 						hex2str(auth_tag_str.buffer, auth_tag_str.length, buff2, sizeof(buff2))));
1224 #endif
1225 			return zrtp_status_auth_fail;
1226 		}
1227 	}
1228 
1229 	status = zrtp_cipher_decrypt(&srtp_stream_ctx->rtp_cipher, (unsigned char*)enc_start, enc_octet_len);
1230 	if(status){
1231 		return zrtp_status_cipher_fail;
1232 	}
1233 
1234 	zrtp_srtp_rp_add(&rp_node->rtp_rp, packet);
1235 	*packet->length -= tag_len;
1236 
1237 	return status;
1238 }
1239 
1240 /*---------------------------------------------------------------------------*/
zrtp_srtp_protect_rtcp(zrtp_srtp_global_t * srtp_global,zrtp_srtp_ctx_t * srtp_ctx,zrtp_rtp_info_t * packet)1241 zrtp_status_t zrtp_srtp_protect_rtcp(	zrtp_srtp_global_t *srtp_global,
1242 										zrtp_srtp_ctx_t	*srtp_ctx,
1243 										zrtp_rtp_info_t *packet)
1244 {
1245 	zrtp_srtp_stream_ctx_t *srtp_stream_ctx = srtp_ctx->outgoing_srtp;
1246 	zrtp_rp_node_t *rp_node;
1247 
1248 	uint32_t *enc_start;        /* pointer to start of encrypted portion  */
1249 	uint32_t *auth_start;       /* pointer to start of auth. portion      */
1250 	unsigned enc_octet_len = 0; /* number of octets in encrypted portion  */
1251 	uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
1252 	zrtp_status_t status;
1253 	ZRTP_UNALIGNED(zrtp_rtcp_hdr_t) *hdr;
1254 	ZRTP_UNALIGNED(uint32_t) *trailer;	/* pointer to start of trailer    */
1255 
1256 	uint32_t seq_num;
1257 
1258 	zrtp_v128_t iv;
1259 	zrtp_string64_t	auth_tag_str = ZSTR_INIT_EMPTY(auth_tag_str);
1260 
1261 	/*add new replay protection node or get existing one*/
1262 	rp_node = add_rp_node(srtp_ctx, srtp_global->rp_ctx, RP_OUTGOING_DIRECTION, packet->ssrc);
1263 	if(NULL == rp_node){
1264 		return zrtp_status_rp_fail;
1265 	}
1266 
1267 	/* check the packet length - it must at least contain a full header */
1268 	if (*(packet->length) < octets_in_rtcp_header){
1269 		return zrtp_status_bad_param;
1270 	}
1271 
1272 	hdr = (zrtp_rtcp_hdr_t*)(packet->packet);
1273 	enc_start = (uint32_t *)hdr + uint32s_in_rtcp_header;
1274 	enc_octet_len = *(packet->length) - octets_in_rtcp_header;
1275 
1276 	/* all of the packet, except the header, gets encrypted */
1277 	/* NOTE: hdr->length is not usable - it refers to only the first
1278 	   RTCP report in the compound packet! */
1279 	/* NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
1280 	   multiples of 32-bits (RFC 3550 6.1) */
1281 	trailer = (uint32_t *) ((char *)enc_start + enc_octet_len);
1282 
1283 	/*
1284 	 * RFC gives us ability of using non-crypted RTCP packets
1285 	 * but we encrypt them anyway. It may be option of stream
1286 	 * context in the future.
1287 	 * if no encryption is used trailer should contain 0x00000000
1288 	 */
1289 	*trailer = zrtp_hton32(ZRTP_RTCP_E_BIT);     /* set encrypt bit */
1290 
1291 	/*
1292 	 * set the auth_start and auth_tag pointers to the proper locations
1293 	 * (note that srtpc *always* provides authentication, unlike srtp)
1294 	 */
1295 	/* Note: This would need to change for optional mikey data */
1296 	auth_start = (uint32_t *)hdr;
1297 	auth_tag = (uint8_t *)hdr + *(packet->length) + sizeof(zrtp_rtcp_trailer_t);
1298 
1299 	status = zrtp_srtp_rp_increment(&rp_node->rtcp_rp);
1300 	if(zrtp_status_ok != status){
1301 		return zrtp_status_rp_fail;
1302 	}
1303 	seq_num = zrtp_srtp_rp_get_value(&rp_node->rtcp_rp);
1304 	*trailer |= zrtp_hton32(seq_num);
1305 	packet->seq = seq_num;
1306 
1307 	iv.v32[0] = 0;
1308 	iv.v32[1] = hdr->ssrc;
1309 	iv.v32[2] = zrtp_hton32(seq_num >> 16);
1310 	iv.v32[3] = zrtp_hton32(seq_num << 16);
1311 
1312 	status = zrtp_cipher_set_iv(&srtp_stream_ctx->rtcp_cipher, &iv);
1313 	if(status){
1314 		return zrtp_status_cipher_fail;
1315 	}
1316 
1317 	status = zrtp_cipher_encrypt(&srtp_stream_ctx->rtcp_cipher, (unsigned char*)enc_start, enc_octet_len);
1318 	if(status){
1319 		return zrtp_status_cipher_fail;
1320 	}
1321 
1322 	status = srtp_stream_ctx->rtcp_auth.hash->hmac_truncated_c(srtp_stream_ctx->rtcp_auth.hash,
1323 															   (const char*)srtp_stream_ctx->rtcp_auth.key,
1324 															   srtp_stream_ctx->rtcp_auth.key_len,
1325 															   (const char*)auth_start,
1326 															   *packet->length + sizeof(zrtp_rtcp_trailer_t),
1327 															   srtp_stream_ctx->rtcp_auth.tag_len->tag_length,
1328 															   (zrtp_stringn_t*) &auth_tag_str);
1329 	if(status){
1330 		return zrtp_status_auth_fail;
1331 	}
1332 
1333 	zrtp_memcpy(auth_tag, auth_tag_str.buffer, auth_tag_str.length);
1334 
1335 	/* increase the packet length by the length of the auth tag and seq_num*/
1336 	*packet->length += (auth_tag_str.length + sizeof(zrtp_rtcp_trailer_t));
1337 
1338 
1339 
1340 #if ZRTP_DEBUG_SRTP_KEYS
1341 	{
1342 		char buffer[1000];
1343 		ZRTP_LOG(3,(_ZTU_, "\tpacket: %s\n",
1344 					hex2str(packet->packet, (*packet->length) - (auth_tag_str.length + sizeof(zrtp_rtcp_trailer_t)), buffer, 1000)));
1345 		ZRTP_LOG(3,(_ZTU_, "\ttrailer and auth tag: %s\n",
1346 					hex2str((uint8_t*)packet->packet + ((*packet->length) - (auth_tag_str.length + sizeof(zrtp_rtcp_trailer_t))),
1347 							auth_tag_str.length + sizeof(zrtp_rtcp_trailer_t),
1348 							buffer, 1000)));
1349 	}
1350 #endif
1351 
1352 	return status;
1353 }
1354 
1355 /*---------------------------------------------------------------------------*/
zrtp_srtp_unprotect_rtcp(zrtp_srtp_global_t * srtp_global,zrtp_srtp_ctx_t * srtp_ctx,zrtp_rtp_info_t * packet)1356 zrtp_status_t zrtp_srtp_unprotect_rtcp(	zrtp_srtp_global_t *srtp_global,
1357 										zrtp_srtp_ctx_t *srtp_ctx,
1358 										zrtp_rtp_info_t *packet)
1359 {
1360 	zrtp_srtp_stream_ctx_t *srtp_stream_ctx = srtp_ctx->incoming_srtp;
1361 	zrtp_rp_node_t *rp_node;
1362 
1363 	uint32_t *enc_start;        /* pointer to start of encrypted portion  */
1364 	uint32_t *auth_start;       /* pointer to start of auth. portion      */
1365 	unsigned enc_octet_len = 0; /* number of octets in encrypted portion  */
1366 	uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
1367 	zrtp_status_t status;
1368 	ZRTP_UNALIGNED(zrtp_rtcp_hdr_t) *hdr;
1369 	ZRTP_UNALIGNED(uint32_t) *trailer;	/* pointer to start of trailer    */
1370 
1371 
1372 	int tag_len = 0;
1373 	zrtp_v128_t iv;
1374 
1375 	/* add new replay protection node or get existing one */
1376 	rp_node = add_rp_node(srtp_ctx, srtp_global->rp_ctx, RP_INCOMING_DIRECTION, packet->ssrc);
1377 	if(NULL == rp_node){
1378 		return zrtp_status_rp_fail;
1379 	}
1380 
1381 	/* check the packet length - it must at least contain a full header */
1382 	if (*(packet->length) < octets_in_rtcp_header){
1383 		return zrtp_status_bad_param;
1384 	}
1385 
1386 	tag_len = srtp_stream_ctx->rtcp_auth.tag_len->tag_length;
1387 	hdr = (zrtp_rtcp_hdr_t*)(packet->packet);
1388 
1389 	enc_octet_len = *packet->length -
1390 		(octets_in_rtcp_header + tag_len + sizeof(zrtp_rtcp_trailer_t));
1391 
1392 	/*	index & E (encryption) bit follow normal data.  hdr->len
1393 		is the number of words (32-bit) in the normal packet minus 1 */
1394 	/*	This should point trailer to the word past the end of the
1395 		normal data. */
1396 	/*	This would need to be modified for optional mikey data */
1397 	/*
1398 	 *	NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
1399 	 *	multiples of 32-bits (RFC 3550 6.1)
1400 	 */
1401 
1402 	trailer = (uint32_t *) ((char *) hdr + *packet->length - (tag_len + sizeof(zrtp_rtcp_trailer_t)));
1403 
1404 	if (*((unsigned char *) trailer) & ZRTP_RTCP_E_BYTE_BIT) {
1405 		enc_start = (uint32_t *)hdr + uint32s_in_rtcp_header;
1406 	} else {
1407 		enc_octet_len = 0;
1408 		enc_start = NULL; /* this indicates that there's no encryption */
1409 	}
1410 
1411 	/*
1412 	 * set the auth_start and auth_tag pointers to the proper locations
1413 	 * (note that srtcp *always* uses authentication, unlike srtp)
1414 	 */
1415 	auth_start = (uint32_t *)hdr;
1416 	auth_tag = (uint8_t *)hdr + *packet->length - tag_len;
1417 
1418 	packet->seq = zrtp_ntoh32(*trailer) & 0x7fffffff;
1419 
1420 	status = zrtp_srtp_rp_check(&rp_node->rtcp_rp, packet);
1421 	if(zrtp_status_ok != status){
1422 		return zrtp_status_rp_fail;
1423 	}
1424 
1425 	iv.v32[0] = 0;
1426 	iv.v32[1] = hdr->ssrc; /* still in network order! */
1427 	iv.v32[2] = zrtp_hton32(packet->seq >> 16);
1428 	iv.v32[3] = zrtp_hton32(packet->seq << 16);
1429 
1430 	status = zrtp_cipher_set_iv(&srtp_stream_ctx->rtcp_cipher, &iv);
1431 	if(status){
1432 		return zrtp_status_cipher_fail;
1433 	}
1434 
1435 	if(tag_len>0){
1436 		zrtp_string64_t	auth_tag_str = ZSTR_INIT_EMPTY(auth_tag_str);
1437 
1438 		status = srtp_stream_ctx->rtcp_auth.hash->hmac_truncated_c(srtp_stream_ctx->rtcp_auth.hash,
1439 																   (const char*)srtp_stream_ctx->rtcp_auth.key,
1440 																   srtp_stream_ctx->rtcp_auth.key_len,
1441 																   (const char*)auth_start,
1442 																   *packet->length - tag_len,
1443 																   tag_len,
1444 																   (zrtp_stringn_t*) &auth_tag_str);
1445 		if(status || tag_len != auth_tag_str.length){
1446 			return zrtp_status_auth_fail;
1447 		}
1448 
1449 		if(0 != zrtp_memcmp((uint8_t *)auth_tag_str.buffer, (uint8_t *)auth_tag, tag_len)){
1450 			return zrtp_status_auth_fail;
1451 		}
1452 	}else{
1453 		return zrtp_status_auth_fail;
1454 	}
1455 
1456 	if(enc_start){
1457 		status = zrtp_cipher_decrypt(&srtp_stream_ctx->rtcp_cipher, (unsigned char*)enc_start, enc_octet_len);
1458 		if(status){
1459 			return zrtp_status_cipher_fail;
1460 		}
1461 	}
1462 
1463 	zrtp_srtp_rp_add(&rp_node->rtcp_rp, packet);
1464 	*packet->length -= (tag_len + sizeof(zrtp_rtcp_trailer_t));
1465 
1466 	return status;
1467 }
1468 
1469 #endif /* !ZRTP_USE_EXTERN_SRTP */
1470