1/*
2 * srtp.c
3 *
4 * the secure real-time transport protocol
5 *
6 * David A. McGrew
7 * Cisco Systems, Inc.
8 */
9/*
10 *
11 * Copyright (c) 2001-2006, Cisco Systems, Inc.
12 * All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 *
18 *   Redistributions of source code must retain the above copyright
19 *   notice, this list of conditions and the following disclaimer.
20 *
21 *   Redistributions in binary form must reproduce the above
22 *   copyright notice, this list of conditions and the following
23 *   disclaimer in the documentation and/or other materials provided
24 *   with the distribution.
25 *
26 *   Neither the name of the Cisco Systems, Inc. nor the names of its
27 *   contributors may be used to endorse or promote products derived
28 *   from this software without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
33 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
34 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
35 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
36 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
37 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
41 * OF THE POSSIBILITY OF SUCH DAMAGE.
42 *
43 */
44
45
46#include "srtp.h"
47#include "ekt.h"             /* for SRTP Encrypted Key Transport */
48#include "aes_icm.h"         /* aes_icm is used in the KDF  */
49#include "alloc.h"           /* for crypto_alloc()          */
50
51#ifndef SRTP_KERNEL
52# include <limits.h>
53# ifdef HAVE_NETINET_IN_H
54#  include <netinet/in.h>
55# elif defined(HAVE_WINSOCK2_H)
56#  include <winsock2.h>
57# endif
58#endif /* ! SRTP_KERNEL */
59
60
61extern cipher_type_t aes_icm;
62extern auth_type_t   tmmhv2;
63
64/* the debug module for srtp */
65
66debug_module_t mod_srtp = {
67  0,                  /* debugging is off by default */
68  "srtp"              /* printable name for module   */
69};
70
71#define octets_in_rtp_header   12
72#define uint32s_in_rtp_header  3
73#define octets_in_rtcp_header  8
74#define uint32s_in_rtcp_header 2
75
76
77err_status_t
78srtp_stream_alloc(srtp_stream_ctx_t **str_ptr,
79		  const srtp_policy_t *p) {
80  srtp_stream_ctx_t *str;
81  err_status_t stat;
82
83  /*
84   * This function allocates the stream context, rtp and rtcp ciphers
85   * and auth functions, and key limit structure.  If there is a
86   * failure during allocation, we free all previously allocated
87   * memory and return a failure code.  The code could probably
88   * be improved, but it works and should be clear.
89   */
90
91  /* allocate srtp stream and set str_ptr */
92  str = (srtp_stream_ctx_t *) crypto_alloc(sizeof(srtp_stream_ctx_t));
93  if (str == NULL)
94    return err_status_alloc_fail;
95  *str_ptr = str;
96
97  /* allocate cipher */
98  stat = crypto_kernel_alloc_cipher(p->rtp.cipher_type,
99				    &str->rtp_cipher,
100				    p->rtp.cipher_key_len);
101  if (stat) {
102    goto err_rtp_cipher_alloc;
103  }
104
105  /* allocate auth function */
106  stat = crypto_kernel_alloc_auth(p->rtp.auth_type,
107				  &str->rtp_auth,
108				  p->rtp.auth_key_len,
109				  p->rtp.auth_tag_len);
110
111  if (stat) {
112    goto err_rtp_auth_alloc;
113  }
114
115  /* allocate key limit structure */
116  str->limit = (key_limit_ctx_t*) crypto_alloc(sizeof(key_limit_ctx_t));
117  if (str->limit == NULL) {
118    stat = err_status_alloc_fail;
119    goto err_limit_alloc;
120  }
121
122  /*
123   * ...and now the RTCP-specific initialization - first, allocate
124   * the cipher
125   */
126  stat = crypto_kernel_alloc_cipher(p->rtcp.cipher_type,
127				    &str->rtcp_cipher,
128				    p->rtcp.cipher_key_len);
129  if (stat) {
130    goto err_rtcp_cipher_alloc;
131  }
132
133  /* allocate auth function */
134  stat = crypto_kernel_alloc_auth(p->rtcp.auth_type,
135				  &str->rtcp_auth,
136				  p->rtcp.auth_key_len,
137				  p->rtcp.auth_tag_len);
138  if (stat) {
139    goto err_rtcp_auth_alloc;
140  }
141
142  /* allocate ekt data associated with stream */
143  stat = ekt_alloc(&str->ekt, p->ekt);
144  if (stat) {
145    goto err_ekt_alloc;
146  }
147
148  return err_status_ok;
149
150err_ekt_alloc:
151  auth_dealloc(str->rtcp_auth);
152err_rtcp_auth_alloc:
153  cipher_dealloc(str->rtcp_cipher);
154err_rtcp_cipher_alloc:
155  crypto_free(str->limit);
156err_limit_alloc:
157  auth_dealloc(str->rtp_auth);
158err_rtp_auth_alloc:
159  cipher_dealloc(str->rtp_cipher);
160err_rtp_cipher_alloc:
161  crypto_free(str);
162  return stat;
163}
164
165err_status_t
166srtp_stream_dealloc(srtp_stream_ctx_t *stream,
167                    srtp_stream_ctx_t *stream_template) {
168  err_status_t status;
169
170  /*
171   * we use a conservative deallocation strategy - if any deallocation
172   * fails, then we report that fact without trying to deallocate
173   * anything else
174   */
175
176  /* deallocate cipher, if it is not the same as that in template */
177  if (!stream_template || stream->rtp_cipher != stream_template->rtp_cipher) {
178    status = cipher_dealloc(stream->rtp_cipher);
179    if (status)
180      return status;
181  }
182
183  /* deallocate auth function, if it is not the same as that in template */
184  if (!stream_template || stream->rtp_auth != stream_template->rtp_auth) {
185    status = auth_dealloc(stream->rtp_auth);
186    if (status)
187      return status;
188  }
189
190  /* deallocate key usage limit, if it is not the same as that in template */
191  if (!stream_template || stream->limit != stream_template->limit) {
192    crypto_free(stream->limit);
193  }
194
195  /*
196   * deallocate rtcp cipher, if it is not the same as that in
197   * template
198   */
199  if (!stream_template || stream->rtcp_cipher != stream_template->rtcp_cipher) {
200    status = cipher_dealloc(stream->rtcp_cipher);
201    if (status)
202      return status;
203  }
204
205  /*
206   * deallocate rtcp auth function, if it is not the same as that in
207   * template
208   */
209  if (!stream_template || stream->rtcp_auth != stream_template->rtcp_auth) {
210    status = auth_dealloc(stream->rtcp_auth);
211    if (status)
212      return status;
213  }
214
215  /* DAM - need to deallocate EKT here */
216
217  /* deallocate srtp stream context */
218  crypto_free(stream);
219
220  return err_status_ok;
221}
222
223
224/*
225 * srtp_stream_clone(stream_template, new) allocates a new stream and
226 * initializes it using the cipher and auth of the stream_template
227 *
228 * the only unique data in a cloned stream is the replay database and
229 * the SSRC
230 */
231
232err_status_t
233srtp_stream_clone(const srtp_stream_ctx_t *stream_template,
234		  uint32_t ssrc,
235		  srtp_stream_ctx_t **str_ptr) {
236  err_status_t status;
237  srtp_stream_ctx_t *str;
238
239  debug_print(mod_srtp, "cloning stream (SSRC: 0x%08x)", ssrc);
240
241  /* allocate srtp stream and set str_ptr */
242  str = (srtp_stream_ctx_t *) crypto_alloc(sizeof(srtp_stream_ctx_t));
243  if (str == NULL)
244    return err_status_alloc_fail;
245  *str_ptr = str;
246
247  /* set cipher and auth pointers to those of the template */
248  str->rtp_cipher  = stream_template->rtp_cipher;
249  str->rtp_auth    = stream_template->rtp_auth;
250  str->rtcp_cipher = stream_template->rtcp_cipher;
251  str->rtcp_auth   = stream_template->rtcp_auth;
252
253  /* set key limit to point to that of the template */
254  status = key_limit_clone(stream_template->limit, &str->limit);
255  if (status)
256    return status;
257
258  /* initialize replay databases */
259  status = rdbx_init(&str->rtp_rdbx,
260		     rdbx_get_window_size(&stream_template->rtp_rdbx));
261  if (status)
262    return status;
263  rdb_init(&str->rtcp_rdb);
264  str->allow_repeat_tx = stream_template->allow_repeat_tx;
265
266  /* set ssrc to that provided */
267  str->ssrc = ssrc;
268
269  /* set direction and security services */
270  str->direction     = stream_template->direction;
271  str->rtp_services  = stream_template->rtp_services;
272  str->rtcp_services = stream_template->rtcp_services;
273
274  /* set pointer to EKT data associated with stream */
275  str->ekt = stream_template->ekt;
276
277  /* defensive coding */
278  str->next = NULL;
279
280  return err_status_ok;
281}
282
283
284/*
285 * key derivation functions, internal to libSRTP
286 *
287 * srtp_kdf_t is a key derivation context
288 *
289 * srtp_kdf_init(&kdf, k) initializes kdf with the key k
290 *
291 * srtp_kdf_generate(&kdf, l, kl, keylen) derives the key
292 * corresponding to label l and puts it into kl; the length
293 * of the key in octets is provided as keylen.  this function
294 * should be called once for each subkey that is derived.
295 *
296 * srtp_kdf_clear(&kdf) zeroizes the kdf state
297 */
298
299typedef enum {
300  label_rtp_encryption  = 0x00,
301  label_rtp_msg_auth    = 0x01,
302  label_rtp_salt        = 0x02,
303  label_rtcp_encryption = 0x03,
304  label_rtcp_msg_auth   = 0x04,
305  label_rtcp_salt       = 0x05
306} srtp_prf_label;
307
308
309/*
310 * srtp_kdf_t represents a key derivation function.  The SRTP
311 * default KDF is the only one implemented at present.
312 */
313
314typedef struct {
315  aes_icm_ctx_t c;    /* cipher used for key derivation  */
316} srtp_kdf_t;
317
318err_status_t
319srtp_kdf_init(srtp_kdf_t *kdf, const uint8_t key[30]) {
320
321  aes_icm_context_init(&kdf->c, key);
322
323  return err_status_ok;
324}
325
326err_status_t
327srtp_kdf_generate(srtp_kdf_t *kdf, srtp_prf_label label,
328		  uint8_t *key, int length) {
329
330  v128_t nonce;
331
332  /* set eigth octet of nonce to <label>, set the rest of it to zero */
333  v128_set_to_zero(&nonce);
334  nonce.v8[7] = label;
335
336  aes_icm_set_iv(&kdf->c, &nonce);
337
338  /* generate keystream output */
339  aes_icm_output(&kdf->c, key, length);
340
341  return err_status_ok;
342}
343
344err_status_t
345srtp_kdf_clear(srtp_kdf_t *kdf) {
346
347  /* zeroize aes context */
348  octet_string_set_to_zero((uint8_t *)kdf, sizeof(srtp_kdf_t));
349
350  return err_status_ok;
351}
352
353/*
354 *  end of key derivation functions
355 */
356
357#define MAX_SRTP_KEY_LEN 256
358
359
360err_status_t
361srtp_stream_init_keys(srtp_stream_ctx_t *srtp, const void *key) {
362  err_status_t stat;
363  srtp_kdf_t kdf;
364  uint8_t tmp_key[MAX_SRTP_KEY_LEN];
365
366  /* initialize KDF state     */
367  srtp_kdf_init(&kdf, (const uint8_t *)key);
368
369  /* generate encryption key  */
370  srtp_kdf_generate(&kdf, label_rtp_encryption,
371		    tmp_key, cipher_get_key_length(srtp->rtp_cipher));
372  /*
373   * if the cipher in the srtp context is aes_icm, then we need
374   * to generate the salt value
375   */
376  if (srtp->rtp_cipher->type == &aes_icm) {
377    /* FIX!!! this is really the cipher key length; rest is salt */
378    int base_key_len = 16;
379    int salt_len = cipher_get_key_length(srtp->rtp_cipher) - base_key_len;
380
381    debug_print(mod_srtp, "found aes_icm, generating salt", NULL);
382
383    /* generate encryption salt, put after encryption key */
384    srtp_kdf_generate(&kdf, label_rtp_salt,
385		      tmp_key + base_key_len, salt_len);
386  }
387  debug_print(mod_srtp, "cipher key: %s",
388	      octet_string_hex_string(tmp_key,
389		      cipher_get_key_length(srtp->rtp_cipher)));
390
391  /* initialize cipher */
392  stat = cipher_init(srtp->rtp_cipher, tmp_key, direction_any);
393  if (stat) {
394    /* zeroize temp buffer */
395    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
396    return err_status_init_fail;
397  }
398
399  /* generate authentication key */
400  srtp_kdf_generate(&kdf, label_rtp_msg_auth,
401		    tmp_key, auth_get_key_length(srtp->rtp_auth));
402  debug_print(mod_srtp, "auth key:   %s",
403	      octet_string_hex_string(tmp_key,
404				      auth_get_key_length(srtp->rtp_auth)));
405
406  /* initialize auth function */
407  stat = auth_init(srtp->rtp_auth, tmp_key);
408  if (stat) {
409    /* zeroize temp buffer */
410    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
411    return err_status_init_fail;
412  }
413
414  /*
415   * ...now initialize SRTCP keys
416   */
417
418  /* generate encryption key  */
419  srtp_kdf_generate(&kdf, label_rtcp_encryption,
420		    tmp_key, cipher_get_key_length(srtp->rtcp_cipher));
421  /*
422   * if the cipher in the srtp context is aes_icm, then we need
423   * to generate the salt value
424   */
425  if (srtp->rtcp_cipher->type == &aes_icm) {
426    /* FIX!!! this is really the cipher key length; rest is salt */
427    int base_key_len = 16;
428    int salt_len = cipher_get_key_length(srtp->rtcp_cipher) - base_key_len;
429
430    debug_print(mod_srtp, "found aes_icm, generating rtcp salt", NULL);
431
432    /* generate encryption salt, put after encryption key */
433    srtp_kdf_generate(&kdf, label_rtcp_salt,
434		      tmp_key + base_key_len, salt_len);
435  }
436  debug_print(mod_srtp, "rtcp cipher key: %s",
437	      octet_string_hex_string(tmp_key,
438		   cipher_get_key_length(srtp->rtcp_cipher)));
439
440  /* initialize cipher */
441  stat = cipher_init(srtp->rtcp_cipher, tmp_key, direction_any);
442  if (stat) {
443    /* zeroize temp buffer */
444    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
445    return err_status_init_fail;
446  }
447
448  /* generate authentication key */
449  srtp_kdf_generate(&kdf, label_rtcp_msg_auth,
450		    tmp_key, auth_get_key_length(srtp->rtcp_auth));
451  debug_print(mod_srtp, "rtcp auth key:   %s",
452	      octet_string_hex_string(tmp_key,
453		     auth_get_key_length(srtp->rtcp_auth)));
454
455  /* initialize auth function */
456  stat = auth_init(srtp->rtcp_auth, tmp_key);
457  if (stat) {
458    /* zeroize temp buffer */
459    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
460    return err_status_init_fail;
461  }
462
463  /* clear memory then return */
464  srtp_kdf_clear(&kdf);
465  octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
466
467  return err_status_ok;
468}
469
470err_status_t
471srtp_stream_init(srtp_stream_ctx_t *srtp,
472		  const srtp_policy_t *p) {
473  err_status_t err;
474
475   debug_print(mod_srtp, "initializing stream (SSRC: 0x%08x)",
476	       p->ssrc.value);
477
478   /* initialize replay database */
479   err = rdbx_init(&srtp->rtp_rdbx, p->window_size);
480   if (err) return err;
481
482   /* initialize key limit to maximum value */
483#ifdef NO_64BIT_MATH
484{
485   uint64_t temp;
486   temp = make64(UINT_MAX,UINT_MAX);
487   key_limit_set(srtp->limit, temp);
488}
489#else
490   key_limit_set(srtp->limit, 0xffffffffffffLL);
491#endif
492
493   /* set the SSRC value */
494   srtp->ssrc = htonl(p->ssrc.value);
495
496   /* set the security service flags */
497   srtp->rtp_services  = p->rtp.sec_serv;
498   srtp->rtcp_services = p->rtcp.sec_serv;
499
500   /*
501    * set direction to unknown - this flag gets checked in srtp_protect(),
502    * srtp_unprotect(), srtp_protect_rtcp(), and srtp_unprotect_rtcp(), and
503    * gets set appropriately if it is set to unknown.
504    */
505   srtp->direction = dir_unknown;
506
507   /* initialize SRTCP replay database */
508   rdb_init(&srtp->rtcp_rdb);
509
510   /* initialize allow_repeat_tx */
511   srtp->allow_repeat_tx = p->allow_repeat_tx;
512
513   /* DAM - no RTCP key limit at present */
514
515   /* initialize keys */
516   err = srtp_stream_init_keys(srtp, p->key);
517   if (err) {
518     rdbx_uninit(&srtp->rtp_rdbx);
519     return err;
520   }
521
522   /*
523    * if EKT is in use, then initialize the EKT data associated with
524    * the stream
525    */
526   err = ekt_stream_init_from_policy(srtp->ekt, p->ekt);
527   if (err) {
528     rdbx_uninit(&srtp->rtp_rdbx);
529     return err;
530   }
531
532   return err_status_ok;
533}
534
535err_status_t
536srtp_stream_uninit(srtp_stream_ctx_t *srtp) {
537  return rdbx_uninit(&srtp->rtp_rdbx);
538}
539
540
541 /*
542  * srtp_event_reporter is an event handler function that merely
543  * reports the events that are reported by the callbacks
544  */
545
546 void
547 srtp_event_reporter(srtp_event_data_t *data) {
548
549   err_report(err_level_warning, "srtp: in stream 0x%x: ",
550	      data->stream->ssrc);
551
552   switch(data->event) {
553   case event_ssrc_collision:
554     err_report(err_level_warning, "\tSSRC collision\n");
555     break;
556   case event_key_soft_limit:
557     err_report(err_level_warning, "\tkey usage soft limit reached\n");
558     break;
559   case event_key_hard_limit:
560     err_report(err_level_warning, "\tkey usage hard limit reached\n");
561     break;
562   case event_packet_index_limit:
563     err_report(err_level_warning, "\tpacket index limit reached\n");
564     break;
565   default:
566     err_report(err_level_warning, "\tunknown event reported to handler\n");
567   }
568 }
569
570 /*
571  * srtp_event_handler is a global variable holding a pointer to the
572  * event handler function; this function is called for any unexpected
573  * event that needs to be handled out of the SRTP data path.  see
574  * srtp_event_t in srtp.h for more info
575  *
576  * it is okay to set srtp_event_handler to NULL, but we set
577  * it to the srtp_event_reporter.
578  */
579
580 static srtp_event_handler_func_t *srtp_event_handler = srtp_event_reporter;
581
582 err_status_t
583 srtp_install_event_handler(srtp_event_handler_func_t func) {
584
585   /*
586    * note that we accept NULL arguments intentionally - calling this
587    * function with a NULL arguments removes an event handler that's
588    * been previously installed
589    */
590
591   /* set global event handling function */
592   srtp_event_handler = func;
593   return err_status_ok;
594 }
595
596 err_status_t
597 srtp_protect(srtp_ctx_t *ctx, void *rtp_hdr, int *pkt_octet_len) {
598   srtp_hdr_t *hdr = (srtp_hdr_t *)rtp_hdr;
599   uint32_t *enc_start;        /* pointer to start of encrypted portion  */
600   uint32_t *auth_start;       /* pointer to start of auth. portion      */
601   unsigned enc_octet_len = 0; /* number of octets in encrypted portion  */
602   xtd_seq_num_t est;          /* estimated xtd_seq_num_t of *hdr        */
603   int delta;                  /* delta of local pkt idx and that in hdr */
604   uint8_t *auth_tag = NULL;   /* location of auth_tag within packet     */
605   err_status_t status;
606   int tag_len;
607   srtp_stream_ctx_t *stream;
608   int prefix_len;
609
610   debug_print(mod_srtp, "function srtp_protect", NULL);
611
612  /* we assume the hdr is 32-bit aligned to start */
613
614   /* check the packet length - it must at least contain a full header */
615   if (*pkt_octet_len < octets_in_rtp_header)
616     return err_status_bad_param;
617
618   /*
619    * look up ssrc in srtp_stream list, and process the packet with
620    * the appropriate stream.  if we haven't seen this stream before,
621    * there's a template key for this srtp_session, and the cipher
622    * supports key-sharing, then we assume that a new stream using
623    * that key has just started up
624    */
625   stream = srtp_get_stream(ctx, hdr->ssrc);
626   if (stream == NULL) {
627     if (ctx->stream_template != NULL) {
628       srtp_stream_ctx_t *new_stream;
629
630       /* allocate and initialize a new stream */
631       status = srtp_stream_clone(ctx->stream_template,
632				  hdr->ssrc, &new_stream);
633       if (status)
634	 return status;
635
636       /* add new stream to the head of the stream_list */
637       new_stream->next = ctx->stream_list;
638       ctx->stream_list = new_stream;
639
640       /* set direction to outbound */
641       new_stream->direction = dir_srtp_sender;
642
643       /* set stream (the pointer used in this function) */
644       stream = new_stream;
645     } else {
646       /* no template stream, so we return an error */
647       return err_status_no_ctx;
648     }
649   }
650
651   /*
652    * verify that stream is for sending traffic - this check will
653    * detect SSRC collisions, since a stream that appears in both
654    * srtp_protect() and srtp_unprotect() will fail this test in one of
655    * those functions.
656    */
657   if (stream->direction != dir_srtp_sender) {
658     if (stream->direction == dir_unknown) {
659       stream->direction = dir_srtp_sender;
660     } else {
661       srtp_handle_event(ctx, stream, event_ssrc_collision);
662     }
663   }
664
665  /*
666   * update the key usage limit, and check it to make sure that we
667   * didn't just hit either the soft limit or the hard limit, and call
668   * the event handler if we hit either.
669   */
670  switch(key_limit_update(stream->limit)) {
671  case key_event_normal:
672    break;
673  case key_event_soft_limit:
674    srtp_handle_event(ctx, stream, event_key_soft_limit);
675    break;
676  case key_event_hard_limit:
677    srtp_handle_event(ctx, stream, event_key_hard_limit);
678	return err_status_key_expired;
679  default:
680    break;
681  }
682
683   /* get tag length from stream */
684   tag_len = auth_get_tag_length(stream->rtp_auth);
685
686   /*
687    * find starting point for encryption and length of data to be
688    * encrypted - the encrypted portion starts after the rtp header
689    * extension, if present; otherwise, it starts after the last csrc,
690    * if any are present
691    *
692    * if we're not providing confidentiality, set enc_start to NULL
693    */
694   if (stream->rtp_services & sec_serv_conf) {
695     enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc;
696     if (hdr->x == 1) {
697       srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t *)enc_start;
698       enc_start += (ntohs(xtn_hdr->length) + 1);
699     }
700     enc_octet_len = (unsigned int)(*pkt_octet_len
701				    - ((enc_start - (uint32_t *)hdr) << 2));
702   } else {
703     enc_start = NULL;
704   }
705
706   /*
707    * if we're providing authentication, set the auth_start and auth_tag
708    * pointers to the proper locations; otherwise, set auth_start to NULL
709    * to indicate that no authentication is needed
710    */
711   if (stream->rtp_services & sec_serv_auth) {
712     auth_start = (uint32_t *)hdr;
713     auth_tag = (uint8_t *)hdr + *pkt_octet_len;
714   } else {
715     auth_start = NULL;
716     auth_tag = NULL;
717   }
718
719   /*
720    * estimate the packet index using the start of the replay window
721    * and the sequence number from the header
722    */
723   delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));
724   status = rdbx_check(&stream->rtp_rdbx, delta);
725   if (status) {
726     if (status != err_status_replay_fail || !stream->allow_repeat_tx)
727       return status;  /* we've been asked to reuse an index */
728   }
729   else
730     rdbx_add_index(&stream->rtp_rdbx, delta);
731
732#ifdef NO_64BIT_MATH
733   debug_print2(mod_srtp, "estimated packet index: %08x%08x",
734		high32(est),low32(est));
735#else
736   debug_print(mod_srtp, "estimated packet index: %016llx", est);
737#endif
738
739   /*
740    * if we're using rindael counter mode, set nonce and seq
741    */
742   if (stream->rtp_cipher->type == &aes_icm) {
743     v128_t iv;
744
745     iv.v32[0] = 0;
746     iv.v32[1] = hdr->ssrc;
747#ifdef NO_64BIT_MATH
748     iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16),
749								 low32(est) << 16));
750#else
751     iv.v64[1] = be64_to_cpu(est << 16);
752#endif
753     status = cipher_set_iv(stream->rtp_cipher, &iv);
754
755   } else {
756     v128_t iv;
757
758     /* otherwise, set the index to est */
759#ifdef NO_64BIT_MATH
760     iv.v32[0] = 0;
761     iv.v32[1] = 0;
762#else
763     iv.v64[0] = 0;
764#endif
765     iv.v64[1] = be64_to_cpu(est);
766     status = cipher_set_iv(stream->rtp_cipher, &iv);
767   }
768   if (status)
769     return err_status_cipher_fail;
770
771   /* shift est, put into network byte order */
772#ifdef NO_64BIT_MATH
773   est = be64_to_cpu(make64((high32(est) << 16) |
774						 (low32(est) >> 16),
775						 low32(est) << 16));
776#else
777   est = be64_to_cpu(est << 16);
778#endif
779
780   /*
781    * if we're authenticating using a universal hash, put the keystream
782    * prefix into the authentication tag
783    */
784   if (auth_start) {
785
786    prefix_len = auth_get_prefix_length(stream->rtp_auth);
787    if (prefix_len) {
788      status = cipher_output(stream->rtp_cipher, auth_tag, prefix_len);
789      if (status)
790	return err_status_cipher_fail;
791      debug_print(mod_srtp, "keystream prefix: %s",
792		  octet_string_hex_string(auth_tag, prefix_len));
793    }
794  }
795
796  /* if we're encrypting, exor keystream into the message */
797  if (enc_start) {
798    status = cipher_encrypt(stream->rtp_cipher,
799			    (uint8_t *)enc_start, &enc_octet_len);
800    if (status)
801      return err_status_cipher_fail;
802  }
803
804  /*
805   *  if we're authenticating, run authentication function and put result
806   *  into the auth_tag
807   */
808  if (auth_start) {
809
810    /* initialize auth func context */
811    status = auth_start(stream->rtp_auth);
812    if (status) return status;
813
814    /* run auth func over packet */
815    status = auth_update(stream->rtp_auth,
816			 (uint8_t *)auth_start, *pkt_octet_len);
817    if (status) return status;
818
819    /* run auth func over ROC, put result into auth_tag */
820    debug_print(mod_srtp, "estimated packet index: %016llx", est);
821    status = auth_compute(stream->rtp_auth, (uint8_t *)&est, 4, auth_tag);
822    debug_print(mod_srtp, "srtp auth tag:    %s",
823		octet_string_hex_string(auth_tag, tag_len));
824    if (status)
825      return err_status_auth_fail;
826
827  }
828
829  if (auth_tag) {
830
831    /* increase the packet length by the length of the auth tag */
832    *pkt_octet_len += tag_len;
833  }
834
835  return err_status_ok;
836}
837
838
839err_status_t
840srtp_unprotect(srtp_ctx_t *ctx, void *srtp_hdr, int *pkt_octet_len) {
841  srtp_hdr_t *hdr = (srtp_hdr_t *)srtp_hdr;
842  uint32_t *enc_start;      /* pointer to start of encrypted portion  */
843  uint32_t *auth_start;     /* pointer to start of auth. portion      */
844  unsigned enc_octet_len = 0;/* number of octets in encrypted portion */
845  uint8_t *auth_tag = NULL; /* location of auth_tag within packet     */
846  xtd_seq_num_t est;        /* estimated xtd_seq_num_t of *hdr        */
847  int delta;                /* delta of local pkt idx and that in hdr */
848  v128_t iv;
849  err_status_t status;
850  srtp_stream_ctx_t *stream;
851  uint8_t tmp_tag[SRTP_MAX_TAG_LEN];
852  int tag_len, prefix_len;
853
854  debug_print(mod_srtp, "function srtp_unprotect", NULL);
855
856  /* we assume the hdr is 32-bit aligned to start */
857
858  /* check the packet length - it must at least contain a full header */
859  if (*pkt_octet_len < octets_in_rtp_header)
860    return err_status_bad_param;
861
862  /*
863   * look up ssrc in srtp_stream list, and process the packet with
864   * the appropriate stream.  if we haven't seen this stream before,
865   * there's only one key for this srtp_session, and the cipher
866   * supports key-sharing, then we assume that a new stream using
867   * that key has just started up
868   */
869  stream = srtp_get_stream(ctx, hdr->ssrc);
870  if (stream == NULL) {
871    if (ctx->stream_template != NULL) {
872      stream = ctx->stream_template;
873      debug_print(mod_srtp, "using provisional stream (SSRC: 0x%08x)",
874		  hdr->ssrc);
875
876      /*
877       * set estimated packet index to sequence number from header,
878       * and set delta equal to the same value
879       */
880#ifdef NO_64BIT_MATH
881      est = (xtd_seq_num_t) make64(0,ntohs(hdr->seq));
882      delta = low32(est);
883#else
884      est = (xtd_seq_num_t) ntohs(hdr->seq);
885      delta = (int)est;
886#endif
887    } else {
888
889      /*
890       * no stream corresponding to SSRC found, and we don't do
891       * key-sharing, so return an error
892       */
893      return err_status_no_ctx;
894    }
895  } else {
896
897    /* estimate packet index from seq. num. in header */
898    delta = rdbx_estimate_index(&stream->rtp_rdbx, &est, ntohs(hdr->seq));
899
900    /* check replay database */
901    status = rdbx_check(&stream->rtp_rdbx, delta);
902    if (status)
903      return status;
904  }
905
906#ifdef NO_64BIT_MATH
907  debug_print2(mod_srtp, "estimated u_packet index: %08x%08x", high32(est),low32(est));
908#else
909  debug_print(mod_srtp, "estimated u_packet index: %016llx", est);
910#endif
911
912  /* get tag length from stream */
913  tag_len = auth_get_tag_length(stream->rtp_auth);
914
915  /*
916   * set the cipher's IV properly, depending on whatever cipher we
917   * happen to be using
918   */
919  if (stream->rtp_cipher->type == &aes_icm) {
920
921    /* aes counter mode */
922    iv.v32[0] = 0;
923    iv.v32[1] = hdr->ssrc;  /* still in network order */
924#ifdef NO_64BIT_MATH
925    iv.v64[1] = be64_to_cpu(make64((high32(est) << 16) | (low32(est) >> 16),
926			         low32(est) << 16));
927#else
928    iv.v64[1] = be64_to_cpu(est << 16);
929#endif
930    status = aes_icm_set_iv((aes_icm_ctx_t*)stream->rtp_cipher->state, &iv);
931  } else {
932
933    /* no particular format - set the iv to the pakcet index */
934#ifdef NO_64BIT_MATH
935    iv.v32[0] = 0;
936    iv.v32[1] = 0;
937#else
938    iv.v64[0] = 0;
939#endif
940    iv.v64[1] = be64_to_cpu(est);
941    status = cipher_set_iv(stream->rtp_cipher, &iv);
942  }
943  if (status)
944    return err_status_cipher_fail;
945
946  /* shift est, put into network byte order */
947#ifdef NO_64BIT_MATH
948  est = be64_to_cpu(make64((high32(est) << 16) |
949					    (low32(est) >> 16),
950					    low32(est) << 16));
951#else
952  est = be64_to_cpu(est << 16);
953#endif
954
955  /*
956   * find starting point for decryption and length of data to be
957   * decrypted - the encrypted portion starts after the rtp header
958   * extension, if present; otherwise, it starts after the last csrc,
959   * if any are present
960   *
961   * if we're not providing confidentiality, set enc_start to NULL
962   */
963  if (stream->rtp_services & sec_serv_conf) {
964    enc_start = (uint32_t *)hdr + uint32s_in_rtp_header + hdr->cc;
965    if (hdr->x == 1) {
966      srtp_hdr_xtnd_t *xtn_hdr = (srtp_hdr_xtnd_t *)enc_start;
967      enc_start += (ntohs(xtn_hdr->length) + 1);
968    }
969    enc_octet_len = (uint32_t)(*pkt_octet_len - tag_len
970			       - ((enc_start - (uint32_t *)hdr) << 2));
971  } else {
972    enc_start = NULL;
973  }
974
975  /*
976   * if we're providing authentication, set the auth_start and auth_tag
977   * pointers to the proper locations; otherwise, set auth_start to NULL
978   * to indicate that no authentication is needed
979   */
980  if (stream->rtp_services & sec_serv_auth) {
981    auth_start = (uint32_t *)hdr;
982    auth_tag = (uint8_t *)hdr + *pkt_octet_len - tag_len;
983  } else {
984    auth_start = NULL;
985    auth_tag = NULL;
986  }
987
988  /*
989   * if we expect message authentication, run the authentication
990   * function and compare the result with the value of the auth_tag
991   */
992  if (auth_start) {
993
994    /*
995     * if we're using a universal hash, then we need to compute the
996     * keystream prefix for encrypting the universal hash output
997     *
998     * if the keystream prefix length is zero, then we know that
999     * the authenticator isn't using a universal hash function
1000     */
1001    if (stream->rtp_auth->prefix_len != 0) {
1002
1003      prefix_len = auth_get_prefix_length(stream->rtp_auth);
1004      status = cipher_output(stream->rtp_cipher, tmp_tag, prefix_len);
1005      debug_print(mod_srtp, "keystream prefix: %s",
1006		  octet_string_hex_string(tmp_tag, prefix_len));
1007      if (status)
1008	return err_status_cipher_fail;
1009    }
1010
1011    /* initialize auth func context */
1012    status = auth_start(stream->rtp_auth);
1013    if (status) return status;
1014
1015    /* now compute auth function over packet */
1016    status = auth_update(stream->rtp_auth, (uint8_t *)auth_start,
1017			 *pkt_octet_len - tag_len);
1018
1019    /* run auth func over ROC, then write tmp tag */
1020    status = auth_compute(stream->rtp_auth, (uint8_t *)&est, 4, tmp_tag);
1021
1022    debug_print(mod_srtp, "computed auth tag:    %s",
1023		octet_string_hex_string(tmp_tag, tag_len));
1024    debug_print(mod_srtp, "packet auth tag:      %s",
1025		octet_string_hex_string(auth_tag, tag_len));
1026    if (status)
1027      return err_status_auth_fail;
1028
1029    if (octet_string_is_eq(tmp_tag, auth_tag, tag_len))
1030      return err_status_auth_fail;
1031  }
1032
1033  /*
1034   * update the key usage limit, and check it to make sure that we
1035   * didn't just hit either the soft limit or the hard limit, and call
1036   * the event handler if we hit either.
1037   */
1038  switch(key_limit_update(stream->limit)) {
1039  case key_event_normal:
1040    break;
1041  case key_event_soft_limit:
1042    srtp_handle_event(ctx, stream, event_key_soft_limit);
1043    break;
1044  case key_event_hard_limit:
1045    srtp_handle_event(ctx, stream, event_key_hard_limit);
1046    return err_status_key_expired;
1047  default:
1048    break;
1049  }
1050
1051  /* if we're encrypting, add keystream into ciphertext */
1052  if (enc_start) {
1053    status = cipher_encrypt(stream->rtp_cipher,
1054			    (uint8_t *)enc_start, &enc_octet_len);
1055    if (status)
1056      return err_status_cipher_fail;
1057  }
1058
1059  /*
1060   * verify that stream is for received traffic - this check will
1061   * detect SSRC collisions, since a stream that appears in both
1062   * srtp_protect() and srtp_unprotect() will fail this test in one of
1063   * those functions.
1064   *
1065   * we do this check *after* the authentication check, so that the
1066   * latter check will catch any attempts to fool us into thinking
1067   * that we've got a collision
1068   */
1069  if (stream->direction != dir_srtp_receiver) {
1070    if (stream->direction == dir_unknown) {
1071      stream->direction = dir_srtp_receiver;
1072    } else {
1073      srtp_handle_event(ctx, stream, event_ssrc_collision);
1074    }
1075  }
1076
1077  /*
1078   * if the stream is a 'provisional' one, in which the template context
1079   * is used, then we need to allocate a new stream at this point, since
1080   * the authentication passed
1081   */
1082  if (stream == ctx->stream_template) {
1083    srtp_stream_ctx_t *new_stream;
1084
1085    /*
1086     * allocate and initialize a new stream
1087     *
1088     * note that we indicate failure if we can't allocate the new
1089     * stream, and some implementations will want to not return
1090     * failure here
1091     */
1092    status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream);
1093    if (status)
1094      return status;
1095
1096    /* add new stream to the head of the stream_list */
1097    new_stream->next = ctx->stream_list;
1098    ctx->stream_list = new_stream;
1099
1100    /* set stream (the pointer used in this function) */
1101    stream = new_stream;
1102  }
1103
1104  /*
1105   * the message authentication function passed, so add the packet
1106   * index into the replay database
1107   */
1108  rdbx_add_index(&stream->rtp_rdbx, delta);
1109
1110  /* decrease the packet length by the length of the auth tag */
1111  *pkt_octet_len -= tag_len;
1112
1113  return err_status_ok;
1114}
1115
1116err_status_t
1117srtp_init() {
1118  err_status_t status;
1119
1120  /* initialize crypto kernel */
1121  status = crypto_kernel_init();
1122  if (status)
1123    return status;
1124
1125  /* load srtp debug module into the kernel */
1126  status = crypto_kernel_load_debug_module(&mod_srtp);
1127  if (status)
1128    return status;
1129
1130  return err_status_ok;
1131}
1132
1133/*
1134 * The following code is under consideration for removal.  See
1135 * SRTP_MAX_TRAILER_LEN
1136 */
1137#if 0
1138
1139/*
1140 * srtp_get_trailer_length(&a) returns the number of octets that will
1141 * be added to an RTP packet by the SRTP processing.  This value
1142 * is constant for a given srtp_stream_t (i.e. between initializations).
1143 */
1144
1145int
1146srtp_get_trailer_length(const srtp_stream_t s) {
1147  return auth_get_tag_length(s->rtp_auth);
1148}
1149
1150#endif
1151
1152/*
1153 * srtp_get_stream(ssrc) returns a pointer to the stream corresponding
1154 * to ssrc, or NULL if no stream exists for that ssrc
1155 *
1156 * this is an internal function
1157 */
1158
1159srtp_stream_ctx_t *
1160srtp_get_stream(srtp_t srtp, uint32_t ssrc) {
1161  srtp_stream_ctx_t *stream;
1162
1163  /* walk down list until ssrc is found */
1164  stream = srtp->stream_list;
1165  while (stream != NULL) {
1166    if (stream->ssrc == ssrc)
1167      return stream;
1168    stream = stream->next;
1169  }
1170
1171  /* we haven't found our ssrc, so return a null */
1172  return NULL;
1173}
1174
1175err_status_t
1176srtp_dealloc(srtp_t session) {
1177  srtp_stream_ctx_t *stream;
1178  err_status_t status;
1179
1180  /*
1181   * we take a conservative deallocation strategy - if we encounter an
1182   * error deallocating a stream, then we stop trying to deallocate
1183   * memory and just return an error
1184   */
1185
1186  /* walk list of streams, deallocating as we go */
1187  stream = session->stream_list;
1188  while (stream != NULL) {
1189    srtp_stream_t next = stream->next;
1190    status = srtp_stream_uninit_and_dealloc(stream, session->stream_template);
1191    if (status) {
1192      return status;
1193    }
1194    stream = next;
1195  }
1196
1197  /* deallocate stream template, if there is one */
1198  if (session->stream_template != NULL) {
1199    status = srtp_stream_uninit_and_dealloc(session->stream_template, NULL);
1200  }
1201
1202  /* deallocate session context */
1203  crypto_free(session);
1204
1205  return err_status_ok;
1206}
1207
1208
1209err_status_t
1210srtp_add_stream(srtp_t session,
1211		const srtp_policy_t *policy)  {
1212  err_status_t status;
1213  srtp_stream_t tmp;
1214
1215  /* sanity check arguments */
1216  if ((session == NULL) || (policy == NULL) || (policy->key == NULL))
1217    return err_status_bad_param;
1218
1219  /* allocate stream  */
1220  status = srtp_stream_alloc(&tmp, policy);
1221  if (status) {
1222    return status;
1223  }
1224
1225  /* initialize stream  */
1226  status = srtp_stream_init(tmp, policy);
1227  if (status) {
1228    crypto_free(tmp);
1229    return status;
1230  }
1231
1232  /*
1233   * set the head of the stream list or the template to point to the
1234   * stream that we've just alloced and init'ed, depending on whether
1235   * or not it has a wildcard SSRC value or not
1236   *
1237   * if the template stream has already been set, then the policy is
1238   * inconsistent, so we return a bad_param error code
1239   */
1240  switch (policy->ssrc.type) {
1241  case (ssrc_any_outbound):
1242    if (session->stream_template) {
1243      return err_status_bad_param;
1244    }
1245    session->stream_template = tmp;
1246    session->stream_template->direction = dir_srtp_sender;
1247    break;
1248  case (ssrc_any_inbound):
1249    if (session->stream_template) {
1250      return err_status_bad_param;
1251    }
1252    session->stream_template = tmp;
1253    session->stream_template->direction = dir_srtp_receiver;
1254    break;
1255  case (ssrc_specific):
1256    tmp->next = session->stream_list;
1257    session->stream_list = tmp;
1258    break;
1259  case (ssrc_undefined):
1260  default:
1261    crypto_free(tmp);
1262    return err_status_bad_param;
1263  }
1264  return err_status_ok;
1265}
1266
1267
1268err_status_t
1269srtp_create(srtp_t *session,               /* handle for session     */
1270	    const srtp_policy_t *policy) { /* SRTP policy (list)     */
1271  err_status_t stat;
1272  srtp_ctx_t *ctx;
1273
1274  /* sanity check arguments */
1275  if (session == NULL)
1276    return err_status_bad_param;
1277
1278  /* allocate srtp context and set ctx_ptr */
1279  ctx = (srtp_ctx_t *) crypto_alloc(sizeof(srtp_ctx_t));
1280  if (ctx == NULL)
1281    return err_status_alloc_fail;
1282  *session = ctx;
1283
1284  /*
1285   * loop over elements in the policy list, allocating and
1286   * initializing a stream for each element
1287   */
1288  ctx->stream_template = NULL;
1289  ctx->stream_list = NULL;
1290  while (policy != NULL) {
1291
1292    stat = srtp_add_stream(ctx, policy);
1293    if (stat) {
1294      /* clean up everything */
1295      srtp_dealloc(*session);
1296      return stat;
1297    }
1298
1299    /* set policy to next item in list  */
1300    policy = policy->next;
1301  }
1302
1303  return err_status_ok;
1304}
1305
1306
1307err_status_t
1308srtp_remove_stream(srtp_t session, uint32_t ssrc) {
1309  srtp_stream_ctx_t *stream, *last_stream;
1310
1311  /* sanity check arguments */
1312  if (session == NULL)
1313    return err_status_bad_param;
1314
1315  /* find stream in list; complain if not found */
1316  last_stream = stream = session->stream_list;
1317  while ((stream != NULL) && (ssrc != stream->ssrc)) {
1318    last_stream = stream;
1319    stream = stream->next;
1320  }
1321  if (stream == NULL)
1322    return err_status_no_ctx;
1323
1324  /* remove stream from the list */
1325  last_stream->next = stream->next;
1326
1327  return srtp_stream_uninit_and_dealloc(stream, session->stream_template);
1328}
1329
1330err_status_t
1331srtp_stream_uninit_and_dealloc(srtp_stream_ctx_t *stream,
1332                               srtp_stream_ctx_t *stream_template) {
1333  err_status_t status;
1334  /* deallocate rdbx data */
1335  status = srtp_stream_uninit(stream);
1336  if (status)
1337    return status;
1338
1339  /* deallocate the stream */
1340  status = srtp_stream_dealloc(stream, stream_template);
1341  if (status)
1342    return status;
1343
1344  return err_status_ok;
1345}
1346
1347
1348/*
1349 * the default policy - provides a convenient way for callers to use
1350 * the default security policy
1351 *
1352 * this policy is that defined in the current SRTP internet draft.
1353 *
1354 */
1355
1356/*
1357 * NOTE: cipher_key_len is really key len (128 bits) plus salt len
1358 *  (112 bits)
1359 */
1360/* There are hard-coded 16's for base_key_len in the key generation code */
1361
1362void
1363crypto_policy_set_rtp_default(crypto_policy_t *p) {
1364
1365  p->cipher_type     = AES_128_ICM;
1366  p->cipher_key_len  = 30;                /* default 128 bits per RFC 3711 */
1367  p->auth_type       = HMAC_SHA1;
1368  p->auth_key_len    = 20;                /* default 160 bits per RFC 3711 */
1369  p->auth_tag_len    = 10;                /* default 80 bits per RFC 3711 */
1370  p->sec_serv        = sec_serv_conf_and_auth;
1371
1372}
1373
1374void
1375crypto_policy_set_rtcp_default(crypto_policy_t *p) {
1376
1377  p->cipher_type     = AES_128_ICM;
1378  p->cipher_key_len  = 30;                 /* default 128 bits per RFC 3711 */
1379  p->auth_type       = HMAC_SHA1;
1380  p->auth_key_len    = 20;                 /* default 160 bits per RFC 3711 */
1381  p->auth_tag_len    = 10;                 /* default 80 bits per RFC 3711 */
1382  p->sec_serv        = sec_serv_conf_and_auth;
1383
1384}
1385
1386void
1387crypto_policy_set_aes_cm_128_hmac_sha1_32(crypto_policy_t *p) {
1388
1389  /*
1390   * corresponds to draft-ietf-mmusic-sdescriptions-12.txt
1391   *
1392   * note that this crypto policy is intended for SRTP, but not SRTCP
1393   */
1394
1395  p->cipher_type     = AES_128_ICM;
1396  p->cipher_key_len  = 30;                /* 128 bit key, 112 bit salt */
1397  p->auth_type       = HMAC_SHA1;
1398  p->auth_key_len    = 20;                /* 160 bit key               */
1399  p->auth_tag_len    = 4;                 /* 32 bit tag                */
1400  p->sec_serv        = sec_serv_conf_and_auth;
1401
1402}
1403
1404
1405void
1406crypto_policy_set_aes_cm_128_null_auth(crypto_policy_t *p) {
1407
1408  /*
1409   * corresponds to draft-ietf-mmusic-sdescriptions-12.txt
1410   *
1411   * note that this crypto policy is intended for SRTP, but not SRTCP
1412   */
1413
1414  p->cipher_type     = AES_128_ICM;
1415  p->cipher_key_len  = 30;                /* 128 bit key, 112 bit salt */
1416  p->auth_type       = NULL_AUTH;
1417  p->auth_key_len    = 0;
1418  p->auth_tag_len    = 0;
1419  p->sec_serv        = sec_serv_conf;
1420
1421}
1422
1423
1424void
1425crypto_policy_set_null_cipher_hmac_sha1_80(crypto_policy_t *p) {
1426
1427  /*
1428   * corresponds to draft-ietf-mmusic-sdescriptions-12.txt
1429   */
1430
1431  p->cipher_type     = NULL_CIPHER;
1432  p->cipher_key_len  = 0;
1433  p->auth_type       = HMAC_SHA1;
1434  p->auth_key_len    = 20;
1435  p->auth_tag_len    = 10;
1436  p->sec_serv        = sec_serv_auth;
1437
1438}
1439
1440
1441/*
1442 * secure rtcp functions
1443 */
1444
1445err_status_t
1446srtp_protect_rtcp(srtp_t ctx, void *rtcp_hdr, int *pkt_octet_len) {
1447  srtcp_hdr_t *hdr = (srtcp_hdr_t *)rtcp_hdr;
1448  uint32_t *enc_start;      /* pointer to start of encrypted portion  */
1449  uint32_t *auth_start;     /* pointer to start of auth. portion      */
1450  uint32_t *trailer;        /* pointer to start of trailer            */
1451  unsigned enc_octet_len = 0;/* number of octets in encrypted portion */
1452  uint8_t *auth_tag = NULL; /* location of auth_tag within packet     */
1453  err_status_t status;
1454  int tag_len;
1455  srtp_stream_ctx_t *stream;
1456  int prefix_len;
1457  uint32_t seq_num;
1458
1459  /* we assume the hdr is 32-bit aligned to start */
1460  /*
1461   * look up ssrc in srtp_stream list, and process the packet with
1462   * the appropriate stream.  if we haven't seen this stream before,
1463   * there's only one key for this srtp_session, and the cipher
1464   * supports key-sharing, then we assume that a new stream using
1465   * that key has just started up
1466   */
1467  stream = srtp_get_stream(ctx, hdr->ssrc);
1468  if (stream == NULL) {
1469    if (ctx->stream_template != NULL) {
1470      srtp_stream_ctx_t *new_stream;
1471
1472      /* allocate and initialize a new stream */
1473      status = srtp_stream_clone(ctx->stream_template,
1474				 hdr->ssrc, &new_stream);
1475      if (status)
1476	return status;
1477
1478      /* add new stream to the head of the stream_list */
1479      new_stream->next = ctx->stream_list;
1480      ctx->stream_list = new_stream;
1481
1482      /* set stream (the pointer used in this function) */
1483      stream = new_stream;
1484    } else {
1485      /* no template stream, so we return an error */
1486      return err_status_no_ctx;
1487    }
1488  }
1489
1490  /*
1491   * verify that stream is for sending traffic - this check will
1492   * detect SSRC collisions, since a stream that appears in both
1493   * srtp_protect() and srtp_unprotect() will fail this test in one of
1494   * those functions.
1495   */
1496  if (stream->direction != dir_srtp_sender) {
1497    if (stream->direction == dir_unknown) {
1498      stream->direction = dir_srtp_sender;
1499    } else {
1500      srtp_handle_event(ctx, stream, event_ssrc_collision);
1501    }
1502  }
1503
1504  /* get tag length from stream context */
1505  tag_len = auth_get_tag_length(stream->rtcp_auth);
1506
1507  /*
1508   * set encryption start and encryption length - if we're not
1509   * providing confidentiality, set enc_start to NULL
1510   */
1511  enc_start = (uint32_t *)hdr + uint32s_in_rtcp_header;
1512  enc_octet_len = *pkt_octet_len - octets_in_rtcp_header;
1513
1514  /* all of the packet, except the header, gets encrypted */
1515  /* NOTE: hdr->length is not usable - it refers to only the first
1516	 RTCP report in the compound packet! */
1517  /* NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
1518	 multiples of 32-bits (RFC 3550 6.1) */
1519  trailer = (uint32_t *) ((char *)enc_start + enc_octet_len);
1520
1521  if (stream->rtcp_services & sec_serv_conf) {
1522    *trailer = htonl(SRTCP_E_BIT);     /* set encrypt bit */
1523  } else {
1524    enc_start = NULL;
1525    enc_octet_len = 0;
1526	/* 0 is network-order independant */
1527    *trailer = 0x00000000;     /* set encrypt bit */
1528  }
1529
1530  /*
1531   * set the auth_start and auth_tag pointers to the proper locations
1532   * (note that srtpc *always* provides authentication, unlike srtp)
1533   */
1534  /* Note: This would need to change for optional mikey data */
1535  auth_start = (uint32_t *)hdr;
1536  auth_tag = (uint8_t *)hdr + *pkt_octet_len + sizeof(srtcp_trailer_t);
1537
1538  /* perform EKT processing if needed */
1539  ekt_write_data(stream->ekt, auth_tag, tag_len, pkt_octet_len,
1540		 rdbx_get_packet_index(&stream->rtp_rdbx));
1541
1542  /*
1543   * check sequence number for overruns, and copy it into the packet
1544   * if its value isn't too big
1545   */
1546  status = rdb_increment(&stream->rtcp_rdb);
1547  if (status)
1548    return status;
1549  seq_num = rdb_get_value(&stream->rtcp_rdb);
1550  *trailer |= htonl(seq_num);
1551  debug_print(mod_srtp, "srtcp index: %x", seq_num);
1552
1553  /*
1554   * if we're using rindael counter mode, set nonce and seq
1555   */
1556  if (stream->rtcp_cipher->type == &aes_icm) {
1557    v128_t iv;
1558
1559    iv.v32[0] = 0;
1560    iv.v32[1] = hdr->ssrc;  /* still in network order! */
1561    iv.v32[2] = htonl(seq_num >> 16);
1562    iv.v32[3] = htonl(seq_num << 16);
1563    status = aes_icm_set_iv((aes_icm_ctx_t*)stream->rtcp_cipher->state, &iv);
1564
1565  } else {
1566    v128_t iv;
1567
1568    /* otherwise, just set the index to seq_num */
1569    iv.v32[0] = 0;
1570    iv.v32[1] = 0;
1571    iv.v32[2] = 0;
1572    iv.v32[3] = htonl(seq_num);
1573    status = cipher_set_iv(stream->rtcp_cipher, &iv);
1574  }
1575  if (status)
1576    return err_status_cipher_fail;
1577
1578  /*
1579   * if we're authenticating using a universal hash, put the keystream
1580   * prefix into the authentication tag
1581   */
1582
1583  /* if auth_start is non-null, then put keystream into tag  */
1584  if (auth_start) {
1585
1586    /* put keystream prefix into auth_tag */
1587    prefix_len = auth_get_prefix_length(stream->rtcp_auth);
1588    status = cipher_output(stream->rtcp_cipher, auth_tag, prefix_len);
1589
1590    debug_print(mod_srtp, "keystream prefix: %s",
1591		octet_string_hex_string(auth_tag, prefix_len));
1592
1593    if (status)
1594      return err_status_cipher_fail;
1595  }
1596
1597  /* if we're encrypting, exor keystream into the message */
1598  if (enc_start) {
1599    status = cipher_encrypt(stream->rtcp_cipher,
1600			    (uint8_t *)enc_start, &enc_octet_len);
1601    if (status)
1602      return err_status_cipher_fail;
1603  }
1604
1605  /* initialize auth func context */
1606  auth_start(stream->rtcp_auth);
1607
1608  /*
1609   * run auth func over packet (including trailer), and write the
1610   * result at auth_tag
1611   */
1612  status = auth_compute(stream->rtcp_auth,
1613			(uint8_t *)auth_start,
1614			(*pkt_octet_len) + sizeof(srtcp_trailer_t),
1615			auth_tag);
1616  debug_print(mod_srtp, "srtcp auth tag:    %s",
1617	      octet_string_hex_string(auth_tag, tag_len));
1618  if (status)
1619    return err_status_auth_fail;
1620
1621  /* increase the packet length by the length of the auth tag and seq_num*/
1622  *pkt_octet_len += (tag_len + sizeof(srtcp_trailer_t));
1623
1624  return err_status_ok;
1625}
1626
1627
1628err_status_t
1629srtp_unprotect_rtcp(srtp_t ctx, void *srtcp_hdr, int *pkt_octet_len) {
1630  srtcp_hdr_t *hdr = (srtcp_hdr_t *)srtcp_hdr;
1631  uint32_t *enc_start;      /* pointer to start of encrypted portion  */
1632  uint32_t *auth_start;     /* pointer to start of auth. portion      */
1633  uint32_t *trailer;        /* pointer to start of trailer            */
1634  unsigned enc_octet_len = 0;/* number of octets in encrypted portion */
1635  uint8_t *auth_tag = NULL; /* location of auth_tag within packet     */
1636  uint8_t tmp_tag[SRTP_MAX_TAG_LEN];
1637  uint8_t tag_copy[SRTP_MAX_TAG_LEN];
1638  err_status_t status;
1639  unsigned auth_len;
1640  int tag_len;
1641  srtp_stream_ctx_t *stream;
1642  int prefix_len;
1643  uint32_t seq_num;
1644  int e_bit_in_packet;     /* whether the E-bit was found in the packet */
1645  int sec_serv_confidentiality; /* whether confidentiality was requested */
1646
1647  /* we assume the hdr is 32-bit aligned to start */
1648  /*
1649   * look up ssrc in srtp_stream list, and process the packet with
1650   * the appropriate stream.  if we haven't seen this stream before,
1651   * there's only one key for this srtp_session, and the cipher
1652   * supports key-sharing, then we assume that a new stream using
1653   * that key has just started up
1654   */
1655  stream = srtp_get_stream(ctx, hdr->ssrc);
1656  if (stream == NULL) {
1657    if (ctx->stream_template != NULL) {
1658      stream = ctx->stream_template;
1659
1660      /*
1661       * check to see if stream_template has an EKT data structure, in
1662       * which case we initialize the template using the EKT policy
1663       * referenced by that data (which consists of decrypting the
1664       * master key from the EKT field)
1665       *
1666       * this function initializes a *provisional* stream, and this
1667       * stream should not be accepted until and unless the packet
1668       * passes its authentication check
1669       */
1670      if (stream->ekt != NULL) {
1671	status = srtp_stream_init_from_ekt(stream, srtcp_hdr, *pkt_octet_len);
1672	if (status)
1673	  return status;
1674      }
1675
1676      debug_print(mod_srtp, "srtcp using provisional stream (SSRC: 0x%08x)",
1677		  hdr->ssrc);
1678    } else {
1679      /* no template stream, so we return an error */
1680      return err_status_no_ctx;
1681    }
1682  }
1683
1684  sec_serv_confidentiality = stream->rtcp_services == sec_serv_conf ||
1685      stream->rtcp_services == sec_serv_conf_and_auth;
1686
1687  /* get tag length from stream context */
1688  tag_len = auth_get_tag_length(stream->rtcp_auth);
1689
1690  /*
1691   * set encryption start, encryption length, and trailer
1692   */
1693  enc_octet_len = *pkt_octet_len -
1694                  (octets_in_rtcp_header + tag_len + sizeof(srtcp_trailer_t));
1695  /* index & E (encryption) bit follow normal data.  hdr->len
1696	 is the number of words (32-bit) in the normal packet minus 1 */
1697  /* This should point trailer to the word past the end of the
1698	 normal data. */
1699  /* This would need to be modified for optional mikey data */
1700  /*
1701   * NOTE: trailer is 32-bit aligned because RTCP 'packets' are always
1702   *	 multiples of 32-bits (RFC 3550 6.1)
1703   */
1704  trailer = (uint32_t *) ((char *) hdr +
1705		     *pkt_octet_len -(tag_len + sizeof(srtcp_trailer_t)));
1706  e_bit_in_packet = (*((unsigned char *) trailer) & SRTCP_E_BYTE_BIT) == SRTCP_E_BYTE_BIT;
1707  if (e_bit_in_packet != sec_serv_confidentiality) {
1708    return err_status_cant_check;
1709  }
1710  if (sec_serv_confidentiality) {
1711    enc_start = (uint32_t *)hdr + uint32s_in_rtcp_header;
1712  } else {
1713    enc_octet_len = 0;
1714    enc_start = NULL; /* this indicates that there's no encryption */
1715  }
1716
1717  /*
1718   * set the auth_start and auth_tag pointers to the proper locations
1719   * (note that srtcp *always* uses authentication, unlike srtp)
1720   */
1721  auth_start = (uint32_t *)hdr;
1722  auth_len = *pkt_octet_len - tag_len;
1723  auth_tag = (uint8_t *)hdr + auth_len;
1724
1725  /*
1726   * if EKT is in use, then we make a copy of the tag from the packet,
1727   * and then zeroize the location of the base tag
1728   *
1729   * we first re-position the auth_tag pointer so that it points to
1730   * the base tag
1731   */
1732  if (stream->ekt) {
1733    auth_tag -= ekt_octets_after_base_tag(stream->ekt);
1734    memcpy(tag_copy, auth_tag, tag_len);
1735    octet_string_set_to_zero(auth_tag, tag_len);
1736    auth_tag = tag_copy;
1737    auth_len += tag_len;
1738  }
1739
1740  /*
1741   * check the sequence number for replays
1742   */
1743  /* this is easier than dealing with bitfield access */
1744  seq_num = ntohl(*trailer) & SRTCP_INDEX_MASK;
1745  debug_print(mod_srtp, "srtcp index: %x", seq_num);
1746  status = rdb_check(&stream->rtcp_rdb, seq_num);
1747  if (status)
1748    return status;
1749
1750  /*
1751   * if we're using aes counter mode, set nonce and seq
1752   */
1753  if (stream->rtcp_cipher->type == &aes_icm) {
1754    v128_t iv;
1755
1756    iv.v32[0] = 0;
1757    iv.v32[1] = hdr->ssrc; /* still in network order! */
1758    iv.v32[2] = htonl(seq_num >> 16);
1759    iv.v32[3] = htonl(seq_num << 16);
1760    status = aes_icm_set_iv((aes_icm_ctx_t*)stream->rtcp_cipher->state, &iv);
1761
1762  } else {
1763    v128_t iv;
1764
1765    /* otherwise, just set the index to seq_num */
1766    iv.v32[0] = 0;
1767    iv.v32[1] = 0;
1768    iv.v32[2] = 0;
1769    iv.v32[3] = htonl(seq_num);
1770    status = cipher_set_iv(stream->rtcp_cipher, &iv);
1771
1772  }
1773  if (status)
1774    return err_status_cipher_fail;
1775
1776  /* initialize auth func context */
1777  auth_start(stream->rtcp_auth);
1778
1779  /* run auth func over packet, put result into tmp_tag */
1780  status = auth_compute(stream->rtcp_auth, (uint8_t *)auth_start,
1781			auth_len, tmp_tag);
1782  debug_print(mod_srtp, "srtcp computed tag:       %s",
1783	      octet_string_hex_string(tmp_tag, tag_len));
1784  if (status)
1785    return err_status_auth_fail;
1786
1787  /* compare the tag just computed with the one in the packet */
1788  debug_print(mod_srtp, "srtcp tag from packet:    %s",
1789	      octet_string_hex_string(auth_tag, tag_len));
1790  if (octet_string_is_eq(tmp_tag, auth_tag, tag_len))
1791    return err_status_auth_fail;
1792
1793  /*
1794   * if we're authenticating using a universal hash, put the keystream
1795   * prefix into the authentication tag
1796   */
1797  prefix_len = auth_get_prefix_length(stream->rtcp_auth);
1798  if (prefix_len) {
1799    status = cipher_output(stream->rtcp_cipher, auth_tag, prefix_len);
1800    debug_print(mod_srtp, "keystream prefix: %s",
1801		octet_string_hex_string(auth_tag, prefix_len));
1802    if (status)
1803      return err_status_cipher_fail;
1804  }
1805
1806  /* if we're decrypting, exor keystream into the message */
1807  if (enc_start) {
1808    status = cipher_encrypt(stream->rtcp_cipher,
1809			    (uint8_t *)enc_start, &enc_octet_len);
1810    if (status)
1811      return err_status_cipher_fail;
1812  }
1813
1814  /* decrease the packet length by the length of the auth tag and seq_num */
1815  *pkt_octet_len -= (tag_len + sizeof(srtcp_trailer_t));
1816
1817  /*
1818   * if EKT is in effect, subtract the EKT data out of the packet
1819   * length
1820   */
1821  *pkt_octet_len -= ekt_octets_after_base_tag(stream->ekt);
1822
1823  /*
1824   * verify that stream is for received traffic - this check will
1825   * detect SSRC collisions, since a stream that appears in both
1826   * srtp_protect() and srtp_unprotect() will fail this test in one of
1827   * those functions.
1828   *
1829   * we do this check *after* the authentication check, so that the
1830   * latter check will catch any attempts to fool us into thinking
1831   * that we've got a collision
1832   */
1833  if (stream->direction != dir_srtp_receiver) {
1834    if (stream->direction == dir_unknown) {
1835      stream->direction = dir_srtp_receiver;
1836    } else {
1837      srtp_handle_event(ctx, stream, event_ssrc_collision);
1838    }
1839  }
1840
1841  /*
1842   * if the stream is a 'provisional' one, in which the template context
1843   * is used, then we need to allocate a new stream at this point, since
1844   * the authentication passed
1845   */
1846  if (stream == ctx->stream_template) {
1847    srtp_stream_ctx_t *new_stream;
1848
1849    /*
1850     * allocate and initialize a new stream
1851     *
1852     * note that we indicate failure if we can't allocate the new
1853     * stream, and some implementations will want to not return
1854     * failure here
1855     */
1856    status = srtp_stream_clone(ctx->stream_template, hdr->ssrc, &new_stream);
1857    if (status)
1858      return status;
1859
1860    /* add new stream to the head of the stream_list */
1861    new_stream->next = ctx->stream_list;
1862    ctx->stream_list = new_stream;
1863
1864    /* set stream (the pointer used in this function) */
1865    stream = new_stream;
1866  }
1867
1868  /* we've passed the authentication check, so add seq_num to the rdb */
1869  rdb_add_index(&stream->rtcp_rdb, seq_num);
1870
1871
1872  return err_status_ok;
1873}
1874
1875
1876
1877/*
1878 * dtls keying for srtp
1879 */
1880
1881err_status_t
1882crypto_policy_set_from_profile_for_rtp(crypto_policy_t *policy,
1883				       srtp_profile_t profile) {
1884
1885  /* set SRTP policy from the SRTP profile in the key set */
1886  switch(profile) {
1887  case srtp_profile_aes128_cm_sha1_80:
1888    crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
1889    crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
1890    break;
1891  case srtp_profile_aes128_cm_sha1_32:
1892    crypto_policy_set_aes_cm_128_hmac_sha1_32(policy);
1893    crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
1894    break;
1895  case srtp_profile_null_sha1_80:
1896    crypto_policy_set_null_cipher_hmac_sha1_80(policy);
1897    crypto_policy_set_null_cipher_hmac_sha1_80(policy);
1898    break;
1899    /* the following profiles are not (yet) supported */
1900  case srtp_profile_null_sha1_32:
1901  case srtp_profile_aes256_cm_sha1_80:
1902  case srtp_profile_aes256_cm_sha1_32:
1903  default:
1904    return err_status_bad_param;
1905  }
1906
1907  return err_status_ok;
1908}
1909
1910err_status_t
1911crypto_policy_set_from_profile_for_rtcp(crypto_policy_t *policy,
1912					srtp_profile_t profile) {
1913
1914  /* set SRTP policy from the SRTP profile in the key set */
1915  switch(profile) {
1916  case srtp_profile_aes128_cm_sha1_80:
1917    crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
1918    break;
1919  case srtp_profile_aes128_cm_sha1_32:
1920    crypto_policy_set_aes_cm_128_hmac_sha1_80(policy);
1921    break;
1922  case srtp_profile_null_sha1_80:
1923    crypto_policy_set_null_cipher_hmac_sha1_80(policy);
1924    break;
1925    /* the following profiles are not (yet) supported */
1926  case srtp_profile_null_sha1_32:
1927  case srtp_profile_aes256_cm_sha1_80:
1928  case srtp_profile_aes256_cm_sha1_32:
1929  default:
1930    return err_status_bad_param;
1931  }
1932
1933  return err_status_ok;
1934}
1935
1936void
1937append_salt_to_key(uint8_t *key, unsigned int bytes_in_key,
1938		   uint8_t *salt, unsigned int bytes_in_salt) {
1939
1940  memcpy(key + bytes_in_key, salt, bytes_in_salt);
1941
1942}
1943
1944unsigned int
1945srtp_profile_get_master_key_length(srtp_profile_t profile) {
1946
1947  switch(profile) {
1948  case srtp_profile_aes128_cm_sha1_80:
1949    return 16;
1950    break;
1951  case srtp_profile_aes128_cm_sha1_32:
1952    return 16;
1953    break;
1954  case srtp_profile_null_sha1_80:
1955    return 16;
1956    break;
1957    /* the following profiles are not (yet) supported */
1958  case srtp_profile_null_sha1_32:
1959  case srtp_profile_aes256_cm_sha1_80:
1960  case srtp_profile_aes256_cm_sha1_32:
1961  default:
1962    return 0;  /* indicate error by returning a zero */
1963  }
1964}
1965
1966unsigned int
1967srtp_profile_get_master_salt_length(srtp_profile_t profile) {
1968
1969  switch(profile) {
1970  case srtp_profile_aes128_cm_sha1_80:
1971    return 14;
1972    break;
1973  case srtp_profile_aes128_cm_sha1_32:
1974    return 14;
1975    break;
1976  case srtp_profile_null_sha1_80:
1977    return 14;
1978    break;
1979    /* the following profiles are not (yet) supported */
1980  case srtp_profile_null_sha1_32:
1981  case srtp_profile_aes256_cm_sha1_80:
1982  case srtp_profile_aes256_cm_sha1_32:
1983  default:
1984    return 0;  /* indicate error by returning a zero */
1985  }
1986}
1987