srtp.c 154 KB
Newer Older
Cullen Jennings's avatar
Cullen Jennings committed
1 2 3 4 5 6 7 8 9
/*
 * srtp.c
 *
 * the secure real-time transport protocol
 *
 * David A. McGrew
 * Cisco Systems, Inc.
 */
/*
10
 *
Geir Istad's avatar
Geir Istad committed
11
 * Copyright (c) 2001-2017, Cisco Systems, Inc.
Cullen Jennings's avatar
Cullen Jennings committed
12
 * All rights reserved.
13
 *
Cullen Jennings's avatar
Cullen Jennings committed
14 15 16
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
17
 *
Cullen Jennings's avatar
Cullen Jennings committed
18 19
 *   Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
20
 *
Cullen Jennings's avatar
Cullen Jennings committed
21 22 23 24
 *   Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the following
 *   disclaimer in the documentation and/or other materials provided
 *   with the distribution.
25
 *
Cullen Jennings's avatar
Cullen Jennings committed
26 27 28
 *   Neither the name of the Cisco Systems, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
29
 *
Cullen Jennings's avatar
Cullen Jennings committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

45 46 47
// Leave this as the top level import. Ensures the existence of defines
#include "config.h"

48
#include "srtp_priv.h"
49 50
#include "crypto_types.h"
#include "err.h"
51 52 53
#include "ekt.h"   /* for SRTP Encrypted Key Transport */
#include "alloc.h" /* for srtp_crypto_alloc() */

54
#ifdef OPENSSL
55 56 57 58 59
#include "aes_gcm_ossl.h" /* for AES GCM mode */
#ifdef OPENSSL_KDF
#include <openssl/kdf.h>
#include "aes_icm_ossl.h" /* for AES GCM mode */
#endif
60
#endif
Cullen Jennings's avatar
Cullen Jennings committed
61

62 63
#include <limits.h>
#ifdef HAVE_NETINET_IN_H
64
#include <netinet/in.h>
65
#elif defined(HAVE_WINSOCK2_H)
66
#include <winsock2.h>
67
#endif
68

Cullen Jennings's avatar
Cullen Jennings committed
69
/* the debug module for srtp */
70
srtp_debug_module_t mod_srtp = {
71 72
    0,     /* debugging is off by default */
    "srtp" /* printable name for module */
Cullen Jennings's avatar
Cullen Jennings committed
73 74
};

75 76 77
#define octets_in_rtp_header 12
#define uint32s_in_rtp_header 3
#define octets_in_rtcp_header 8
Cullen Jennings's avatar
Cullen Jennings committed
78
#define uint32s_in_rtcp_header 2
79 80
#define octets_in_rtp_extn_hdr 4

81 82 83 84 85 86 87 88 89 90 91 92 93
static srtp_err_status_t srtp_validate_rtp_header(void *rtp_hdr,
                                                  int *pkt_octet_len)
{
    if (*pkt_octet_len < octets_in_rtp_header)
        return srtp_err_status_bad_param;

    srtp_hdr_t *hdr = (srtp_hdr_t *)rtp_hdr;

    /* Check RTP header length */
    int rtp_header_len = octets_in_rtp_header + 4 * hdr->cc;
    if (hdr->x == 1)
        rtp_header_len += octets_in_rtp_extn_hdr;

94
    if (*pkt_octet_len < rtp_header_len)
95 96 97 98 99 100 101 102 103 104 105 106 107 108
        return srtp_err_status_bad_param;

    /* Verifing profile length. */
    if (hdr->x == 1) {
        srtp_hdr_xtnd_t *xtn_hdr =
            (srtp_hdr_xtnd_t *)((uint32_t *)hdr + uint32s_in_rtp_header +
                                hdr->cc);
        int profile_len = ntohs(xtn_hdr->length);
        rtp_header_len += profile_len * 4;
        /* profile length counts the number of 32-bit words */
        if (*pkt_octet_len < rtp_header_len)
            return srtp_err_status_bad_param;
    }
    return srtp_err_status_ok;
109
}
Cullen Jennings's avatar
Cullen Jennings committed
110

111
const char *srtp_get_version_string()
112 113 114 115 116 117 118
{
    /*
     * Simply return the autotools generated string
     */
    return SRTP_VER_STRING;
}

119
unsigned int srtp_get_version()
120 121 122
{
    unsigned int major = 0, minor = 0, micro = 0;
    unsigned int rv = 0;
123
    int parse_rv;
124 125

    /*
126
     * Parse the autotools generated version
127
     */
128 129
    parse_rv = sscanf(SRTP_VERSION, "%u.%u.%u", &major, &minor, &micro);
    if (parse_rv != 3) {
130 131 132 133 134 135
        /*
         * We're expected to parse all 3 version levels.
         * If not, then this must not be an official release.
         * Return all zeros on the version
         */
        return (0);
136
    }
137

138
    /*
139 140
     * We allow 8 bits for the major and minor, while
     * allowing 16 bits for the micro.  16 bits for the micro
141
     * may be beneficial for a continuous delivery model
142 143 144 145 146 147 148
     * in the future.
     */
    rv |= (major & 0xFF) << 24;
    rv |= (minor & 0xFF) << 16;
    rv |= micro & 0xFF;
    return rv;
}
Cullen Jennings's avatar
Cullen Jennings committed
149

150 151
srtp_err_status_t srtp_stream_dealloc(srtp_stream_ctx_t *stream,
                                      const srtp_stream_ctx_t *stream_template)
152
{
153
    srtp_err_status_t status;
154 155
    unsigned int i = 0;
    srtp_session_keys_t *session_keys = NULL;
156
    srtp_session_keys_t *template_session_keys = NULL;
Ryan Hooper's avatar
Ryan Hooper committed
157

158 159 160 161 162 163 164 165
    /*
     * we use a conservative deallocation strategy - if any deallocation
     * fails, then we report that fact without trying to deallocate
     * anything else
     */
    if (stream->session_keys) {
        for (i = 0; i < stream->num_master_keys; i++) {
            session_keys = &stream->session_keys[i];
Ryan Hooper's avatar
Ryan Hooper committed
166

167 168
            if (stream_template &&
                stream->num_master_keys == stream_template->num_master_keys) {
169 170 171
                template_session_keys = &stream_template->session_keys[i];
            } else {
                template_session_keys = NULL;
172
            }
Ryan Hooper's avatar
Ryan Hooper committed
173

174 175 176 177 178 179 180 181 182 183
            /*
            * deallocate cipher, if it is not the same as that in template
            */
            if (template_session_keys &&
                session_keys->rtp_cipher == template_session_keys->rtp_cipher) {
                /* do nothing */
            } else if (session_keys->rtp_cipher) {
                status = srtp_cipher_dealloc(session_keys->rtp_cipher);
                if (status)
                    return status;
184
            }
Ryan Hooper's avatar
Ryan Hooper committed
185

186 187 188 189 190 191 192 193 194 195 196
            /*
             * deallocate auth function, if it is not the same as that in
             * template
             */
            if (template_session_keys &&
                session_keys->rtp_auth == template_session_keys->rtp_auth) {
                /* do nothing */
            } else if (session_keys->rtp_auth) {
                status = srtp_auth_dealloc(session_keys->rtp_auth);
                if (status)
                    return status;
197
            }
Ryan Hooper's avatar
Ryan Hooper committed
198

199 200 201 202 203 204 205 206
            if (template_session_keys &&
                session_keys->rtp_xtn_hdr_cipher ==
                    template_session_keys->rtp_xtn_hdr_cipher) {
                /* do nothing */
            } else if (session_keys->rtp_xtn_hdr_cipher) {
                status = srtp_cipher_dealloc(session_keys->rtp_xtn_hdr_cipher);
                if (status)
                    return status;
207
            }
Ryan Hooper's avatar
Ryan Hooper committed
208

209 210 211 212 213 214 215 216 217 218 219 220
            /*
             * deallocate rtcp cipher, if it is not the same as that in
             * template
             */
            if (template_session_keys &&
                session_keys->rtcp_cipher ==
                    template_session_keys->rtcp_cipher) {
                /* do nothing */
            } else if (session_keys->rtcp_cipher) {
                status = srtp_cipher_dealloc(session_keys->rtcp_cipher);
                if (status)
                    return status;
221
            }
Ryan Hooper's avatar
Ryan Hooper committed
222

223 224 225 226 227 228 229 230 231 232 233 234
            /*
             * deallocate rtcp auth function, if it is not the same as that in
             * template
             */
            if (template_session_keys &&
                session_keys->rtcp_auth == template_session_keys->rtcp_auth) {
                /* do nothing */
            } else if (session_keys->rtcp_auth) {
                status = srtp_auth_dealloc(session_keys->rtcp_auth);
                if (status)
                    return status;
            }
235

236 237 238 239 240 241
            /*
             * zeroize the salt value
             */
            octet_string_set_to_zero(session_keys->salt, SRTP_AEAD_SALT_LEN);
            octet_string_set_to_zero(session_keys->c_salt, SRTP_AEAD_SALT_LEN);

242
            if (session_keys->mki_id) {
243 244
                octet_string_set_to_zero(session_keys->mki_id,
                                         session_keys->mki_size);
245
                srtp_crypto_free(session_keys->mki_id);
246
                session_keys->mki_id = NULL;
247
            }
248

249 250 251 252 253 254 255 256
            /*
             * deallocate key usage limit, if it is not the same as that in
             * template
             */
            if (template_session_keys &&
                session_keys->limit == template_session_keys->limit) {
                /* do nothing */
            } else if (session_keys->limit) {
257 258
                srtp_crypto_free(session_keys->limit);
            }
259
        }
260
        srtp_crypto_free(stream->session_keys);
261
    }
Ryan Hooper's avatar
Ryan Hooper committed
262

263 264 265 266 267
    status = srtp_rdbx_dealloc(&stream->rtp_rdbx);
    if (status)
        return status;

    /* DAM - need to deallocate EKT here */
268

269 270 271 272 273
    if (stream_template &&
        stream->enc_xtn_hdr == stream_template->enc_xtn_hdr) {
        /* do nothing */
    } else if (stream->enc_xtn_hdr) {
        srtp_crypto_free(stream->enc_xtn_hdr);
274
    }
Ryan Hooper's avatar
Ryan Hooper committed
275

276 277 278 279
    /* deallocate srtp stream context */
    srtp_crypto_free(stream);

    return srtp_err_status_ok;
280 281
}

282 283 284 285 286 287 288
srtp_err_status_t srtp_stream_alloc(srtp_stream_ctx_t **str_ptr,
                                    const srtp_policy_t *p)
{
    srtp_stream_ctx_t *str;
    srtp_err_status_t stat;
    unsigned int i = 0;
    srtp_session_keys_t *session_keys = NULL;
Ryan Hooper's avatar
Ryan Hooper committed
289

290 291 292 293 294 295 296 297 298 299 300 301 302 303
    /*
     * This function allocates the stream context, rtp and rtcp ciphers
     * and auth functions, and key limit structure.  If there is a
     * failure during allocation, we free all previously allocated
     * memory and return a failure code.  The code could probably
     * be improved, but it works and should be clear.
     */

    /* allocate srtp stream and set str_ptr */
    str = (srtp_stream_ctx_t *)srtp_crypto_alloc(sizeof(srtp_stream_ctx_t));
    if (str == NULL)
        return srtp_err_status_alloc_fail;

    *str_ptr = str;
Ryan Hooper's avatar
Ryan Hooper committed
304 305

    /*
306 307
     *To keep backwards API compatible if someone is using multiple master
     * keys then key should be set to NULL
Ryan Hooper's avatar
Ryan Hooper committed
308
     */
309 310 311 312
    if (p->key != NULL) {
        str->num_master_keys = 1;
    } else {
        str->num_master_keys = p->num_master_keys;
Ryan Hooper's avatar
Ryan Hooper committed
313 314
    }

315 316
    str->session_keys = (srtp_session_keys_t *)srtp_crypto_alloc(
        sizeof(srtp_session_keys_t) * str->num_master_keys);
Cullen Jennings's avatar
Cullen Jennings committed
317

318
    if (str->session_keys == NULL) {
319
        srtp_stream_dealloc(str, NULL);
320 321
        return srtp_err_status_alloc_fail;
    }
Cullen Jennings's avatar
Cullen Jennings committed
322

323 324 325 326 327 328 329 330
    for (i = 0; i < str->num_master_keys; i++) {
        session_keys = &str->session_keys[i];

        /* allocate cipher */
        stat = srtp_crypto_kernel_alloc_cipher(
            p->rtp.cipher_type, &session_keys->rtp_cipher,
            p->rtp.cipher_key_len, p->rtp.auth_tag_len);
        if (stat) {
331
            srtp_stream_dealloc(str, NULL);
332 333
            return stat;
        }
334

335 336 337 338 339
        /* allocate auth function */
        stat = srtp_crypto_kernel_alloc_auth(
            p->rtp.auth_type, &session_keys->rtp_auth, p->rtp.auth_key_len,
            p->rtp.auth_tag_len);
        if (stat) {
340
            srtp_stream_dealloc(str, NULL);
341 342
            return stat;
        }
343

344 345 346 347 348 349 350 351
        /*
         * ...and now the RTCP-specific initialization - first, allocate
         * the cipher
         */
        stat = srtp_crypto_kernel_alloc_cipher(
            p->rtcp.cipher_type, &session_keys->rtcp_cipher,
            p->rtcp.cipher_key_len, p->rtcp.auth_tag_len);
        if (stat) {
352
            srtp_stream_dealloc(str, NULL);
353 354 355 356 357 358 359 360
            return stat;
        }

        /* allocate auth function */
        stat = srtp_crypto_kernel_alloc_auth(
            p->rtcp.auth_type, &session_keys->rtcp_auth, p->rtcp.auth_key_len,
            p->rtcp.auth_tag_len);
        if (stat) {
361
            srtp_stream_dealloc(str, NULL);
362 363 364 365 366 367 368 369 370
            return stat;
        }

        session_keys->mki_id = NULL;

        /* allocate key limit structure */
        session_keys->limit = (srtp_key_limit_ctx_t *)srtp_crypto_alloc(
            sizeof(srtp_key_limit_ctx_t));
        if (session_keys->limit == NULL) {
371
            srtp_stream_dealloc(str, NULL);
372 373
            return srtp_err_status_alloc_fail;
        }
374 375
    }

376 377 378
    /* allocate ekt data associated with stream */
    stat = srtp_ekt_alloc(&str->ekt, p->ekt);
    if (stat) {
379
        srtp_stream_dealloc(str, NULL);
Ryan Hooper's avatar
Ryan Hooper committed
380 381 382
        return stat;
    }

383 384 385
    if (p->enc_xtn_hdr && p->enc_xtn_hdr_count > 0) {
        srtp_cipher_type_id_t enc_xtn_hdr_cipher_type;
        int enc_xtn_hdr_cipher_key_len;
386

387 388 389
        str->enc_xtn_hdr = (int *)srtp_crypto_alloc(p->enc_xtn_hdr_count *
                                                    sizeof(p->enc_xtn_hdr[0]));
        if (!str->enc_xtn_hdr) {
390
            srtp_stream_dealloc(str, NULL);
391 392 393 394 395
            return srtp_err_status_alloc_fail;
        }
        memcpy(str->enc_xtn_hdr, p->enc_xtn_hdr,
               p->enc_xtn_hdr_count * sizeof(p->enc_xtn_hdr[0]));
        str->enc_xtn_hdr_count = p->enc_xtn_hdr_count;
Cullen Jennings's avatar
Cullen Jennings committed
396

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        /*
         * For GCM ciphers, the corresponding ICM cipher is used for header
         * extensions encryption.
         */
        switch (p->rtp.cipher_type) {
        case SRTP_AES_GCM_128:
            enc_xtn_hdr_cipher_type = SRTP_AES_ICM_128;
            enc_xtn_hdr_cipher_key_len = SRTP_AES_ICM_128_KEY_LEN_WSALT;
            break;
        case SRTP_AES_GCM_256:
            enc_xtn_hdr_cipher_type = SRTP_AES_ICM_256;
            enc_xtn_hdr_cipher_key_len = SRTP_AES_ICM_256_KEY_LEN_WSALT;
            break;
        default:
            enc_xtn_hdr_cipher_type = p->rtp.cipher_type;
            enc_xtn_hdr_cipher_key_len = p->rtp.cipher_key_len;
            break;
        }
Cullen Jennings's avatar
Cullen Jennings committed
415

416 417
        for (i = 0; i < str->num_master_keys; i++) {
            session_keys = &str->session_keys[i];
Cullen Jennings's avatar
Cullen Jennings committed
418

419 420 421 422 423
            /* allocate cipher for extensions header encryption */
            stat = srtp_crypto_kernel_alloc_cipher(
                enc_xtn_hdr_cipher_type, &session_keys->rtp_xtn_hdr_cipher,
                enc_xtn_hdr_cipher_key_len, 0);
            if (stat) {
424
                srtp_stream_dealloc(str, NULL);
425 426 427
                return stat;
            }
        }
Ryan Hooper's avatar
Ryan Hooper committed
428
    } else {
429 430 431 432
        for (i = 0; i < str->num_master_keys; i++) {
            session_keys = &str->session_keys[i];
            session_keys->rtp_xtn_hdr_cipher = NULL;
        }
Cullen Jennings's avatar
Cullen Jennings committed
433

434 435
        str->enc_xtn_hdr = NULL;
        str->enc_xtn_hdr_count = 0;
Ryan Hooper's avatar
Ryan Hooper committed
436 437
    }

438 439
    return srtp_err_status_ok;
}
Ryan Hooper's avatar
Ryan Hooper committed
440

Cullen Jennings's avatar
Cullen Jennings committed
441 442 443
/*
 * srtp_stream_clone(stream_template, new) allocates a new stream and
 * initializes it using the cipher and auth of the stream_template
444
 *
Cullen Jennings's avatar
Cullen Jennings committed
445 446 447 448
 * the only unique data in a cloned stream is the replay database and
 * the SSRC
 */

449 450 451 452 453 454 455 456 457
srtp_err_status_t srtp_stream_clone(const srtp_stream_ctx_t *stream_template,
                                    uint32_t ssrc,
                                    srtp_stream_ctx_t **str_ptr)
{
    srtp_err_status_t status;
    srtp_stream_ctx_t *str;
    unsigned int i = 0;
    srtp_session_keys_t *session_keys = NULL;
    const srtp_session_keys_t *template_session_keys = NULL;
Ryan Hooper's avatar
Ryan Hooper committed
458

459
    debug_print(mod_srtp, "cloning stream (SSRC: 0x%08x)", ntohl(ssrc));
Ulf Olsson's avatar
Ulf Olsson committed
460

461 462 463 464 465
    /* allocate srtp stream and set str_ptr */
    str = (srtp_stream_ctx_t *)srtp_crypto_alloc(sizeof(srtp_stream_ctx_t));
    if (str == NULL)
        return srtp_err_status_alloc_fail;
    *str_ptr = str;
Cullen Jennings's avatar
Cullen Jennings committed
466

467 468 469
    str->num_master_keys = stream_template->num_master_keys;
    str->session_keys = (srtp_session_keys_t *)srtp_crypto_alloc(
        sizeof(srtp_session_keys_t) * str->num_master_keys);
470

471
    if (str->session_keys == NULL) {
472
        srtp_stream_dealloc(*str_ptr, stream_template);
473 474 475
        *str_ptr = NULL;
        return srtp_err_status_alloc_fail;
    }
Cullen Jennings's avatar
Cullen Jennings committed
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    for (i = 0; i < stream_template->num_master_keys; i++) {
        session_keys = &str->session_keys[i];
        template_session_keys = &stream_template->session_keys[i];

        /* set cipher and auth pointers to those of the template */
        session_keys->rtp_cipher = template_session_keys->rtp_cipher;
        session_keys->rtp_auth = template_session_keys->rtp_auth;
        session_keys->rtp_xtn_hdr_cipher =
            template_session_keys->rtp_xtn_hdr_cipher;
        session_keys->rtcp_cipher = template_session_keys->rtcp_cipher;
        session_keys->rtcp_auth = template_session_keys->rtcp_auth;
        session_keys->mki_size = template_session_keys->mki_size;

        if (template_session_keys->mki_size == 0) {
            session_keys->mki_id = NULL;
        } else {
            session_keys->mki_id =
                srtp_crypto_alloc(template_session_keys->mki_size);
David McGrew's avatar
David McGrew committed
495

496
            if (session_keys->mki_id == NULL) {
497
                srtp_stream_dealloc(*str_ptr, stream_template);
498
                *str_ptr = NULL;
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                return srtp_err_status_init_fail;
            }
            memcpy(session_keys->mki_id, template_session_keys->mki_id,
                   session_keys->mki_size);
        }
        /* Copy the salt values */
        memcpy(session_keys->salt, template_session_keys->salt,
               SRTP_AEAD_SALT_LEN);
        memcpy(session_keys->c_salt, template_session_keys->c_salt,
               SRTP_AEAD_SALT_LEN);

        /* set key limit to point to that of the template */
        status = srtp_key_limit_clone(template_session_keys->limit,
                                      &session_keys->limit);
        if (status) {
514
            srtp_stream_dealloc(*str_ptr, stream_template);
515 516 517 518
            *str_ptr = NULL;
            return status;
        }
    }
519

520 521 522 523
    /* initialize replay databases */
    status = srtp_rdbx_init(
        &str->rtp_rdbx, srtp_rdbx_get_window_size(&stream_template->rtp_rdbx));
    if (status) {
524
        srtp_stream_dealloc(*str_ptr, stream_template);
525 526 527 528 529
        *str_ptr = NULL;
        return status;
    }
    srtp_rdb_init(&str->rtcp_rdb);
    str->allow_repeat_tx = stream_template->allow_repeat_tx;
Cullen Jennings's avatar
Cullen Jennings committed
530

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    /* set ssrc to that provided */
    str->ssrc = ssrc;

    /* reset pending ROC */
    str->pending_roc = 0;

    /* set direction and security services */
    str->direction = stream_template->direction;
    str->rtp_services = stream_template->rtp_services;
    str->rtcp_services = stream_template->rtcp_services;

    /* set pointer to EKT data associated with stream */
    str->ekt = stream_template->ekt;

    /* copy information about extensions header encryption */
    str->enc_xtn_hdr = stream_template->enc_xtn_hdr;
    str->enc_xtn_hdr_count = stream_template->enc_xtn_hdr_count;

    /* defensive coding */
    str->next = NULL;
    return srtp_err_status_ok;
}
Cullen Jennings's avatar
Cullen Jennings committed
553 554 555 556 557 558

/*
 * key derivation functions, internal to libSRTP
 *
 * srtp_kdf_t is a key derivation context
 *
559 560
 * srtp_kdf_init(&kdf, cipher_id, k, keylen) initializes kdf to use cipher
 * described by cipher_id, with the master key k with length in octets keylen.
561
 *
Cullen Jennings's avatar
Cullen Jennings committed
562 563 564 565 566
 * srtp_kdf_generate(&kdf, l, kl, keylen) derives the key
 * corresponding to label l and puts it into kl; the length
 * of the key in octets is provided as keylen.  this function
 * should be called once for each subkey that is derived.
 *
567
 * srtp_kdf_clear(&kdf) zeroizes and deallocates the kdf state
Cullen Jennings's avatar
Cullen Jennings committed
568 569 570
 */

typedef enum {
571 572 573 574 575 576 577 578
    label_rtp_encryption = 0x00,
    label_rtp_msg_auth = 0x01,
    label_rtp_salt = 0x02,
    label_rtcp_encryption = 0x03,
    label_rtcp_msg_auth = 0x04,
    label_rtcp_salt = 0x05,
    label_rtp_header_encryption = 0x06,
    label_rtp_header_salt = 0x07
Cullen Jennings's avatar
Cullen Jennings committed
579 580
} srtp_prf_label;

581 582 583 584
#define MAX_SRTP_KEY_LEN 256

#if defined(OPENSSL) && defined(OPENSSL_KDF)
#define MAX_SRTP_AESKEY_LEN 32
585
#define MAX_SRTP_SALT_LEN 14
Cullen Jennings's avatar
Cullen Jennings committed
586 587 588 589 590

/*
 * srtp_kdf_t represents a key derivation function.  The SRTP
 * default KDF is the only one implemented at present.
 */
591
typedef struct {
592 593 594
    uint8_t master_key[MAX_SRTP_AESKEY_LEN];
    uint8_t master_salt[MAX_SRTP_SALT_LEN];
    const EVP_CIPHER *evp;
Cullen Jennings's avatar
Cullen Jennings committed
595 596
} srtp_kdf_t;

597 598 599 600
static srtp_err_status_t srtp_kdf_init(srtp_kdf_t *kdf,
                                       const uint8_t *key,
                                       int key_len,
                                       int salt_len)
601 602
{
    memset(kdf, 0x0, sizeof(srtp_kdf_t));
603

604
    /* The NULL cipher has zero key length */
605 606
    if (key_len == 0)
        return srtp_err_status_ok;
Cullen Jennings's avatar
Cullen Jennings committed
607

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    if ((key_len > MAX_SRTP_AESKEY_LEN) || (salt_len > MAX_SRTP_SALT_LEN)) {
        return srtp_err_status_bad_param;
    }
    switch (key_len) {
    case SRTP_AES_256_KEYSIZE:
        kdf->evp = EVP_aes_256_ctr();
        break;
    case SRTP_AES_192_KEYSIZE:
        kdf->evp = EVP_aes_192_ctr();
        break;
    case SRTP_AES_128_KEYSIZE:
        kdf->evp = EVP_aes_128_ctr();
        break;
    default:
        return srtp_err_status_bad_param;
        break;
    }
625 626
    memcpy(kdf->master_key, key, key_len);
    memcpy(kdf->master_salt, key + key_len, salt_len);
627
    return srtp_err_status_ok;
Cullen Jennings's avatar
Cullen Jennings committed
628 629
}

630 631 632 633
static srtp_err_status_t srtp_kdf_generate(srtp_kdf_t *kdf,
                                           srtp_prf_label label,
                                           uint8_t *key,
                                           unsigned int length)
634 635
{
    int ret;
Cullen Jennings's avatar
Cullen Jennings committed
636

637
    /* The NULL cipher will not have an EVP */
638 639
    if (!kdf->evp)
        return srtp_err_status_ok;
640 641 642 643 644 645 646
    octet_string_set_to_zero(key, length);

    /*
     * Invoke the OpenSSL SRTP KDF function
     * This is useful if OpenSSL is in FIPS mode and FIP
     * compliance is required for SRTP.
     */
647 648
    ret = kdf_srtp(kdf->evp, (char *)&kdf->master_key,
                   (char *)&kdf->master_salt, NULL, NULL, label, (char *)key);
649 650 651 652 653 654 655
    if (ret == -1) {
        return (srtp_err_status_algo_fail);
    }

    return srtp_err_status_ok;
}

656 657
static srtp_err_status_t srtp_kdf_clear(srtp_kdf_t *kdf)
{
658 659
    octet_string_set_to_zero(kdf->master_key, MAX_SRTP_AESKEY_LEN);
    octet_string_set_to_zero(kdf->master_salt, MAX_SRTP_SALT_LEN);
660 661
    kdf->evp = NULL;

662
    return srtp_err_status_ok;
663 664
}

665
#else  /* if OPENSSL_KDF */
666 667 668 669 670

/*
 * srtp_kdf_t represents a key derivation function.  The SRTP
 * default KDF is the only one implemented at present.
 */
671 672
typedef struct {
    srtp_cipher_t *cipher; /* cipher used for key derivation  */
673 674
} srtp_kdf_t;

675 676 677
static srtp_err_status_t srtp_kdf_init(srtp_kdf_t *kdf,
                                       const uint8_t *key,
                                       int key_len)
678
{
679 680
    srtp_cipher_type_id_t cipher_id;
    switch (key_len) {
681
    case SRTP_AES_ICM_256_KEY_LEN_WSALT:
682
        cipher_id = SRTP_AES_ICM_256;
683
        break;
684
    case SRTP_AES_ICM_192_KEY_LEN_WSALT:
685
        cipher_id = SRTP_AES_ICM_192;
686
        break;
687
    case SRTP_AES_ICM_128_KEY_LEN_WSALT:
688
        cipher_id = SRTP_AES_ICM_128;
689 690 691 692 693 694
        break;
    default:
        return srtp_err_status_bad_param;
        break;
    }

695
    srtp_err_status_t stat;
696
    stat = srtp_crypto_kernel_alloc_cipher(cipher_id, &kdf->cipher, key_len, 0);
697 698
    if (stat)
        return stat;
699 700 701 702 703 704 705 706 707

    stat = srtp_cipher_init(kdf->cipher, key);
    if (stat) {
        srtp_cipher_dealloc(kdf->cipher);
        return stat;
    }
    return srtp_err_status_ok;
}

708 709 710 711
static srtp_err_status_t srtp_kdf_generate(srtp_kdf_t *kdf,
                                           srtp_prf_label label,
                                           uint8_t *key,
                                           unsigned int length)
712 713 714
{
    srtp_err_status_t status;
    v128_t nonce;
715

716 717 718
    /* set eigth octet of nonce to <label>, set the rest of it to zero */
    v128_set_to_zero(&nonce);
    nonce.v8[7] = label;
719 720 721 722 723 724

    status = srtp_cipher_set_iv(kdf->cipher, (uint8_t *)&nonce,
                                srtp_direction_encrypt);
    if (status)
        return status;

725 726 727
    /* generate keystream output */
    octet_string_set_to_zero(key, length);
    status = srtp_cipher_encrypt(kdf->cipher, key, &length);
728 729
    if (status)
        return status;
Cullen Jennings's avatar
Cullen Jennings committed
730

731
    return srtp_err_status_ok;
Cullen Jennings's avatar
Cullen Jennings committed
732 733
}

734 735
static srtp_err_status_t srtp_kdf_clear(srtp_kdf_t *kdf)
{
736 737
    srtp_err_status_t status;
    status = srtp_cipher_dealloc(kdf->cipher);
738 739
    if (status)
        return status;
740
    kdf->cipher = NULL;
741
    return srtp_err_status_ok;
Cullen Jennings's avatar
Cullen Jennings committed
742
}
743
#endif /* else OPENSSL_KDF */
Cullen Jennings's avatar
Cullen Jennings committed
744 745

/*
746
 *  end of key derivation functions
Cullen Jennings's avatar
Cullen Jennings committed
747 748
 */

Jonathan Lennox's avatar
Jonathan Lennox committed
749 750 751
/* Get the base key length corresponding to a given combined key+salt
 * length for the given cipher.
 * TODO: key and salt lengths should be separate fields in the policy.  */
752 753
static inline int base_key_length(const srtp_cipher_type_t *cipher,
                                  int key_length)
Jonathan Lennox's avatar
Jonathan Lennox committed
754
{
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    switch (cipher->id) {
    case SRTP_AES_ICM_128:
    case SRTP_AES_ICM_192:
    case SRTP_AES_ICM_256:
        /* The legacy modes are derived from
         * the configured key length on the policy */
        return key_length - SRTP_SALT_LEN;
        break;
    case SRTP_AES_GCM_128:
        return key_length - SRTP_AEAD_SALT_LEN;
        break;
    case SRTP_AES_GCM_256:
        return key_length - SRTP_AEAD_SALT_LEN;
        break;
    default:
        return key_length;
        break;
    }
Jonathan Lennox's avatar
Jonathan Lennox committed
773 774
}

775
unsigned int srtp_validate_policy_master_keys(const srtp_policy_t *policy)
Ryan Hooper's avatar
Ryan Hooper committed
776
{
777
    unsigned long i = 0;
Ryan Hooper's avatar
Ryan Hooper committed
778

779 780
    if (policy->key == NULL) {
        if (policy->num_master_keys <= 0)
Ryan Hooper's avatar
Ryan Hooper committed
781
            return 0;
782 783

        if (policy->num_master_keys > SRTP_MAX_NUM_MASTER_KEYS)
784 785
            return 0;

786 787 788
        for (i = 0; i < policy->num_master_keys; i++) {
            if (policy->keys[i]->key == NULL)
                return 0;
789 790
            if (policy->keys[i]->mki_size > SRTP_MAX_MKI_LEN)
                return 0;
791
        }
Ryan Hooper's avatar
Ryan Hooper committed
792 793 794 795 796
    }

    return 1;
}

797 798 799 800
srtp_session_keys_t *srtp_get_session_keys_with_mki_index(
    srtp_stream_ctx_t *stream,
    unsigned int use_mki,
    unsigned int mki_index)
801
{
Ryan Hooper's avatar
Ryan Hooper committed
802
    if (use_mki) {
803 804
        if (mki_index >= stream->num_master_keys) {
            return NULL;
Ryan Hooper's avatar
Ryan Hooper committed
805
        }
806
        return &stream->session_keys[mki_index];
Ryan Hooper's avatar
Ryan Hooper committed
807
    }
808

Ryan Hooper's avatar
Ryan Hooper committed
809 810 811
    return &stream->session_keys[0];
}

812 813 814
unsigned int srtp_inject_mki(uint8_t *mki_tag_location,
                             srtp_session_keys_t *session_keys,
                             unsigned int use_mki)
Ryan Hooper's avatar
Ryan Hooper committed
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
{
    unsigned int mki_size = 0;

    if (use_mki) {
        mki_size = session_keys->mki_size;

        if (mki_size != 0) {
            // Write MKI into memory
            memcpy(mki_tag_location, session_keys->mki_id, mki_size);
        }
    }

    return mki_size;
}

830 831 832 833 834
srtp_err_status_t srtp_stream_init_all_master_keys(
    srtp_stream_ctx_t *srtp,
    unsigned char *key,
    srtp_master_key_t **keys,
    const unsigned int max_master_keys)
835
{
836
    unsigned int i = 0;
Ryan Hooper's avatar
Ryan Hooper committed
837
    srtp_err_status_t status = srtp_err_status_ok;
838 839
    srtp_master_key_t single_master_key;

840
    if (key != NULL) {
841 842 843 844 845 846 847
        srtp->num_master_keys = 1;
        single_master_key.key = key;
        single_master_key.mki_id = NULL;
        single_master_key.mki_size = 0;
        status = srtp_stream_init_keys(srtp, &single_master_key, 0);
    } else {
        srtp->num_master_keys = max_master_keys;
Ryan Hooper's avatar
Ryan Hooper committed
848

849 850
        for (i = 0; i < srtp->num_master_keys && i < SRTP_MAX_NUM_MASTER_KEYS;
             i++) {
851
            status = srtp_stream_init_keys(srtp, keys[i], i);
Ryan Hooper's avatar
Ryan Hooper committed
852

853 854 855
            if (status) {
                return status;
            }
Ryan Hooper's avatar
Ryan Hooper committed
856 857 858 859 860 861
        }
    }

    return status;
}

862 863 864
srtp_err_status_t srtp_stream_init_keys(srtp_stream_ctx_t *srtp,
                                        srtp_master_key_t *master_key,
                                        const unsigned int current_mki_index)
865
{
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    srtp_err_status_t stat;
    srtp_kdf_t kdf;
    uint8_t tmp_key[MAX_SRTP_KEY_LEN];
    int kdf_keylen = 30, rtp_keylen, rtcp_keylen;
    int rtp_base_key_len, rtp_salt_len;
    int rtcp_base_key_len, rtcp_salt_len;
    srtp_session_keys_t *session_keys = NULL;
    unsigned char *key = master_key->key;

    /* If RTP or RTCP have a key length > AES-128, assume matching kdf. */
    /* TODO: kdf algorithm, master key length, and master salt length should
     * be part of srtp_policy_t.
    */
    session_keys = &srtp->session_keys[current_mki_index];

/* initialize key limit to maximum value */
#ifdef NO_64BIT_MATH
    {
        uint64_t temp;
        temp = make64(UINT_MAX, UINT_MAX);
        srtp_key_limit_set(session_keys->limit, temp);
    }
888
#else
889
    srtp_key_limit_set(session_keys->limit, 0xffffffffffffLL);
890 891
#endif

892 893
    if (master_key->mki_size != 0) {
        session_keys->mki_id = srtp_crypto_alloc(master_key->mki_size);
894

895 896
        if (session_keys->mki_id == NULL) {
            return srtp_err_status_init_fail;
897
        }
898 899 900 901 902 903
        memcpy(session_keys->mki_id, master_key->mki_id, master_key->mki_size);
    } else {
        session_keys->mki_id = NULL;
    }

    session_keys->mki_size = master_key->mki_size;
904

905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    rtp_keylen = srtp_cipher_get_key_length(session_keys->rtp_cipher);
    rtcp_keylen = srtp_cipher_get_key_length(session_keys->rtcp_cipher);
    rtp_base_key_len =
        base_key_length(session_keys->rtp_cipher->type, rtp_keylen);
    rtp_salt_len = rtp_keylen - rtp_base_key_len;

    if (rtp_keylen > kdf_keylen) {
        kdf_keylen = 46; /* AES-CTR mode is always used for KDF */
    }

    if (rtcp_keylen > kdf_keylen) {
        kdf_keylen = 46; /* AES-CTR mode is always used for KDF */
    }

    debug_print(mod_srtp, "srtp key len: %d", rtp_keylen);
    debug_print(mod_srtp, "srtcp key len: %d", rtcp_keylen);
    debug_print(mod_srtp, "base key len: %d", rtp_base_key_len);
    debug_print(mod_srtp, "kdf key len: %d", kdf_keylen);
    debug_print(mod_srtp, "rtp salt len: %d", rtp_salt_len);

    /*
     * Make sure the key given to us is 'zero' appended.  GCM
     * mode uses a shorter master SALT (96 bits), but still relies on
     * the legacy CTR mode KDF, which uses a 112 bit master SALT.
     */
    memset(tmp_key, 0x0, MAX_SRTP_KEY_LEN);
    memcpy(tmp_key, key, (rtp_base_key_len + rtp_salt_len));

/* initialize KDF state     */
934
#if defined(OPENSSL) && defined(OPENSSL_KDF)
935 936
    stat = srtp_kdf_init(&kdf, (const uint8_t *)tmp_key, rtp_base_key_len,
                         rtp_salt_len);
937
#else
938
    stat = srtp_kdf_init(&kdf, (const uint8_t *)tmp_key, kdf_keylen);
939
#endif
940
    if (stat) {
941 942
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
943 944 945
        return srtp_err_status_init_fail;
    }

946 947 948
    /* generate encryption key  */
    stat = srtp_kdf_generate(&kdf, label_rtp_encryption, tmp_key,
                             rtp_base_key_len);
949
    if (stat) {
950 951 952
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
953
    }
954 955
    debug_print(mod_srtp, "cipher key: %s",
                srtp_octet_string_hex_string(tmp_key, rtp_base_key_len));
956 957 958 959 960

    /*
     * if the cipher in the srtp context uses a salt, then we need
     * to generate the salt value
     */
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    if (rtp_salt_len > 0) {
        debug_print(mod_srtp, "found rtp_salt_len > 0, generating salt", NULL);

        /* generate encryption salt, put after encryption key */
        stat = srtp_kdf_generate(&kdf, label_rtp_salt,
                                 tmp_key + rtp_base_key_len, rtp_salt_len);
        if (stat) {
            /* zeroize temp buffer */
            octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
            return srtp_err_status_init_fail;
        }
        memcpy(session_keys->salt, tmp_key + rtp_base_key_len,
               SRTP_AEAD_SALT_LEN);
    }
    if (rtp_salt_len > 0) {
        debug_print(mod_srtp, "cipher salt: %s",
                    srtp_octet_string_hex_string(tmp_key + rtp_base_key_len,
                                                 rtp_salt_len));
    }

    /* initialize cipher */
    stat = srtp_cipher_init(session_keys->rtp_cipher, tmp_key);
    if (stat) {
        /* zeroize temp buffer */
985 986 987
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
    }
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

    if (session_keys->rtp_xtn_hdr_cipher) {
        /* generate extensions header encryption key  */
        int rtp_xtn_hdr_keylen;
        int rtp_xtn_hdr_base_key_len;
        int rtp_xtn_hdr_salt_len;
        srtp_kdf_t tmp_kdf;
        srtp_kdf_t *xtn_hdr_kdf;

        if (session_keys->rtp_xtn_hdr_cipher->type !=
            session_keys->rtp_cipher->type) {
            /*
             * With GCM ciphers, the header extensions are still encrypted using
             * the corresponding ICM cipher.
             * See https://tools.ietf.org/html/rfc7714#section-8.3
             */
            uint8_t tmp_xtn_hdr_key[MAX_SRTP_KEY_LEN];
            rtp_xtn_hdr_keylen =
                srtp_cipher_get_key_length(session_keys->rtp_xtn_hdr_cipher);
            rtp_xtn_hdr_base_key_len = base_key_length(
                session_keys->rtp_xtn_hdr_cipher->type, rtp_xtn_hdr_keylen);
            rtp_xtn_hdr_salt_len =
                rtp_xtn_hdr_keylen - rtp_xtn_hdr_base_key_len;
            if (rtp_xtn_hdr_salt_len > rtp_salt_len) {
                switch (session_keys->rtp_cipher->type->id) {
                case SRTP_AES_GCM_128:
                case SRTP_AES_GCM_256:
                    /*
                     * The shorter GCM salt is padded to the required ICM salt
                     * length.
                     */
                    rtp_xtn_hdr_salt_len = rtp_salt_len;
                    break;
                default:
                    /* zeroize temp buffer */
                    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
                    return srtp_err_status_bad_param;
                }
            }
            memset(tmp_xtn_hdr_key, 0x0, MAX_SRTP_KEY_LEN);
            memcpy(tmp_xtn_hdr_key, key,
                   (rtp_xtn_hdr_base_key_len + rtp_xtn_hdr_salt_len));
            xtn_hdr_kdf = &tmp_kdf;

/* initialize KDF state */
#if defined(OPENSSL) && defined(OPENSSL_KDF)
            stat =
                srtp_kdf_init(xtn_hdr_kdf, (const uint8_t *)tmp_xtn_hdr_key,
                              rtp_xtn_hdr_base_key_len, rtp_xtn_hdr_salt_len);
#else
            stat = srtp_kdf_init(xtn_hdr_kdf, (const uint8_t *)tmp_xtn_hdr_key,
                                 kdf_keylen);
#endif
            octet_string_set_to_zero(tmp_xtn_hdr_key, MAX_SRTP_KEY_LEN);
            if (stat) {
                /* zeroize temp buffer */
                octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
                return srtp_err_status_init_fail;
            }
        } else {
            /* Reuse main KDF. */
            rtp_xtn_hdr_keylen = rtp_keylen;
            rtp_xtn_hdr_base_key_len = rtp_base_key_len;
            rtp_xtn_hdr_salt_len = rtp_salt_len;
            xtn_hdr_kdf = &kdf;
        }

        stat = srtp_kdf_generate(xtn_hdr_kdf, label_rtp_header_encryption,
                                 tmp_key, rtp_xtn_hdr_base_key_len);
        if (stat) {
            /* zeroize temp buffer */
            octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
            return srtp_err_status_init_fail;
        }
        debug_print(
            mod_srtp, "extensions cipher key: %s",
            srtp_octet_string_hex_string(tmp_key, rtp_xtn_hdr_base_key_len));

        /*
         * if the cipher in the srtp context uses a salt, then we need
         * to generate the salt value
         */
        if (rtp_xtn_hdr_salt_len > 0) {
            debug_print(mod_srtp,
                        "found rtp_xtn_hdr_salt_len > 0, generating salt",
                        NULL);

            /* generate encryption salt, put after encryption key */
            stat = srtp_kdf_generate(xtn_hdr_kdf, label_rtp_header_salt,
                                     tmp_key + rtp_xtn_hdr_base_key_len,
                                     rtp_xtn_hdr_salt_len);
            if (stat) {
                /* zeroize temp buffer */
                octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
                return srtp_err_status_init_fail;
            }
        }
        if (rtp_xtn_hdr_salt_len > 0) {
            debug_print(
                mod_srtp, "extensions cipher salt: %s",
                srtp_octet_string_hex_string(tmp_key + rtp_xtn_hdr_base_key_len,
                                             rtp_xtn_hdr_salt_len));
        }

        /* initialize extensions header cipher */
        stat = srtp_cipher_init(session_keys->rtp_xtn_hdr_cipher, tmp_key);
        if (stat) {
            /* zeroize temp buffer */
            octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
            return srtp_err_status_init_fail;
        }

        if (xtn_hdr_kdf != &kdf) {
            /* release memory for custom header extension encryption kdf */
            stat = srtp_kdf_clear(xtn_hdr_kdf);
            if (stat) {
                /* zeroize temp buffer */
                octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
                return srtp_err_status_init_fail;
            }
        }
1109 1110
    }

1111 1112 1113
    /* generate authentication key */
    stat = srtp_kdf_generate(&kdf, label_rtp_msg_auth, tmp_key,
                             srtp_auth_get_key_length(session_keys->rtp_auth));
1114
    if (stat) {
1115 1116 1117
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
1118
    }
1119 1120 1121
    debug_print(mod_srtp, "auth key:   %s",
                srtp_octet_string_hex_string(
                    tmp_key, srtp_auth_get_key_length(session_keys->rtp_auth)));
1122

1123 1124 1125
    /* initialize auth function */
    stat = srtp_auth_init(session_keys->rtp_auth, tmp_key);
    if (stat) {
1126
        /* zeroize temp buffer */
1127 1128 1129
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
    }
1130

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    /*
     * ...now initialize SRTCP keys
     */

    rtcp_base_key_len =
        base_key_length(session_keys->rtcp_cipher->type, rtcp_keylen);
    rtcp_salt_len = rtcp_keylen - rtcp_base_key_len;
    debug_print(mod_srtp, "rtcp salt len: %d", rtcp_salt_len);

    /* generate encryption key  */
    stat = srtp_kdf_generate(&kdf, label_rtcp_encryption, tmp_key,
                             rtcp_base_key_len);
Jonathan Lennox's avatar
Jonathan Lennox committed
1143
    if (stat) {
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
    }

    /*
     * if the cipher in the srtp context uses a salt, then we need
     * to generate the salt value
     */
    if (rtcp_salt_len > 0) {
        debug_print(mod_srtp, "found rtcp_salt_len > 0, generating rtcp salt",
                    NULL);

        /* generate encryption salt, put after encryption key */
        stat = srtp_kdf_generate(&kdf, label_rtcp_salt,
                                 tmp_key + rtcp_base_key_len, rtcp_salt_len);
        if (stat) {
            /* zeroize temp buffer */
            octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
            return srtp_err_status_init_fail;
        }
        memcpy(session_keys->c_salt, tmp_key + rtcp_base_key_len,
               SRTP_AEAD_SALT_LEN);
    }
    debug_print(mod_srtp, "rtcp cipher key: %s",
                srtp_octet_string_hex_string(tmp_key, rtcp_base_key_len));
    if (rtcp_salt_len > 0) {
        debug_print(mod_srtp, "rtcp cipher salt: %s",
                    srtp_octet_string_hex_string(tmp_key + rtcp_base_key_len,
                                                 rtcp_salt_len));
    }
Jonathan Lennox's avatar
Jonathan Lennox committed
1175

1176 1177 1178 1179 1180 1181 1182
    /* initialize cipher */
    stat = srtp_cipher_init(session_keys->rtcp_cipher, tmp_key);
    if (stat) {
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
    }
1183

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    /* generate authentication key */
    stat = srtp_kdf_generate(&kdf, label_rtcp_msg_auth, tmp_key,
                             srtp_auth_get_key_length(session_keys->rtcp_auth));
    if (stat) {
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
    }

    debug_print(
        mod_srtp, "rtcp auth key:   %s",
        srtp_octet_string_hex_string(
            tmp_key, srtp_auth_get_key_length(session_keys->rtcp_auth)));

    /* initialize auth function */
    stat = srtp_auth_init(session_keys->rtcp_auth, tmp_key);
    if (stat) {
        /* zeroize temp buffer */
        octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
        return srtp_err_status_init_fail;
    }
1205

1206 1207 1208 1209 1210
    /* clear memory then return */
    stat = srtp_kdf_clear(&kdf);
    octet_string_set_to_zero(tmp_key, MAX_SRTP_KEY_LEN);
    if (stat)
        return srtp_err_status_init_fail;
1211

1212
    return srtp_err_status_ok;
1213
}
Cullen Jennings's avatar
Cullen Jennings committed
1214

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
srtp_err_status_t srtp_stream_init(srtp_stream_ctx_t *srtp,
                                   const srtp_policy_t *p)
{
    srtp_err_status_t err;

    debug_print(mod_srtp, "initializing stream (SSRC: 0x%08x)", p->ssrc.value);

    /* initialize replay database */
    /*
     * window size MUST be at least 64.  MAY be larger.  Values more than
     * 2^15 aren't meaningful due to how extended sequence numbers are
     * calculated.
     * Let a window size of 0 imply the default value.
     */
Cullen Jennings's avatar
Cullen Jennings committed
1229

1230 1231 1232
    if (p->window_size != 0 &&
        (p->window_size < 64 || p->window_size >= 0x8000))
        return srtp_err_status_bad_param;
Cullen Jennings's avatar
Cullen Jennings committed
1233

1234 1235 1236 1237 1238 1239
    if (p->window_size != 0)
        err = srtp_rdbx_init(&srtp->rtp_rdbx, p->window_size);
    else
        err = srtp_rdbx_init(&srtp->rtp_rdbx, 128);
    if (err)
        return err;
1240

1241 1242
    /* set the SSRC value */
    srtp->ssrc = htonl(p->ssrc.value);
1243

1244 1245
    /* reset pending ROC */
    srtp->pending_roc = 0;
Cullen Jennings's avatar
Cullen Jennings committed
1246

1247 1248 1249
    /* set the security service flags */
    srtp->rtp_services = p->rtp.sec_serv;
    srtp->rtcp_services = p->rtcp.sec_serv;
Cullen Jennings's avatar
Cullen Jennings committed
1250

1251 1252 1253 1254 1255 1256
    /*
     * set direction to unknown - this flag gets checked in srtp_protect(),
     * srtp_unprotect(), srtp_protect_rtcp(), and srtp_unprotect_rtcp(), and
     * gets set appropriately if it is set to unknown.
     */
    srtp->direction = dir_unknown;
1257

1258 1259
    /* initialize SRTCP replay database */
    srtp_rdb_init(&srtp->rtcp_rdb);
Cullen Jennings's avatar
Cullen Jennings committed
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    /* initialize allow_repeat_tx */
    /* guard against uninitialized memory: allow only 0 or 1 here */
    if (p->allow_repeat_tx != 0 && p->allow_repeat_tx != 1) {
        srtp_rdbx_dealloc(&srtp->rtp_rdbx);
        return srtp_err_status_bad_param;
    }
    srtp->allow_repeat_tx = p->allow_repeat_tx;

    /* DAM - no RTCP key limit at present */

    /* initialize keys */
    err = srtp_stream_init_all_master_keys(srtp, p->key, p->keys,
                                           p->num_master_keys);
    if (err) {
        srtp_rdbx_dealloc(&srtp->rtp_rdbx);
        return err;
    }

    /*
     * if EKT is in use, then initialize the EKT data associated with
     * the stream
     */
    err = srtp_ekt_stream_init_from_policy(srtp->ekt, p->ekt);
    if (err) {
        srtp_rdbx_dealloc(&srtp->rtp_rdbx);
        return err;
    }
Cullen Jennings's avatar
Cullen Jennings committed
1288

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    return srtp_err_status_ok;
}

/*
 * srtp_event_reporter is an event handler function that merely
 * reports the events that are reported by the callbacks
 */

void srtp_event_reporter(srtp_event_data_t *data)
{
    srtp_err_report(srtp_err_level_warning, "srtp: in stream 0x%x: ",
                    data->ssrc);

    switch (data->event) {
    case event_ssrc_collision:
        srtp_err_report(srtp_err_level_warning, "\tSSRC collision\n");
        break;
    case event_key_soft_limit:
        srtp_err_report(srtp_err_level_warning,
                        "\tkey usage soft limit reached\n");
        break;
    case event_key_hard_limit:
        srtp_err_report(srtp_err_level_warning,
                        "\tkey usage hard limit reached\n");
        break;
    case event_packet_index_limit:
        srtp_err_report(srtp_err_level_warning,
                        "\tpacket index limit reached\n");
        break;
    default:
        srtp_err_report(srtp_err_level_warning,
                        "\tunknown event reported to handler\n");
    }
}

/*
 * srtp_event_handler is a global variable holding a pointer to the
 * event handler function; this function is called for any unexpected
 * event that needs to be handled out of the SRTP data path.  see
 * srtp_event_t in srtp.h for more info
 *
 * it is okay to set srtp_event_handler to NULL, but we set
 * it to the srtp_event_reporter.
 */

static srtp_event_handler_func_t *srtp_event_handler = srtp_event_reporter;

srtp_err_status_t srtp_install_event_handler(srtp_event_handler_func_t func)
{
    /*
     * note that we accept NULL arguments intentionally - calling this
     * function with a NULL arguments removes an event handler that's
     * been previously installed
     */
Cullen Jennings's avatar
Cullen Jennings committed
1343

1344 1345 1346 1347
    /* set global event handling function */
    srtp_event_handler = func;
    return srtp_err_status_ok;
}
1348 1349 1350 1351 1352

/*
 * Check if the given extension header id is / should be encrypted.
 * Returns 1 if yes, otherwise 0.
 */
1353 1354 1355 1356
static int srtp_protect_extension_header(srtp_stream_ctx_t *stream, int id)
{
    int *enc_xtn_hdr = stream->enc_xtn_hdr;
    int count = stream->enc_xtn_hdr_count;
1357

1358 1359
    if (!enc_xtn_hdr || count <= 0) {
        return 0;
1360 1361
    }

1362 1363 1364 1365
    while (count > 0) {
        if (*enc_xtn_hdr == id) {
            return 1;
        }
1366

1367 1368 1369 1370 1371
        enc_xtn_hdr++;
        count--;
    }
    return 0;
}
1372 1373 1374 1375

/*
 * extensions header encryption RFC 6904
 */
1376 1377 1378 1379
static srtp_err_status_t srtp_process_header_encryption(
    srtp_stream_ctx_t *stream,
    srtp_hdr_xtnd_t *xtn_hdr,
    srtp_session_keys_t *session_keys)
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
{
    srtp_err_status_t status;
    uint8_t keystream[257]; /* Maximum 2 bytes header + 255 bytes data. */
    int keystream_pos;
    uint8_t *xtn_hdr_data = ((uint8_t *)xtn_hdr) + octets_in_rtp_extn_hdr;
    uint8_t *xtn_hdr_end =
        xtn_hdr_data + (ntohs(xtn_hdr->length) * sizeof(uint32_t));

    if (ntohs(xtn_hdr->profile_specific) == 0xbede) {
        /* RFC 5285, section 4.2. One-Byte Header */
        while (xtn_hdr_data < xtn_hdr_end) {
            uint8_t xid = (*xtn_hdr_data & 0xf0) >> 4;
            unsigned int xlen = (*xtn_hdr_data & 0x0f) + 1;
            uint32_t xlen_with_header = 1 + xlen;
            xtn_hdr_data++;

            if (xtn_hdr_data + xlen > xtn_hdr_end)
                return srtp_err_status_parse_err;

            if (xid == 15) {
                /* found header 15, stop further processing. */
                break;
            }
1403

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
            status = srtp_cipher_output(session_keys->rtp_xtn_hdr_cipher,
                                        keystream, &xlen_with_header);
            if (status)
                return srtp_err_status_cipher_fail;

            if (srtp_protect_extension_header(stream, xid)) {
                keystream_pos = 1;
                while (xlen > 0) {
                    *xtn_hdr_data ^= keystream[keystream_pos++];
                    xtn_hdr_data++;
                    xlen--;
                }
            } else {
                xtn_hdr_data += xlen;
            }
1419

1420 1421 1422 1423
            /* skip padding bytes. */
            while (xtn_hdr_data < xtn_hdr_end && *xtn_hdr_data == 0) {
                xtn_hdr_data++;
            }
1424
        }
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    } else if ((ntohs(xtn_hdr->profile_specific) & 0x1fff) == 0x100) {
        /* RFC 5285, section 4.3. Two-Byte Header */
        while (xtn_hdr_data + 1 < xtn_hdr_end) {
            uint8_t xid = *xtn_hdr_data;
            unsigned int xlen = *(xtn_hdr_data + 1);
            uint32_t xlen_with_header = 2 + xlen;
            xtn_hdr_data += 2;

            if (xtn_hdr_data + xlen > xtn_hdr_end)
                return srtp_err_status_parse_err;

            status = srtp_cipher_output(session_keys->rtp_xtn_hdr_cipher,
                                        keystream, &xlen_with_header);
            if (status)
                return srtp_err_status_cipher_fail;

            if (xlen > 0 && srtp_protect_extension_header(stream, xid)) {
                keystream_pos = 2;
                while (xlen > 0) {
                    *xtn_hdr_data ^= keystream[keystream_pos++];
                    xtn_hdr_data++;
                    xlen--;
                }
            } else {
                xtn_hdr_data += xlen;
            }
1451

1452 1453 1454 1455
            /* skip padding bytes. */
            while (xtn_hdr_data < xtn_hdr_end && *xtn_hdr_data == 0) {
                xtn_hdr_data++;
            }
1456
        }
1457 1458 1459
    } else {
        /* unsupported extension header format. */
        return srtp_err_status_parse_err;
1460 1461
    }

1462
    return srtp_err_status_ok;
1463 1464
}

1465 1466
/*
 * AEAD uses a new IV formation method.  This function implements
1467 1468
 * section 8.1. (SRTP IV Formation for AES-GCM) of RFC7714.
 * The calculation is defined as, where (+) is the xor operation:
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
 *
 *
 *              0  0  0  0  0  0  0  0  0  0  1  1
 *              0  1  2  3  4  5  6  7  8  9  0  1
 *            +--+--+--+--+--+--+--+--+--+--+--+--+
 *            |00|00|    SSRC   |     ROC   | SEQ |---+
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *                                                    |
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *            |         Encryption Salt           |->(+)
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *                                                    |
 *            +--+--+--+--+--+--+--+--+--+--+--+--+   |
 *            |       Initialization Vector       |<--+
 *            +--+--+--+--+--+--+--+--+--+--+--+--+*
 *
Ryan Hooper's avatar
Ryan Hooper committed
1485
 * Input:  *session_keys - pointer to SRTP stream context session keys,
1486
 *                         used to retrieve the SALT
1487 1488 1489 1490 1491 1492
 *         *iv     - Pointer to receive the calculated IV
 *         *seq    - The ROC and SEQ value to use for the
 *                   IV calculation.
 *         *hdr    - The RTP header, used to get the SSRC value
 *
 */
Ryan Hooper's avatar
Ryan Hooper committed
1493

1494 1495 1496 1497
static void srtp_calc_aead_iv(srtp_session_keys_t *session_keys,
                              v128_t *iv,
                              srtp_xtd_seq_num_t *seq,
                              srtp_hdr_t *hdr)
1498
{
1499 1500
    v128_t in;
    v128_t salt;
1501 1502

#ifdef NO_64BIT_MATH
1503 1504
    uint32_t local_roc = ((high32(*seq) << 16) | (low32(*seq) >> 16));
    uint16_t local_seq = (uint16_t)(low32(*seq));
1505 1506
#else
    uint32_t local_roc = (uint32_t)(*seq >> 16);
1507
    uint16_t local_seq = (uint16_t)*seq;
1508
#endif
1509 1510 1511 1512

    memset(&in, 0, sizeof(v128_t));
    memset(&salt, 0, sizeof(v128_t));

1513 1514 1515
    in.v16[5] = htons(local_seq);
    local_roc = htonl(local_roc);
    memcpy(&in.v16[3], &local_roc, sizeof(local_roc));
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525

    /*
     * Copy in the RTP SSRC value
     */
    memcpy(&in.v8[2], &hdr->ssrc, 4);
    debug_print(mod_srtp, "Pre-salted RTP IV = %s\n", v128_hex_string(&in));

    /*
     * Get the SALT value from the context
     */
Ryan Hooper's avatar
Ryan Hooper committed
1526
    memcpy(salt.v8, session_keys->salt, SRTP_AEAD_SALT_LEN);
1527 1528 1529 1530 1531 1532 1533 1534
    debug_print(mod_srtp, "RTP SALT = %s\n", v128_hex_string(&salt));

    /*
     * Finally, apply tyhe SALT to the input
     */
    v128_xor(iv, &in, &salt);
}

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
srtp_session_keys_t *srtp_get_session_keys(srtp_stream_ctx_t *stream,
                                           uint8_t *hdr,
                                           const unsigned int *pkt_octet_len,
                                           unsigned int *mki_size)
{
    unsigned int base_mki_start_location = *pkt_octet_len;
    unsigned int mki_start_location = 0;
    unsigned int tag_len = 0;
    unsigned int i = 0;

    // Determine the authentication tag size
    if (stream->session_keys[0].rtp_cipher->algorithm == SRTP_AES_GCM_128 ||
        stream->session_keys[0].rtp_cipher->algorithm == SRTP_AES_GCM_256) {
        tag_len = 0;
    } else {
        tag_len = srtp_auth_get_tag_length(stream->session_keys[0].rtp_auth);
    }

    if (tag_len > base_mki_start_location) {
        *mki_size = 0;
        return NULL;
    }

    base_mki_start_location -= tag_len;

    for (i = 0; i < stream->num_master_keys; i++) {
1561 1562
        if (stream->session_keys[i].mki_size != 0 &&
            stream->session_keys[i].mki_size <= base_mki_start_location) {
1563 1564 1565
            *mki_size = stream->session_keys[i].mki_size;
            mki_start_location = base_mki_start_location - *mki_size;

1566 1567
            if (memcmp(hdr + mki_start_location, stream->session_keys[i].mki_id,
                       *mki_size) == 0) {
1568 1569 1570 1571
                return &stream->session_keys[i];
            }
        }
    }
1572

1573 1574
    *mki_size = 0;
    return NULL;
Ryan Hooper's avatar
Ryan Hooper committed
1575 1576
}

1577 1578 1579 1580 1581
static srtp_err_status_t srtp_estimate_index(srtp_rdbx_t *rdbx,
                                             uint32_t roc,
                                             srtp_xtd_seq_num_t *est,
                                             srtp_sequence_number_t seq,
                                             int *delta)
Ulf Olsson's avatar
Ulf Olsson committed
1582 1583
{
#ifdef NO_64BIT_MATH
1584 1585 1586 1587
    uint32_t internal_pkt_idx_reduced;
    uint32_t external_pkt_idx_reduced;
    uint32_t internal_roc;
    uint32_t roc_difference;
Ulf Olsson's avatar
Ulf Olsson committed
1588 1589 1590
#endif

#ifdef NO_64BIT_MATH
1591 1592
    *est = (srtp_xtd_seq_num_t)make64(roc >> 16, (roc << 16) | seq);
    *delta = low32(est) - rdbx->index;
Ulf Olsson's avatar
Ulf Olsson committed
1593
#else
1594 1595
    *est = (srtp_xtd_seq_num_t)(((uint64_t)roc) << 16) | seq;
    *delta = (int)(*est - rdbx->index);
Ulf Olsson's avatar
Ulf Olsson committed
1596 1597
#endif

1598
    if (*est > rdbx->index) {
Ulf Olsson's avatar
Ulf Olsson committed
1599
#ifdef NO_64BIT_MATH
1600 1601 1602 1603 1604 1605
        internal_roc = (uint32_t)(rdbx->index >> 16);
        roc_difference = roc - internal_roc;
        if (roc_difference > 1) {
            *delta = 0;
            return srtp_err_status_pkt_idx_adv;
        }
Ulf Olsson's avatar
Ulf Olsson committed
1606

1607 1608
        internal_pkt_idx_reduced = (uint32_t)(rdbx->index & 0xFFFF);
        external_pkt_idx_reduced = (uint32_t)((roc_difference << 16) | seq);
Ulf Olsson's avatar
Ulf Olsson committed
1609

1610 1611 1612 1613 1614
        if (external_pkt_idx_reduced - internal_pkt_idx_reduced >
            seq_num_median) {
            *delta = 0;
            return srtp_err_status_pkt_idx_adv;
        }
Ulf Olsson's avatar
Ulf Olsson committed
1615
#else
1616 1617 1618 1619
        if (*est -