]> git.sesse.net Git - vlc/blobdiff - libs/srtp/srtp.c
Use var_InheritString for --decklink-video-connection.
[vlc] / libs / srtp / srtp.c
index c9414374a42b63db0a3b605a74fbc02657372355..f2f2c95731d54dde758a89690330cb35b4f181a0 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Secure RTP with libgcrypt
- * Copyright (C) 2007  Rémi Denis-Courmont <rdenis # simphalempin , com>
+ * Copyright (C) 2007  Rémi Denis-Courmont
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  */
 
+/* TODO:
+ * Useless stuff (because nothing depends on it):
+ * - non-nul key derivation rate
+ * - MKI payload
+ */
+
 #ifdef HAVE_CONFIG_H
 # include <config.h>
 #endif
 
 #include <gcrypt.h>
 
-#define debug( ... ) (void)0
+#ifdef WIN32
+# include <winsock2.h>
+#else
+# include <netinet/in.h>
+# include <pthread.h>
+GCRY_THREAD_OPTION_PTHREAD_IMPL;
+#endif
 
-/* TODO:
- * Useful stuff:
- * - ROC profile thingy (multicast really needs this)
- * - replay protection
- *
- * Useless stuff (because nothing depends on it):
- * - non-nul key derivation rate
- * - MKI payload
- */
+#define debug( ... ) (void)0
 
 typedef struct srtp_proto_t
 {
@@ -62,6 +66,7 @@ struct srtp_session_t
     uint32_t rtcp_index;
     uint32_t rtp_roc;
     uint16_t rtp_seq;
+    uint16_t rtp_rcc;
     uint8_t  tag_len;
 };
 
@@ -75,25 +80,23 @@ enum
     SRTCP_SALT
 };
 
-#ifdef WIN32
-# include <winsock2.h>
-#else
-# include <netinet/in.h>
-# include <pthread.h>
-GCRY_THREAD_OPTION_PTHREAD_IMPL;
-#endif
+
+static inline unsigned rcc_mode (const srtp_session_t *s)
+{
+    return (s->flags >> 4) & 3;
+}
 
 static bool libgcrypt_usable = false;
 
 static void initonce_libgcrypt (void)
 {
-    if ((gcry_check_version ("1.1.94") == NULL)
-     || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
-     || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
 #ifndef WIN32
-     || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
+    gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
 #endif
-       )
+
+    if ((gcry_check_version ("1.1.94") == NULL)
+     || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
+     || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0))
         return;
 
     libgcrypt_usable = true;
@@ -103,20 +106,17 @@ static int init_libgcrypt (void)
 {
     int retval;
 #ifndef WIN32
-    static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
     static pthread_once_t once = PTHREAD_ONCE_INIT;
 
-    pthread_mutex_lock (&mutex);
     pthread_once (&once, initonce_libgcrypt);
-    retval = -libgcrypt_usable;
-    pthread_mutex_unlock (&mutex);
 #else
 # warning FIXME: This is not thread-safe.
     if (!libgcrypt_usable)
         initonce_libgcrypt ();
-    retval = -libgcrypt_usable;
 #endif
 
+    retval = libgcrypt_usable ? 0 : -1;
+
     return retval;
 
 }
@@ -160,33 +160,52 @@ static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
  * internal cryptographic counters; it is however of course feasible to open
  * multiple simultaneous sessions with the same master key.
  *
- * @param name cipher-suite name
- * @param kdr key derivation rate
+ * @param encr encryption algorithm number
+ * @param auth authentication algortihm number
+ * @param tag_len authentication tag byte length (NOT including RCC)
  * @param flags OR'ed optional flags.
  *
  * @return NULL in case of error
  */
 srtp_session_t *
-srtp_create (const char *name, unsigned flags, unsigned kdr)
+srtp_create (int encr, int auth, unsigned tag_len, int prf, unsigned flags)
 {
-    assert (name != NULL);
+    if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
+        return NULL;
 
-    if (kdr != 0)
-        return NULL; // FIXME: KDR not implemented yet
+    int cipher, md;
+    switch (encr)
+    {
+        case SRTP_ENCR_NULL:
+            cipher = GCRY_CIPHER_NONE;
+            break;
 
-    uint8_t tag_len;
-    int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
+        case SRTP_ENCR_AES_CM:
+            cipher = GCRY_CIPHER_AES;
+            break;
 
-    if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
-        tag_len = 10;
-    else
-    if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
-        tag_len = 4;
-    else
-    // F8_128_HMAC_SHA1_80 is not implemented
+        default:
+            return NULL;
+    }
+
+    switch (auth)
+    {
+        case SRTP_AUTH_NULL:
+            md = GCRY_MD_NONE;
+            break;
+
+        case SRTP_AUTH_HMAC_SHA1:
+            md = GCRY_MD_SHA1;
+            break;
+
+        default:
+            return NULL;
+    }
+
+    if (tag_len > gcry_md_get_algo_dlen (md))
         return NULL;
 
-    if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
+    if (prf != SRTP_PRF_AES_CM)
         return NULL;
 
     srtp_session_t *s = malloc (sizeof (*s));
@@ -195,8 +214,13 @@ srtp_create (const char *name, unsigned flags, unsigned kdr)
 
     memset (s, 0, sizeof (*s));
     s->flags = flags;
-    s->kdr = kdr;
     s->tag_len = tag_len;
+    s->rtp_rcc = 1; /* Default RCC rate */
+    if (rcc_mode (s))
+    {
+        if (tag_len < 4)
+            goto error;
+    }
 
     if (proto_create (&s->rtp, cipher, md) == 0)
     {
@@ -205,11 +229,43 @@ srtp_create (const char *name, unsigned flags, unsigned kdr)
         proto_destroy (&s->rtp);
     }
 
+error:
     free (s);
     return NULL;
 }
 
 
+/**
+ * Counter Mode encryption/decryption (ctr length = 16 bytes)
+ * with non-padded (truncated) text
+ */
+static int
+ctr_crypt (gcry_cipher_hd_t hd, const void *ctr, uint8_t *data, size_t len)
+{
+    const size_t ctrlen = 16;
+    div_t d = div (len, ctrlen);
+
+    if (gcry_cipher_setctr (hd, ctr, ctrlen)
+     || gcry_cipher_encrypt (hd, data, d.quot * ctrlen, NULL, 0))
+        return -1;
+
+    if (d.rem)
+    {
+        /* Truncated last block */
+        uint8_t dummy[ctrlen];
+        data += d.quot * ctrlen;
+        memcpy (dummy, data, d.rem);
+        memset (dummy + d.rem, 0, ctrlen - d.rem);
+
+        if (gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
+            return -1;
+        memcpy (data, dummy, d.rem);
+    }
+
+    return 0;
+}
+
+
 /**
  * AES-CM key derivation (saltlen = 14 bytes)
  */
@@ -228,29 +284,8 @@ derive (gcry_cipher_hd_t prf, const void *salt,
     for (size_t i = 0; i < rlen; i++)
         iv[sizeof (iv) - rlen + i] ^= r[i];
 
-    /* TODO: retry with CTR mode */
-    while (outlen >= sizeof (iv))
-    {
-        /* AES */
-        if (gcry_cipher_encrypt (prf, out, sizeof (iv), iv, sizeof (iv)))
-            return EINVAL;
-        outlen -= sizeof (iv);
-        out = ((uint8_t *)out) + sizeof (iv);
-
-        /* Increment IV in network byte order */
-        if (++iv[sizeof (iv) - 1] == 0)
-            ++iv[sizeof (iv) -2];
-    }
-
-    if (outlen > 0)
-    {
-        /* Truncated last AES output block */
-        if (gcry_cipher_encrypt (prf, iv, sizeof (iv), NULL, 0))
-            return -1;
-        memcpy (out, iv, outlen);
-    }
-
-    return 0;
+    memset (out, 0, outlen);
+    return ctr_crypt (prf, iv, out, outlen);
 }
 
 
@@ -286,11 +321,11 @@ srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
     gcry_cipher_hd_t prf;
     uint8_t r[6];
 
-    /* TODO: retry with CTR mode */
-    if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_ECB, 0)
+    if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, 0)
      || gcry_cipher_setkey (prf, key, keylen))
         return -1;
 
+#if 0
     /* RTP key derivation */
     if (s->kdr != 0)
     {
@@ -304,6 +339,7 @@ srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
         }
     }
     else
+#endif
         memset (r, 0, sizeof (r));
 
     if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
@@ -336,37 +372,78 @@ srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
     return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
 }
 
+static int hexdigit (char c)
+{
+    if ((c >= '0') && (c <= '9'))
+        return c - '0';
+    if ((c >= 'A') && (c <= 'F'))
+        return c - 'A' + 0xA;
+    if ((c >= 'a') && (c <= 'f'))
+        return c - 'a' + 0xa;
+    return -1;
+}
 
-/** AES-CM encryption/decryption (ctr length = 16 bytes) */
-static int
-ctr_crypt (gcry_cipher_hd_t hd, uint32_t *ctr, uint8_t *data, size_t len)
+static ssize_t hexstring (const char *in, uint8_t *out, size_t outlen)
 {
-    const size_t ctrlen = 16;
-    while (len >= ctrlen)
-    {
-        if (gcry_cipher_setctr (hd, ctr, ctrlen)
-         || gcry_cipher_encrypt (hd, data, ctrlen, NULL, 0))
-            return -1;
+    size_t inlen = strlen (in);
 
-        data += ctrlen;
-        len -= ctrlen;
-        ctr[3] = htonl (ntohl (ctr[3]) + 1);
-    }
+    if ((inlen > (2 * outlen)) || (inlen & 1))
+        return -1;
 
-    if (len > 0)
+    for (size_t i = 0; i < inlen; i += 2)
     {
-        /* Truncated last block */
-        uint8_t dummy[ctrlen];
-        memcpy (dummy, data, len);
-        memset (dummy + len, 0, ctrlen - len);
-
-        if (gcry_cipher_setctr (hd, ctr, ctrlen)
-         || gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
+        int a = hexdigit (in[i]), b = hexdigit (in[i + 1]);
+        if ((a == -1) || (b == -1))
             return -1;
-        memcpy (data, dummy, len);
+        out[i / 2] = (a << 4) | b;
     }
+    return inlen / 2;
+}
 
-    return 0;
+/**
+ * Sets (or resets) the master key and master salt for a SRTP session
+ * from hexadecimal strings. See also srtp_setkey().
+ *
+ * @return 0 on success, in case of error:
+ *  EINVAL  invalid or unsupported key/salt sizes combination
+ */
+int
+srtp_setkeystring (srtp_session_t *s, const char *key, const char *salt)
+{
+    uint8_t bkey[16]; /* TODO/NOTE: hard-coded for AES */
+    uint8_t bsalt[14]; /* TODO/NOTE: hard-coded for the PRF-AES-CM */
+    ssize_t bkeylen = hexstring (key, bkey, sizeof (bkey));
+    ssize_t bsaltlen = hexstring (salt, bsalt, sizeof (bsalt));
+
+    if ((bkeylen == -1) || (bsaltlen == -1))
+        return EINVAL;
+    return srtp_setkey (s, bkey, bkeylen, bsalt, bsaltlen) ? EINVAL : 0;
+}
+
+/**
+ * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
+ * specified (through this function), the default rate of ONE is assumed
+ * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
+ * of the RCC mode has been selected.
+ *
+ * The RCC mode is selected through one of these flags for srtp_create():
+ *  SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
+ *  SRTP_RCC_MODE2: integrity protection for all packets
+ *  SRTP_RCC_MODE3: no integrity protection
+ *
+ * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
+ * (through encryption) but is much more prone to DoS. It can only be used if
+ * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
+ * or trusted routers and proper source address filtering).
+ *
+ * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
+ *
+ * @param rate RoC Carry rate (MUST NOT be zero)
+ */
+void srtp_setrcc_rate (srtp_session_t *s, uint16_t rate)
+{
+    assert (rate != 0);
+    s->rtp_rcc = rate;
 }
 
 
@@ -418,14 +495,14 @@ static inline uint16_t rtp_seq (const uint8_t *buf)
 
 /** Message Authentication and Integrity for RTP */
 static const uint8_t *
-rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len)
+rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len,
+            uint32_t roc)
 {
     const gcry_md_hd_t md = s->rtp.mac;
-    uint32_t roc = htonl (srtp_compute_roc (s, rtp_seq (data)));
 
     gcry_md_reset (md);
     gcry_md_write (md, data, len);
-    gcry_md_write (md, &roc, 4);
+    gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
     return gcry_md_read (md, 0);
 }
 
@@ -440,6 +517,7 @@ rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len)
  *
  * @return 0 on success, in case of error:
  *  EINVAL  malformatted RTP packet
+ *  EACCES  replayed packet or out-of-window or sync lost
  */
 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
 {
@@ -473,11 +551,22 @@ static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
     memcpy (&ssrc, buf + 8, 4);
 
     /* Updates ROC and sequence (it's safe now) */
-    if (roc > s->rtp_roc)
+    int16_t diff = seq - s->rtp_seq;
+    if (diff > 0)
+    {
+        /* Sequence in the future, good */
+        s->rtp.window = s->rtp.window << diff;
+        s->rtp.window |= 1;
         s->rtp_seq = seq, s->rtp_roc = roc;
+    }
     else
-    if (seq > s->rtp_seq)
-        s->rtp_seq = seq;
+    {
+        /* Sequence in the past/present, bad */
+        diff = -diff;
+        if ((diff >= 64) || ((s->rtp.window >> diff) & 1))
+            return EACCES; /* Replay attack */
+        s->rtp.window |= 1 << diff;
+    }
 
     /* Encrypt/Decrypt */
     if (s->flags & SRTP_UNENCRYPTED)
@@ -498,29 +587,55 @@ static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
  *
  * @param buf RTP packet to be encrypted/digested
  * @param lenp pointer to the RTP packet length on entry,
- *             set to the SRTP length on exit (undefined in case of error)
+ *             set to the SRTP length on exit (undefined on non-ENOSPC error)
  * @param bufsize size (bytes) of the packet buffer
  *
  * @return 0 on success, in case of error:
  *  EINVAL  malformatted RTP packet or internal error
- *  ENOSPC  bufsize is too small (to add authentication tag)
+ *  ENOSPC  bufsize is too small to add authentication tag
+ *          (<lenp> will hold the required byte size)
+ *  EACCES  packet would trigger a replay error on receiver
  */
 int
 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
 {
     size_t len = *lenp;
+    size_t tag_len = s->tag_len;
+
+    if (!(s->flags & SRTP_UNAUTHENTICATED))
+    {
+        *lenp = len + tag_len;
+        if (bufsize < (len + tag_len))
+            return ENOSPC;
+    }
+
     int val = srtp_crypt (s, buf, len);
     if (val)
         return val;
 
     if (!(s->flags & SRTP_UNAUTHENTICATED))
     {
-        if (bufsize < (len + s->tag_len))
-            return ENOSPC;
-
-        const uint8_t *tag = rtp_digest (s, buf, len);
-        memcpy (buf + len, tag, s->tag_len);
-        *lenp = len + s->tag_len;
+        uint32_t roc = srtp_compute_roc (s, rtp_seq (buf));
+        const uint8_t *tag = rtp_digest (s, buf, len, roc);
+        if (rcc_mode (s))
+        {
+            assert (s->rtp_rcc);
+            if ((rtp_seq (buf) % s->rtp_rcc) == 0)
+            {
+                memcpy (buf + len, &(uint32_t){ htonl (s->rtp_roc) }, 4);
+                len += 4;
+                if (rcc_mode (s) == 3)
+                    tag_len = 0;
+                else
+                    tag_len -= 4;
+            }
+            else
+            {
+                if (rcc_mode (s) & 1)
+                    tag_len = 0;
+            }
+        }
+        memcpy (buf + len, tag, tag_len);
     }
 
     return 0;
@@ -543,18 +658,62 @@ int
 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
 {
     size_t len = *lenp;
-    /* FIXME: anti-replay */
+    if (len < 12u)
+        return EINVAL;
 
     if (!(s->flags & SRTP_UNAUTHENTICATED))
     {
-        if (len < (12u + s->tag_len))
+        size_t tag_len = s->tag_len, roc_len = 0;
+        if (rcc_mode (s))
+        {
+            if ((rtp_seq (buf) % s->rtp_rcc) == 0)
+            {
+                roc_len = 4;
+                if (rcc_mode (s) == 3)
+                    tag_len = 0;
+                else
+                    tag_len -= 4;
+            }
+            else
+            {
+                if (rcc_mode (s) & 1)
+                    tag_len = 0; // RCC mode 1 or 3: no auth
+            }
+        }
+
+        if (len < (12u + roc_len + tag_len))
             return EINVAL;
-        len -= s->tag_len;
+        len -= roc_len + tag_len;
 
-        const uint8_t *tag = rtp_digest (s, buf, len);
-        if (memcmp (buf + len, tag, s->tag_len))
+        uint32_t roc = srtp_compute_roc (s, rtp_seq (buf)), rcc;
+        if (roc_len)
+        {
+            assert (roc_len == 4);
+            memcpy (&rcc, buf + len, 4);
+            rcc = ntohl (rcc);
+        }
+        else
+            rcc = roc;
+
+        const uint8_t *tag = rtp_digest (s, buf, len, rcc);
+#if 0
+        printf ("Computed: 0x");
+        for (unsigned i = 0; i < tag_len; i++)
+            printf ("%02x", tag[i]);
+        printf ("\nReceived: 0x");
+        for (unsigned i = 0; i < tag_len; i++)
+            printf ("%02x", buf[len + roc_len + i]);
+        puts ("");
+#endif
+        if (memcmp (buf + len + roc_len, tag, tag_len))
             return EACCES;
 
+        if (roc_len)
+        {
+            /* Authenticated packet carried a Roll-Over-Counter */
+            s->rtp_roc += rcc - roc;
+            assert (srtp_compute_roc (s, rtp_seq (buf)) == rcc);
+        }
         *lenp = len;
     }
 
@@ -600,10 +759,33 @@ static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
     if ((len < 12) || ((buf[0] >> 6) != 2))
         return EINVAL;
 
-    uint32_t index = s->rtcp_index++;
-    if (index == 0x7fffffff)
-        s->rtcp_index = 0; /* 31-bit wrap */
+    uint32_t index;
+    memcpy (&index, buf + len, 4);
+    index = ntohl (index);
+    if (((index >> 31) != 0) != ((s->flags & SRTCP_UNENCRYPTED) == 0))
+        return EINVAL; // E-bit mismatch
+
+    index &= ~(1 << 31); // clear E-bit for counter
 
+    /* Updates SRTCP index (safe here) */
+    int32_t diff = index - s->rtcp_index;
+    if (diff > 0)
+    {
+        /* Packet in the future, good */
+        s->rtcp.window = s->rtcp.window << diff;
+        s->rtcp.window |= 1;
+        s->rtcp_index = index;
+    }
+    else
+    {
+        /* Packet in the past/present, bad */
+        diff = -diff;
+        if ((diff >= 64) || ((s->rtcp.window >> diff) & 1))
+            return EACCES; // replay attack!
+        s->rtp.window |= 1 << diff;
+    }
+
+    /* Crypts SRTCP */
     if (s->flags & SRTCP_UNENCRYPTED)
         return 0;
 
@@ -637,7 +819,10 @@ srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
     if (bufsize < (len + 4 + s->tag_len))
         return ENOSPC;
 
-    uint32_t index = s->rtcp_index;
+    uint32_t index = ++s->rtcp_index;
+    if (index >> 31)
+        s->rtcp_index = index = 0; /* 31-bit wrap */
+
     if ((s->flags & SRTCP_UNENCRYPTED) == 0)
         index |= 0x80000000; /* Set Encrypted bit */
     memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
@@ -646,12 +831,11 @@ srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
     if (val)
         return val;
 
-    len += 4; /* Digest SRTCP index too */
+    len += 4; /* Digests SRTCP index too */
 
     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
     memcpy (buf + len, tag, s->tag_len);
     *lenp = len + s->tag_len;
-    s->rtcp_index++; /* Update index */
     return 0;
 }
 
@@ -672,7 +856,6 @@ int
 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
 {
     size_t len = *lenp;
-    /* FIXME: anti-replay ?? */
 
     if (len < (4u + s->tag_len))
         return EINVAL;
@@ -683,12 +866,6 @@ srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
          return EACCES;
 
     len -= 4; /* Remove SRTCP index before decryption */
-    uint32_t index;
-    memcpy (&index, buf + len, 4);
-    index = ntohl (index);
-    if (((index - s->rtcp_index) & 0xffffffff) < 0x80000000)
-        s->rtcp_index = index; /* Update index */
-
     *lenp = len;
     return srtp_crypt (s, buf, len);
 }