Commit baa0ceac authored by jan.koester's avatar jan.koester
Browse files

crypto: SRTP/SRTCP (RFC 3711, AES_CM_128_HMAC_SHA1_80) with RFC and libsrtp vectors

parent 3abe1aaa
Loading
Loading
Loading
Loading
+2 −0
Changes for src/CMakeLists.txt: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -18,6 +18,7 @@ list(APPEND netplussrc
    crypto/rsa_pkcs1_sha384.cpp
    crypto/ecdsa_verify.cpp
    crypto/curve25519.cpp
    crypto/srtp.cpp
    crypto/pkcs12.cpp
    crypto/tls.cpp
    utils/certgen.cpp
@@ -86,6 +87,7 @@ set(headers
    crypto/pkcs12.h
    crypto/tls.h
    crypto/curve25519.h
    crypto/srtp.h
    utils/certgen.h
    threadpool.h
)

src/crypto/srtp.cpp

0 → 100644
+192 −0
Changes for src/crypto/srtp.cpp: 192 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
Copyright (c) 2026, Jan Koester jan.koester@gmx.net
All rights reserved. (BSD-3-Clause, see LICENSE)
*******************************************************************************/
#include "srtp.h"
#include "aes.h"
#include "sha.h"

#include <cstring>

namespace netplus::srtp {

namespace {
    // RTP header length incl. CSRCs and header extension; 0 = malformed
    size_t rtpHeaderLength(const uint8_t *p, size_t n) {
        if (n < 12 || (p[0] >> 6) != 2) return 0;
        size_t len = 12 + 4u * (p[0] & 0x0f);
        if (p[0] & 0x10) {   // extension
            if (n < len + 4) return 0;
            len += 4 + 4u * ((p[len + 2] << 8) | p[len + 3]);
        }
        return len <= n ? len : 0;
    }
    uint32_t be32(const uint8_t *p) { return (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) | (uint32_t(p[2]) << 8) | p[3]; }

    bool constEq(const uint8_t *a, const uint8_t *b, size_t n) {
        uint8_t d = 0;
        for (size_t i = 0; i < n; ++i) d |= a[i] ^ b[i];
        return d == 0;
    }
}

std::vector<uint8_t> deriveKey(const std::vector<uint8_t> &masterKey, const std::vector<uint8_t> &masterSalt, uint8_t label, size_t length) {
    // x = key_id XOR master_salt, key_id = label || r (r = 0 with kdr 0); key = AES-CM(master key, x * 2^16)
    aes128 cipher(masterKey);
    uint8_t iv[16] = {};
    std::memcpy(iv, masterSalt.data(), std::min<size_t>(masterSalt.size(), 14));
    iv[7] ^= label;
    std::vector<uint8_t> out;
    for (uint16_t ctr = 0; out.size() < length; ++ctr) {
        iv[14] = static_cast<uint8_t>(ctr >> 8);
        iv[15] = static_cast<uint8_t>(ctr);
        uint8_t block[16];
        cipher.encrypt_ecb(iv, block);
        for (int i = 0; i < 16 && out.size() < length; ++i) out.push_back(block[i]);
    }
    return out;
}

Context::Context(const std::vector<uint8_t> &masterKey, const std::vector<uint8_t> &masterSalt) {
    _rtpCipher = std::make_unique<aes128>(deriveKey(masterKey, masterSalt, 0, 16));
    _rtpAuth = deriveKey(masterKey, masterSalt, 1, 20);
    auto s = deriveKey(masterKey, masterSalt, 2, 14);
    std::memcpy(_rtpSalt.data(), s.data(), 14);
    _rtcpCipher = std::make_unique<aes128>(deriveKey(masterKey, masterSalt, 3, 16));
    _rtcpAuth = deriveKey(masterKey, masterSalt, 4, 20);
    s = deriveKey(masterKey, masterSalt, 5, 14);
    std::memcpy(_rtcpSalt.data(), s.data(), 14);
}

Context::~Context() = default;

void Context::keystream(const std::array<uint8_t, 14> &salt, uint32_t ssrc, uint64_t index, uint8_t *data, size_t len) {
    // IV = (k_s * 2^16) XOR (SSRC * 2^64) XOR (i * 2^16)
    uint8_t iv[16] = {};
    std::memcpy(iv, salt.data(), 14);
    for (int i = 0; i < 4; ++i) iv[4 + i] ^= static_cast<uint8_t>(ssrc >> (24 - 8 * i));
    for (int i = 0; i < 6; ++i) iv[8 + i] ^= static_cast<uint8_t>(index >> (40 - 8 * i));
    aes128 &cipher = (&salt == &_rtpSalt) ? *_rtpCipher : *_rtcpCipher;
    uint8_t block[16];
    for (size_t off = 0, ctr = 0; off < len; off += 16, ++ctr) {
        iv[14] = static_cast<uint8_t>(ctr >> 8);
        iv[15] = static_cast<uint8_t>(ctr);
        cipher.encrypt_ecb(iv, block);
        for (size_t i = 0; i < 16 && off + i < len; ++i) data[off + i] ^= block[i];
    }
}

std::array<uint8_t, TAG_LEN> Context::tag(const std::vector<uint8_t> &authKey, const uint8_t *data, size_t len, const uint8_t *tail,
                                           size_t tailLen) {
    std::vector<uint8_t> msg(data, data + len);
    msg.insert(msg.end(), tail, tail + tailLen);
    auto mac = hmac_sha1(authKey, msg);
    std::array<uint8_t, TAG_LEN> t{};
    std::memcpy(t.data(), mac.data(), TAG_LEN);
    return t;
}

bool Context::protectRtp(std::vector<uint8_t> &p) {
    size_t hl = rtpHeaderLength(p.data(), p.size());
    if (!hl) return false;
    const uint16_t seq = static_cast<uint16_t>((p[2] << 8) | p[3]);
    const uint32_t ssrc = be32(p.data() + 8);
    Stream &st = _streams[ssrc];
    if (st.started && seq < st.lastSeq && st.lastSeq - seq > 0x8000) ++st.roc;   // wrapped
    if (!st.started || static_cast<uint16_t>(seq - st.lastSeq) < 0x8000) st.lastSeq = seq;
    st.started = true;
    const uint64_t index = (uint64_t(st.roc) << 16) | seq;
    keystream(_rtpSalt, ssrc, index, p.data() + hl, p.size() - hl);
    uint8_t roc[4] = {uint8_t(st.roc >> 24), uint8_t(st.roc >> 16), uint8_t(st.roc >> 8), uint8_t(st.roc)};
    auto t = tag(_rtpAuth, p.data(), p.size(), roc, 4);
    p.insert(p.end(), t.begin(), t.end());
    return true;
}

bool Context::unprotectRtp(std::vector<uint8_t> &p) {
    if (p.size() < 12 + TAG_LEN) return false;
    size_t hl = rtpHeaderLength(p.data(), p.size() - TAG_LEN);
    if (!hl) return false;
    const uint16_t seq = static_cast<uint16_t>((p[2] << 8) | p[3]);
    const uint32_t ssrc = be32(p.data() + 8);
    Stream &st = _streams[ssrc];
    // RFC 3711 3.3.1: guess the rollover counter from the highest sequence number
    uint32_t v = st.roc;
    if (st.started) {
        if (st.lastSeq < 0x8000) {
            if (seq > st.lastSeq && seq - st.lastSeq > 0x8000 && st.roc > 0) v = st.roc - 1;
        } else if (seq < st.lastSeq - 0x8000) {
            v = st.roc + 1;
        }
    }
    const uint64_t index = (uint64_t(v) << 16) | seq;
    if (st.started) {   // replay check
        if (index <= st.highest) {
            uint64_t delta = st.highest - index;
            if (delta >= 64 || (st.window >> delta) & 1) return false;
        }
    }
    const size_t body = p.size() - TAG_LEN;
    uint8_t roc[4] = {uint8_t(v >> 24), uint8_t(v >> 16), uint8_t(v >> 8), uint8_t(v)};
    auto t = tag(_rtpAuth, p.data(), body, roc, 4);
    if (!constEq(t.data(), p.data() + body, TAG_LEN)) return false;
    keystream(_rtpSalt, ssrc, index, p.data() + hl, body - hl);
    p.resize(body);
    // update the state only for authentic packets
    if (!st.started || index > st.highest) {
        uint64_t shift = st.started ? index - st.highest : 0;
        st.window = shift >= 64 ? 1 : (st.window << shift) | 1;
        st.highest = index;
        st.roc = v;
        st.lastSeq = seq;
        st.started = true;
    } else {
        st.window |= uint64_t(1) << (st.highest - index);
    }
    return true;
}

bool Context::protectRtcp(std::vector<uint8_t> &p) {
    if (p.size() < 8 || (p[0] >> 6) != 2) return false;
    const uint32_t ssrc = be32(p.data() + 4);
    Stream &st = _streams[ssrc];
    const uint32_t index = st.rtcpIndex++ & 0x7fffffff;
    keystream(_rtcpSalt, ssrc, index, p.data() + 8, p.size() - 8);
    uint8_t ei[4] = {uint8_t(0x80 | (index >> 24)), uint8_t(index >> 16), uint8_t(index >> 8), uint8_t(index)};
    p.insert(p.end(), ei, ei + 4);
    auto t = tag(_rtcpAuth, p.data(), p.size(), nullptr, 0);
    p.insert(p.end(), t.begin(), t.end());
    return true;
}

bool Context::unprotectRtcp(std::vector<uint8_t> &p) {
    if (p.size() < 8 + 4 + TAG_LEN || (p[0] >> 6) != 2) return false;
    const size_t body = p.size() - TAG_LEN;
    auto t = tag(_rtcpAuth, p.data(), body, nullptr, 0);
    if (!constEq(t.data(), p.data() + body, TAG_LEN)) return false;
    const uint8_t *ei = p.data() + body - 4;
    const bool encrypted = ei[0] & 0x80;
    const uint32_t index = be32(ei) & 0x7fffffff;
    const uint32_t ssrc = be32(p.data() + 4);
    Stream &st = _streams[ssrc];
    if (st.rtcpStarted) {
        if (index <= st.rtcpIndex) {
            uint32_t delta = st.rtcpIndex - index;
            if (delta >= 64 || (st.rtcpWindow >> delta) & 1) return false;
            st.rtcpWindow |= uint64_t(1) << delta;
        } else {
            uint32_t shift = index - st.rtcpIndex;
            st.rtcpWindow = shift >= 64 ? 1 : (st.rtcpWindow << shift) | 1;
            st.rtcpIndex = index;
        }
    } else {
        st.rtcpStarted = true;
        st.rtcpIndex = index;
        st.rtcpWindow = 1;
    }
    p.resize(body - 4);
    if (encrypted) keystream(_rtcpSalt, ssrc, index, p.data() + 8, p.size() - 8);
    return true;
}

}

src/crypto/srtp.h

0 → 100644
+67 −0
Changes for src/crypto/srtp.h: 67 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
Copyright (c) 2026, Jan Koester jan.koester@gmx.net
All rights reserved. (BSD-3-Clause, see LICENSE)
*******************************************************************************/
#pragma once

// SRTP / SRTCP (RFC 3711) with the profile every WebRTC endpoint implements:
// SRTP_AES128_CM_HMAC_SHA1_80 (RFC 5764 use_srtp id 0x0001) -- AES-128 in
// counter mode, HMAC-SHA1 tags truncated to 80 bits, key derivation rate 0.
//
// One Context holds the session keys derived from one master key/salt (as
// exported by DTLS-SRTP for one direction) and the per-SSRC state: rollover
// counter, highest sequence number and a 64-packet replay window. A context
// either protects (sending side) or unprotects (receiving side); WebRTC uses
// two contexts per connection. Not thread-safe.

#include <array>
#include <cstdint>
#include <map>
#include <memory>
#include <vector>

namespace netplus {
    class aes128;

    namespace srtp {
        constexpr uint16_t AES128_CM_HMAC_SHA1_80 = 0x0001;
        constexpr size_t MASTER_KEY_LEN = 16, MASTER_SALT_LEN = 14, TAG_LEN = 10;

        // RFC 3711 4.3: one session key from the master key/salt (label 0..5)
        std::vector<uint8_t> deriveKey(const std::vector<uint8_t> &masterKey, const std::vector<uint8_t> &masterSalt,
                                       uint8_t label, size_t length);

        class Context {
        public:
            Context(const std::vector<uint8_t> &masterKey, const std::vector<uint8_t> &masterSalt);
            ~Context();

            // RTP: encrypts the payload and appends the tag; false on a malformed packet
            bool protectRtp(std::vector<uint8_t> &packet);
            // RTP: checks the tag (and replays), decrypts, strips the tag; false = drop
            bool unprotectRtp(std::vector<uint8_t> &packet);
            // RTCP: encrypts after the first 8 bytes, appends E|index and the tag
            bool protectRtcp(std::vector<uint8_t> &packet);
            bool unprotectRtcp(std::vector<uint8_t> &packet);

        private:
            struct Stream {
                uint32_t roc = 0;
                uint16_t lastSeq = 0;      // highest sequence number seen/sent
                bool     started = false;
                uint64_t window = 0;       // replay bitmap below the highest index
                uint64_t highest = 0;      // highest packet index (roc << 16 | seq)
                uint32_t rtcpIndex = 0;    // SRTCP: next index to send / highest received
                uint64_t rtcpWindow = 0;
                bool     rtcpStarted = false;
            };
            void keystream(const std::array<uint8_t, 14> &salt, uint32_t ssrc, uint64_t index, uint8_t *data, size_t len);
            std::array<uint8_t, TAG_LEN> tag(const std::vector<uint8_t> &authKey, const uint8_t *data, size_t len, const uint8_t *tail, size_t tailLen);

            std::unique_ptr<aes128> _rtpCipher, _rtcpCipher;
            std::vector<uint8_t> _rtpAuth, _rtcpAuth;
            std::array<uint8_t, 14> _rtpSalt{}, _rtcpSalt{};
            std::map<uint32_t, Stream> _streams;
        };
    }
}
+4 −0
Changes for test/CMakeLists.txt: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -320,3 +320,7 @@ else()
    target_link_libraries(close_race_test netplus-static)
endif()
add_test(NAME close_race_test COMMAND close_race_test)

add_executable(srtp_test srtp_test.cpp)
target_link_libraries(srtp_test netplus-static)
add_test(NAME srtp_test COMMAND srtp_test)

test/srtp_test.cpp

0 → 100644
+102 −0
Changes for test/srtp_test.cpp: 102 added lines, 0 removed lines.
Original line number Diff line number Diff line
// SRTP/SRTCP (RFC 3711): key derivation vectors (B.3), libsrtp's reference
// packets for AES_CM_128_HMAC_SHA1_80, rollover, replay and tamper checks.
#include "../src/crypto/srtp.h"

#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>

static int failures = 0, checks = 0;
#define CHECK(c) do { ++checks; if (!(c)) { ++failures; std::printf("FAILED line %d: %s\n", __LINE__, #c); } } while (0)

static std::vector<uint8_t> hex(const std::string &h) {
    std::vector<uint8_t> v;
    for (size_t i = 0; i + 1 < h.size(); i += 2) {
        if (h[i] == ' ') { --i; continue; }
        v.push_back(static_cast<uint8_t>(std::strtol(h.substr(i, 2).c_str(), nullptr, 16)));
    }
    return v;
}
static std::string str(const std::vector<uint8_t> &v) {
    std::string s;
    char b[3];
    for (auto c : v) { std::snprintf(b, 3, "%02x", c); s += b; }
    return s;
}

int main() {
    using namespace netplus::srtp;
    // RFC 3711 B.3
    auto mk = hex("E1F97A0D3E018BE0D64FA32C06DE4139"), ms = hex("0EC675AD498AFEEBB6960B3AABE6");
    CHECK(str(deriveKey(mk, ms, 0, 16)) == "c61e7a93744f39ee10734afe3ff7a087");
    CHECK(str(deriveKey(mk, ms, 2, 14)) == "30cbbc08863d8c85d49db34a9ae1");
    CHECK(str(deriveKey(mk, ms, 1, 20)) == "cebe321f6ff7716b6fd4ab49af256a156d38baa4");

    // libsrtp test/srtp_driver.c: same master key/salt
    std::vector<uint8_t> rtp = hex("800f1234decafbadcafebabe");
    for (int i = 0; i < 16; ++i) rtp.push_back(0xab);
    const std::string srtpRef = "800f1234decafbadcafebabe4e55dc4ce79978d88ca4d215949d2402b78d6acc99ea179b8dbb";
    {
        Context tx(mk, ms);
        auto p = rtp;
        CHECK(tx.protectRtp(p));
        CHECK(str(p) == srtpRef);
        Context rx(mk, ms);
        CHECK(rx.unprotectRtp(p));
        CHECK(p == rtp);
        auto again = hex(srtpRef);
        CHECK(!rx.unprotectRtp(again));   // replay
    }
    {
        Context rx(mk, ms);
        auto bad = hex(srtpRef);
        bad[14] ^= 1;   // payload bit flipped
        CHECK(!rx.unprotectRtp(bad));
        auto good = hex(srtpRef);
        CHECK(rx.unprotectRtp(good));   // a forged packet does not poison the state
    }
    // SRTCP reference packet (index 1, encrypted)
    std::vector<uint8_t> rtcp = hex("81c8000bcafebabe");
    for (int i = 0; i < 16; ++i) rtcp.push_back(0xab);
    {
        Context rx(mk, ms);
        auto p = hex("81c8000bcafebabe7128035be487b9bdbef89041f977a5a880000001993e08cd54d6c1230798");
        CHECK(rx.unprotectRtcp(p));
        CHECK(p == rtcp);
        auto again = hex("81c8000bcafebabe7128035be487b9bdbef89041f977a5a880000001993e08cd54d6c1230798");
        CHECK(!rx.unprotectRtcp(again));   // replay
        Context tx(mk, ms), rx2(mk, ms);
        for (int i = 0; i < 3; ++i) {
            auto q = rtcp;
            CHECK(tx.protectRtcp(q));
            CHECK(q.size() == rtcp.size() + 14);
            CHECK(rx2.unprotectRtcp(q) && q == rtcp);
        }
    }
    // sequence numbers wrapping: the rollover counter follows on both sides
    {
        Context tx(mk, ms), rx(mk, ms);
        int ok = 0;
        for (uint32_t n = 0; n < 200; ++n) {
            uint16_t seq = static_cast<uint16_t>(65436 + n);   // passes 65535 -> 0
            auto p = rtp;
            p[2] = static_cast<uint8_t>(seq >> 8);
            p[3] = static_cast<uint8_t>(seq);
            auto orig = p;
            tx.protectRtp(p);
            if (rx.unprotectRtp(p) && p == orig) ++ok;
        }
        CHECK(ok == 200);
        // out of order within the window is fine, too old is not
        auto a = rtp, b = rtp;
        a[2] = 0; a[3] = 210;
        b[2] = 0; b[3] = 205;
        tx.protectRtp(a);
        tx.protectRtp(b);
        CHECK(rx.unprotectRtp(a));
        CHECK(rx.unprotectRtp(b));
    }
    std::printf("%s: %d/%d checks passed\n", failures ? "FAILED" : "OK", checks - failures, checks);
    return failures ? 1 : 0;
}