2 * Secure RTP with libgcrypt
3 * Copyright (C) 2007 RĂ©mi Denis-Courmont <rdenis # simphalempin , com>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 * Useless stuff (because nothing depends on it):
22 * - non-nul key derivation rate
43 # include <winsock2.h>
45 # include <netinet/in.h>
47 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
50 #define debug( ... ) (void)0
52 typedef struct srtp_proto_t
54 gcry_cipher_hd_t cipher
;
84 static inline unsigned rcc_mode (const srtp_session_t
*s
)
86 return (s
->flags
>> 4) & 3;
89 static bool libgcrypt_usable
= false;
91 static void initonce_libgcrypt (void)
94 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
97 if ((gcry_check_version ("1.1.94") == NULL
)
98 || gcry_control (GCRYCTL_DISABLE_SECMEM
, 0)
99 || gcry_control (GCRYCTL_INITIALIZATION_FINISHED
, 0))
102 libgcrypt_usable
= true;
105 static int init_libgcrypt (void)
109 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
111 pthread_once (&once
, initonce_libgcrypt
);
113 # warning FIXME: This is not thread-safe.
114 if (!libgcrypt_usable
)
115 initonce_libgcrypt ();
118 retval
= libgcrypt_usable
? 0 : -1;
125 static void proto_destroy (srtp_proto_t
*p
)
127 gcry_md_close (p
->mac
);
128 gcry_cipher_close (p
->cipher
);
133 * Releases all resources associated with a Secure RTP session.
135 void srtp_destroy (srtp_session_t
*s
)
139 proto_destroy (&s
->rtcp
);
140 proto_destroy (&s
->rtp
);
145 static int proto_create (srtp_proto_t
*p
, int gcipher
, int gmd
)
147 if (gcry_cipher_open (&p
->cipher
, gcipher
, GCRY_CIPHER_MODE_CTR
, 0) == 0)
149 if (gcry_md_open (&p
->mac
, gmd
, GCRY_MD_FLAG_HMAC
) == 0)
151 gcry_cipher_close (p
->cipher
);
158 * Allocates a Secure RTP one-way session.
159 * The same session cannot be used both ways because this would confuse
160 * internal cryptographic counters; it is however of course feasible to open
161 * multiple simultaneous sessions with the same master key.
163 * @param encr encryption algorithm number
164 * @param auth authentication algortihm number
165 * @param tag_len authentication tag byte length (NOT including RCC)
166 * @param flags OR'ed optional flags.
168 * @return NULL in case of error
171 srtp_create (int encr
, int auth
, unsigned tag_len
, int prf
, unsigned flags
)
173 if ((flags
& ~SRTP_FLAGS_MASK
) || init_libgcrypt ())
180 cipher
= GCRY_CIPHER_NONE
;
183 case SRTP_ENCR_AES_CM
:
184 cipher
= GCRY_CIPHER_AES
;
197 case SRTP_AUTH_HMAC_SHA1
:
205 if (tag_len
> gcry_md_get_algo_dlen (md
))
208 if (prf
!= SRTP_PRF_AES_CM
)
211 srtp_session_t
*s
= malloc (sizeof (*s
));
215 memset (s
, 0, sizeof (*s
));
217 s
->tag_len
= tag_len
;
218 s
->rtp_rcc
= 1; /* Default RCC rate */
225 if (proto_create (&s
->rtp
, cipher
, md
) == 0)
227 if (proto_create (&s
->rtcp
, cipher
, md
) == 0)
229 proto_destroy (&s
->rtp
);
239 * Counter Mode encryption/decryption (ctr length = 16 bytes)
240 * with non-padded (truncated) text
243 ctr_crypt (gcry_cipher_hd_t hd
, const void *ctr
, uint8_t *data
, size_t len
)
245 const size_t ctrlen
= 16;
246 div_t d
= div (len
, ctrlen
);
248 if (gcry_cipher_setctr (hd
, ctr
, ctrlen
)
249 || gcry_cipher_encrypt (hd
, data
, d
.quot
* ctrlen
, NULL
, 0))
254 /* Truncated last block */
255 uint8_t dummy
[ctrlen
];
256 data
+= d
.quot
* ctrlen
;
257 memcpy (dummy
, data
, d
.rem
);
258 memset (dummy
+ d
.rem
, 0, ctrlen
- d
.rem
);
260 if (gcry_cipher_encrypt (hd
, dummy
, ctrlen
, data
, ctrlen
))
262 memcpy (data
, dummy
, d
.rem
);
270 * AES-CM key derivation (saltlen = 14 bytes)
273 derive (gcry_cipher_hd_t prf
, const void *salt
,
274 const uint8_t *r
, size_t rlen
, uint8_t label
,
275 void *out
, size_t outlen
)
279 memcpy (iv
, salt
, 14);
283 iv
[13 - rlen
] ^= label
;
284 for (size_t i
= 0; i
< rlen
; i
++)
285 iv
[sizeof (iv
) - rlen
+ i
] ^= r
[i
];
287 memset (out
, 0, outlen
);
288 return ctr_crypt (prf
, iv
, out
, outlen
);
293 proto_derive (srtp_proto_t
*p
, gcry_cipher_hd_t prf
,
294 const void *salt
, size_t saltlen
,
295 const uint8_t *r
, size_t rlen
, bool rtcp
)
301 uint8_t label
= rtcp
? SRTCP_CRYPT
: SRTP_CRYPT
;
303 if (derive (prf
, salt
, r
, rlen
, label
++, keybuf
, 16)
304 || gcry_cipher_setkey (p
->cipher
, keybuf
, 16)
305 || derive (prf
, salt
, r
, rlen
, label
++, keybuf
, 20)
306 || gcry_md_setkey (p
->mac
, keybuf
, 20)
307 || derive (prf
, salt
, r
, rlen
, label
, p
->salt
, 14))
315 * SRTP/SRTCP cipher/salt/MAC keys derivation.
318 srtp_derive (srtp_session_t
*s
, const void *key
, size_t keylen
,
319 const void *salt
, size_t saltlen
)
321 gcry_cipher_hd_t prf
;
324 if (gcry_cipher_open (&prf
, GCRY_CIPHER_AES
, GCRY_CIPHER_MODE_CTR
, 0)
325 || gcry_cipher_setkey (prf
, key
, keylen
))
329 /* RTP key derivation */
332 uint64_t index
= (((uint64_t)s
->rtp_roc
) << 16) | s
->rtp_seq
;
335 for (int i
= sizeof (r
) - 1; i
>= 0; i
--)
343 memset (r
, 0, sizeof (r
));
345 if (proto_derive (&s
->rtp
, prf
, salt
, saltlen
, r
, 6, false))
348 /* RTCP key derivation */
349 memcpy (r
, &(uint32_t){ htonl (s
->rtcp_index
) }, 4);
350 if (proto_derive (&s
->rtcp
, prf
, salt
, saltlen
, r
, 4, true))
353 (void)gcry_cipher_close (prf
);
359 * Sets (or resets) the master key and master salt for a SRTP session.
360 * This must be done at least once before using rtp_send(), rtp_recv(),
361 * rtcp_send() or rtcp_recv(). Also, rekeying is required every
362 * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
363 * otherwise the protocol security might be broken.
365 * @return 0 on success, in case of error:
366 * EINVAL invalid or unsupported key/salt sizes combination
369 srtp_setkey (srtp_session_t
*s
, const void *key
, size_t keylen
,
370 const void *salt
, size_t saltlen
)
372 return srtp_derive (s
, key
, keylen
, salt
, saltlen
) ? EINVAL
: 0;
375 static int hexdigit (char c
)
377 if ((c
>= '0') && (c
<= '9'))
379 if ((c
>= 'A') && (c
<= 'F'))
380 return c
- 'A' + 0xA;
381 if ((c
>= 'a') && (c
<= 'f'))
382 return c
- 'a' + 0xa;
386 static ssize_t
hexstring (const char *in
, uint8_t *out
, size_t outlen
)
388 size_t inlen
= strlen (in
);
390 if ((inlen
> (2 * outlen
)) || (inlen
& 1))
393 for (size_t i
= 0; i
< inlen
; i
+= 2)
395 int a
= hexdigit (in
[i
]), b
= hexdigit (in
[i
+ 1]);
396 if ((a
== -1) || (b
== -1))
398 out
[i
/ 2] = (a
<< 4) | b
;
404 * Sets (or resets) the master key and master salt for a SRTP session
405 * from hexadecimal strings. See also srtp_setkey().
407 * @return 0 on success, in case of error:
408 * EINVAL invalid or unsupported key/salt sizes combination
411 srtp_setkeystring (srtp_session_t
*s
, const char *key
, const char *salt
)
413 uint8_t bkey
[16]; /* TODO/NOTE: hard-coded for AES */
414 uint8_t bsalt
[14]; /* TODO/NOTE: hard-coded for the PRF-AES-CM */
415 ssize_t bkeylen
= hexstring (key
, bkey
, sizeof (bkey
));
416 ssize_t bsaltlen
= hexstring (salt
, bsalt
, sizeof (bsalt
));
418 if ((bkeylen
== -1) || (bsaltlen
== -1))
420 return srtp_setkey (s
, bkey
, bkeylen
, bsalt
, bsaltlen
) ? EINVAL
: 0;
424 * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
425 * specified (through this function), the default rate of ONE is assumed
426 * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
427 * of the RCC mode has been selected.
429 * The RCC mode is selected through one of these flags for srtp_create():
430 * SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
431 * SRTP_RCC_MODE2: integrity protection for all packets
432 * SRTP_RCC_MODE3: no integrity protection
434 * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
435 * (through encryption) but is much more prone to DoS. It can only be used if
436 * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
437 * or trusted routers and proper source address filtering).
439 * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
441 * @param rate RoC Carry rate (MUST NOT be zero)
443 void srtp_setrcc_rate (srtp_session_t
*s
, uint16_t rate
)
450 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
452 rtp_crypt (gcry_cipher_hd_t hd
, uint32_t ssrc
, uint32_t roc
, uint16_t seq
,
453 const uint32_t *salt
, uint8_t *data
, size_t len
)
455 /* Determines cryptographic counter (IV) */
457 counter
[0] = salt
[0];
458 counter
[1] = salt
[1] ^ ssrc
;
459 counter
[2] = salt
[2] ^ htonl (roc
);
460 counter
[3] = salt
[3] ^ htonl (seq
<< 16);
463 return ctr_crypt (hd
, counter
, data
, len
);
467 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
469 srtp_compute_roc (const srtp_session_t
*s
, uint16_t seq
)
471 uint32_t roc
= s
->rtp_roc
;
473 if (((seq
- s
->rtp_seq
) & 0xffff) < 0x8000)
475 /* Sequence is ahead, good */
476 if (seq
< s
->rtp_seq
)
477 roc
++; /* Sequence number wrap */
481 /* Sequence is late, bad */
482 if (seq
> s
->rtp_seq
)
483 roc
--; /* Wrap back */
489 /** Returns RTP sequence (in host-byte order) */
490 static inline uint16_t rtp_seq (const uint8_t *buf
)
492 return (buf
[2] << 8) | buf
[3];
496 /** Message Authentication and Integrity for RTP */
497 static const uint8_t *
498 rtp_digest (srtp_session_t
*s
, const uint8_t *data
, size_t len
,
501 const gcry_md_hd_t md
= s
->rtp
.mac
;
504 gcry_md_write (md
, data
, len
);
505 gcry_md_write (md
, &(uint32_t){ htonl (roc
) }, 4);
506 return gcry_md_read (md
, 0);
511 * Encrypts/decrypts a RTP packet and updates SRTP context
512 * (CTR block cypher mode of operation has identical encryption and
513 * decryption function).
515 * @param buf RTP packet to be en-/decrypted
516 * @param len RTP packet length
518 * @return 0 on success, in case of error:
519 * EINVAL malformatted RTP packet
520 * EACCES replayed packet or out-of-window or sync lost
522 static int srtp_crypt (srtp_session_t
*s
, uint8_t *buf
, size_t len
)
526 if ((len
< 12) || ((buf
[0] >> 6) != 2))
529 /* Computes encryption offset */
530 uint16_t offset
= 12;
531 offset
+= (buf
[0] & 0xf) * 4; // skips CSRC
541 memcpy (&extlen
, buf
+ offset
- 2, 2);
542 offset
+= htons (extlen
); // skips RTP extension header
548 /* Determines RTP 48-bits counter and SSRC */
549 uint16_t seq
= rtp_seq (buf
);
550 uint32_t roc
= srtp_compute_roc (s
, seq
), ssrc
;
551 memcpy (&ssrc
, buf
+ 8, 4);
553 /* Updates ROC and sequence (it's safe now) */
554 int16_t diff
= seq
- s
->rtp_seq
;
557 /* Sequence in the future, good */
558 s
->rtp
.window
= s
->rtp
.window
<< diff
;
560 s
->rtp_seq
= seq
, s
->rtp_roc
= roc
;
564 /* Sequence in the past/present, bad */
566 if ((diff
>= 64) || ((s
->rtp
.window
>> diff
) & 1))
567 return EACCES
; /* Replay attack */
568 s
->rtp
.window
|= 1 << diff
;
571 /* Encrypt/Decrypt */
572 if (s
->flags
& SRTP_UNENCRYPTED
)
575 if (rtp_crypt (s
->rtp
.cipher
, ssrc
, roc
, seq
, s
->rtp
.salt
,
576 buf
+ offset
, len
- offset
))
584 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
585 * the authentication tag and appends it.
586 * Note that you can encrypt packet in disorder.
588 * @param buf RTP packet to be encrypted/digested
589 * @param lenp pointer to the RTP packet length on entry,
590 * set to the SRTP length on exit (undefined on non-ENOSPC error)
591 * @param bufsize size (bytes) of the packet buffer
593 * @return 0 on success, in case of error:
594 * EINVAL malformatted RTP packet or internal error
595 * ENOSPC bufsize is too small to add authentication tag
596 * (<lenp> will hold the required byte size)
597 * EACCES packet would trigger a replay error on receiver
600 srtp_send (srtp_session_t
*s
, uint8_t *buf
, size_t *lenp
, size_t bufsize
)
603 size_t tag_len
= s
->tag_len
;
605 if (!(s
->flags
& SRTP_UNAUTHENTICATED
))
607 *lenp
= len
+ tag_len
;
608 if (bufsize
< (len
+ tag_len
))
612 int val
= srtp_crypt (s
, buf
, len
);
616 if (!(s
->flags
& SRTP_UNAUTHENTICATED
))
618 uint32_t roc
= srtp_compute_roc (s
, rtp_seq (buf
));
619 const uint8_t *tag
= rtp_digest (s
, buf
, len
, roc
);
623 if ((rtp_seq (buf
) % s
->rtp_rcc
) == 0)
625 memcpy (buf
+ len
, &(uint32_t){ htonl (s
->rtp_roc
) }, 4);
627 if (rcc_mode (s
) == 3)
634 if (rcc_mode (s
) & 1)
638 memcpy (buf
+ len
, tag
, tag_len
);
646 * Turns a SRTP packet into a RTP packet: authenticates the packet,
649 * @param buf RTP packet to be digested/decrypted
650 * @param lenp pointer to the SRTP packet length on entry,
651 * set to the RTP length on exit (undefined in case of error)
653 * @return 0 on success, in case of error:
654 * EINVAL malformatted SRTP packet
655 * EACCES authentication failed (spoofed packet or out-of-sync)
658 srtp_recv (srtp_session_t
*s
, uint8_t *buf
, size_t *lenp
)
664 if (!(s
->flags
& SRTP_UNAUTHENTICATED
))
666 size_t tag_len
= s
->tag_len
, roc_len
= 0;
669 if ((rtp_seq (buf
) % s
->rtp_rcc
) == 0)
672 if (rcc_mode (s
) == 3)
679 if (rcc_mode (s
) & 1)
680 tag_len
= 0; // RCC mode 1 or 3: no auth
684 if (len
< (12u + roc_len
+ tag_len
))
686 len
-= roc_len
+ tag_len
;
688 uint32_t roc
= srtp_compute_roc (s
, rtp_seq (buf
)), rcc
;
691 assert (roc_len
== 4);
692 memcpy (&rcc
, buf
+ len
, 4);
698 const uint8_t *tag
= rtp_digest (s
, buf
, len
, rcc
);
700 printf ("Computed: 0x");
701 for (unsigned i
= 0; i
< tag_len
; i
++)
702 printf ("%02x", tag
[i
]);
703 printf ("\nReceived: 0x");
704 for (unsigned i
= 0; i
< tag_len
; i
++)
705 printf ("%02x", buf
[len
+ roc_len
+ i
]);
708 if (memcmp (buf
+ len
+ roc_len
, tag
, tag_len
))
713 /* Authenticated packet carried a Roll-Over-Counter */
714 s
->rtp_roc
+= rcc
- roc
;
715 assert (srtp_compute_roc (s
, rtp_seq (buf
)) == rcc
);
720 return srtp_crypt (s
, buf
, len
);
724 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
726 rtcp_crypt (gcry_cipher_hd_t hd
, uint32_t ssrc
, uint32_t index
,
727 const uint32_t *salt
, uint8_t *data
, size_t len
)
729 return rtp_crypt (hd
, ssrc
, index
>> 16, index
& 0xffff, salt
, data
, len
);
733 /** Message Authentication and Integrity for RTCP */
734 static const uint8_t *
735 rtcp_digest (gcry_md_hd_t md
, const void *data
, size_t len
)
738 gcry_md_write (md
, data
, len
);
739 return gcry_md_read (md
, 0);
744 * Encrypts/decrypts a RTCP packet and updates SRTCP context
745 * (CTR block cypher mode of operation has identical encryption and
746 * decryption function).
748 * @param buf RTCP packet to be en-/decrypted
749 * @param len RTCP packet length
751 * @return 0 on success, in case of error:
752 * EINVAL malformatted RTCP packet
754 static int srtcp_crypt (srtp_session_t
*s
, uint8_t *buf
, size_t len
)
758 /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
759 if ((len
< 12) || ((buf
[0] >> 6) != 2))
763 memcpy (&index
, buf
+ len
, 4);
764 index
= ntohl (index
);
765 if (((index
>> 31) != 0) != ((s
->flags
& SRTCP_UNENCRYPTED
) == 0))
766 return EINVAL
; // E-bit mismatch
768 index
&= ~(1 << 31); // clear E-bit for counter
770 /* Updates SRTCP index (safe here) */
771 int32_t diff
= index
- s
->rtcp_index
;
774 /* Packet in the future, good */
775 s
->rtcp
.window
= s
->rtcp
.window
<< diff
;
777 s
->rtcp_index
= index
;
781 /* Packet in the past/present, bad */
783 if ((diff
>= 64) || ((s
->rtcp
.window
>> diff
) & 1))
784 return EACCES
; // replay attack!
785 s
->rtp
.window
|= 1 << diff
;
789 if (s
->flags
& SRTCP_UNENCRYPTED
)
793 memcpy (&ssrc
, buf
+ 4, 4);
795 if (rtcp_crypt (s
->rtcp
.cipher
, ssrc
, index
, s
->rtp
.salt
,
803 * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
804 * the authentication tag and appends it.
806 * @param buf RTCP packet to be encrypted/digested
807 * @param lenp pointer to the RTCP packet length on entry,
808 * set to the SRTCP length on exit (undefined in case of error)
809 * @param bufsize size (bytes) of the packet buffer
811 * @return 0 on success, in case of error:
812 * EINVAL malformatted RTCP packet or internal error
813 * ENOSPC bufsize is too small (to add index and authentication tag)
816 srtcp_send (srtp_session_t
*s
, uint8_t *buf
, size_t *lenp
, size_t bufsize
)
819 if (bufsize
< (len
+ 4 + s
->tag_len
))
822 uint32_t index
= ++s
->rtcp_index
;
824 s
->rtcp_index
= index
= 0; /* 31-bit wrap */
826 if ((s
->flags
& SRTCP_UNENCRYPTED
) == 0)
827 index
|= 0x80000000; /* Set Encrypted bit */
828 memcpy (buf
+ len
, &(uint32_t){ htonl (index
) }, 4);
830 int val
= srtcp_crypt (s
, buf
, len
);
834 len
+= 4; /* Digests SRTCP index too */
836 const uint8_t *tag
= rtcp_digest (s
->rtp
.mac
, buf
, len
);
837 memcpy (buf
+ len
, tag
, s
->tag_len
);
838 *lenp
= len
+ s
->tag_len
;
844 * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
847 * @param buf RTCP packet to be digested/decrypted
848 * @param lenp pointer to the SRTCP packet length on entry,
849 * set to the RTCP length on exit (undefined in case of error)
851 * @return 0 on success, in case of error:
852 * EINVAL malformatted SRTCP packet
853 * EACCES authentication failed (spoofed packet or out-of-sync)
856 srtcp_recv (srtp_session_t
*s
, uint8_t *buf
, size_t *lenp
)
860 if (len
< (4u + s
->tag_len
))
864 const uint8_t *tag
= rtcp_digest (s
->rtp
.mac
, buf
, len
);
865 if (memcmp (buf
+ len
, tag
, s
->tag_len
))
868 len
-= 4; /* Remove SRTCP index before decryption */
870 return srtp_crypt (s
, buf
, len
);