PR #26017 opened by ambitiuswisdom
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26017
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26017.patch

Native RTMPE and RTMPTE currently require GMP, libgcrypt, OpenSSL, or mbedTLS 
for Diffie-Hellman key exchange. This series adds a Windows CNG backend, 
allowing Windows builds to use these protocols without an external crypto 
library.

The backend reuses the existing bcrypt detection and is selected when none of 
the existing DH backends is enabled. Selection is independent of the TLS 
backend. It uses the fixed RTMPE DH parameters, validates peer public keys, and 
preserves the shared-secret representation used by the GMP backend, including 
short secrets.

Raw DH secret derivation requires Windows 8.1 or later. If the operation is 
unavailable, the connection fails with an explicit error. No new configure 
option or change to the Windows build target is required.

The series also includes three preparatory changes:
- Preserve caller-owned buffers during RTMPE encryption. In-place encryption 
modifies packet data and corrupts headers reused for subsequent chunks.
- Reject DH public keys outside the valid range before checking subgroup 
membership.
- Make the internal FF_DH context opaque to accommodate backend-specific state.
Validation with MinGW-w64 on Windows 11:
- fate-rtmpdh and fate-rtmpcrypt pass with CNG + Schannel, GMP + Schannel, and 
a minimal configuration enabling only ffrtmpcrypt.
- Local RTMPE/RTMPTE tests cover handshake types 6, 8, and 9, both handshake 
layouts, short shared secrets, and encrypted control traffic.
- Failure injection verifies that unsupported raw-secret derivation reports an 
error and aborts the handshake.

Windows 8.1 itself has not been tested; protocol validation used a local test 
server.


>From d4c21e9e3532512c64705d10168719a23c04ba04 Mon Sep 17 00:00:00 2001
From: Ruonan <[email protected]>
Date: Fri, 13 Nov 2026 12:00:32 +0800
Subject: [PATCH 1/4] avformat/rtmpcrypt: preserve the input buffer when
 encrypting packets

Encrypting in place modifies the caller's packet data and chunk headers.
The packet writer reuses continuation headers, so packets spanning more
than two chunks can be corrupted.

Encrypt into a reusable output buffer and add a regression test for a
packet spanning three chunks. Link the packet helpers explicitly so the
test also works when only the ffrtmpcrypt protocol is enabled.

Signed-off-by: Ruonan <[email protected]>
---
 libavformat/Makefile          |  4 +-
 libavformat/rtmpcrypt.c       | 10 +++-
 libavformat/tests/rtmpcrypt.c | 92 +++++++++++++++++++++++++++++++++++
 tests/fate/libavformat.mak    |  5 +-
 tests/ref/fate/rtmpcrypt      |  1 +
 5 files changed, 109 insertions(+), 3 deletions(-)
 create mode 100644 libavformat/tests/rtmpcrypt.c
 create mode 100644 tests/ref/fate/rtmpcrypt

diff --git a/libavformat/Makefile b/libavformat/Makefile
index 891d7f82d9a..14e725de690 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -789,7 +789,7 @@ TESTPROGS-$(CONFIG_RTPDEC)               += rtpdec
 
 FIFO-MUXER-TESTPROGS-$(CONFIG_NETWORK)   += fifo_muxer
 TESTPROGS-$(CONFIG_FIFO_MUXER)           += $(FIFO-MUXER-TESTPROGS-yes)
-TESTPROGS-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += rtmpdh
+TESTPROGS-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += rtmpcrypt rtmpdh
 TESTPROGS-$(CONFIG_HTTP_PROTOCOL)        += http
 TESTPROGS-$(CONFIG_NETWORK)              += noproxy
 TESTPROGS-$(CONFIG_SRTP)                 += srtp
@@ -799,6 +799,8 @@ TESTPROGS-$(CONFIG_AU_MUXER)             += auenc
 TESTPROGS-$(CONFIG_MPEGTS_DEMUXER)       += mpegts_probe
 TESTPROGS-$(CONFIG_OGG_MUXER)            += ogg_pages
 
+$(SUBDIR)tests/rtmpcrypt$(EXESUF): $(SUBDIR)rtmppkt.o
+
 TOOLS     = aviocat                                                     \
             ismindex                                                    \
             pktdumper                                                   \
diff --git a/libavformat/rtmpcrypt.c b/libavformat/rtmpcrypt.c
index a835ab263f5..e4419f28a87 100644
--- a/libavformat/rtmpcrypt.c
+++ b/libavformat/rtmpcrypt.c
@@ -28,6 +28,7 @@
 
 #include "libavutil/blowfish.h"
 #include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
 #include "libavutil/opt.h"
 #include "libavutil/rc4.h"
 #include "libavutil/xtea.h"
@@ -45,6 +46,8 @@ typedef struct RTMPEContext {
     FF_DH        *dh;                ///< Diffie-Hellman context
     struct AVRC4 key_in;             ///< RC4 key used for decrypt data
     struct AVRC4 key_out;            ///< RC4 key used for encrypt data
+    uint8_t      *write_buffer;
+    unsigned int write_buffer_size;
     int          handshaked;         ///< flag indicating when the handshake 
is performed
     int          tunneling;          ///< use a HTTP connection (RTMPTE)
 } RTMPEContext;
@@ -240,6 +243,7 @@ static int rtmpe_close(URLContext *h)
     RTMPEContext *rt = h->priv_data;
 
     ff_dh_free(rt->dh);
+    av_freep(&rt->write_buffer);
     ffurl_closep(&rt->stream);
 
     return 0;
@@ -300,8 +304,12 @@ static int rtmpe_write(URLContext *h, const uint8_t *buf, 
int size)
     int ret;
 
     if (rt->handshaked) {
+        av_fast_malloc(&rt->write_buffer, &rt->write_buffer_size, size);
+        if (!rt->write_buffer)
+            return AVERROR(ENOMEM);
         /* encrypt data to send to the server */
-        av_rc4_crypt(&rt->key_out, (uint8_t *)buf, buf, size, NULL, 1);
+        av_rc4_crypt(&rt->key_out, rt->write_buffer, buf, size, NULL, 1);
+        buf = rt->write_buffer;
     }
 
     if ((ret = ffurl_write(rt->stream, buf, size)) < 0)
diff --git a/libavformat/tests/rtmpcrypt.c b/libavformat/tests/rtmpcrypt.c
new file mode 100644
index 00000000000..77236ffab7a
--- /dev/null
+++ b/libavformat/tests/rtmpcrypt.c
@@ -0,0 +1,92 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+
+#include "libavformat/rtmpcrypt.c"
+#include "libavformat/rtmppkt.h"
+
+typedef struct Output {
+    uint8_t data[512];
+    int size;
+} Output;
+
+static int write_packet(URLContext *h, const uint8_t *buf, int size)
+{
+    Output *out = h->priv_data;
+
+    if (size > sizeof(out->data) - out->size)
+        return AVERROR(ENOSPC);
+    memcpy(out->data + out->size, buf, size);
+    out->size += size;
+    return size;
+}
+
+int main(void)
+{
+    static const URLProtocol sink_protocol = { .url_write = write_packet };
+    static const uint8_t key[16] = { 1, 2, 3, 4 };
+    uint8_t payload[300], expected[314];
+    Output out = { 0 };
+    URLContext sink = { .prot = &sink_protocol, .priv_data = &out,
+                        .flags = AVIO_FLAG_WRITE };
+    RTMPEContext rt = { .stream = &sink, .handshaked = 1 };
+    URLContext encrypted = { .prot = &ff_ffrtmpcrypt_protocol, .priv_data = 
&rt,
+                             .flags = AVIO_FLAG_WRITE };
+    RTMPPacket pkt = { 0 }, *previous = NULL;
+    struct AVRC4 decrypt;
+    int i, ret, nb_previous = 0;
+
+    avformat_network_init();
+    av_rc4_init(&rt.key_out, key, sizeof(key) * 8, 0);
+    av_rc4_init(&decrypt, key, sizeof(key) * 8, 0);
+    if (ff_rtmp_packet_create(&pkt, 3, RTMP_PT_INVOKE, 0, sizeof(payload)) < 0)
+        return 1;
+    for (i = 0; i < sizeof(payload); i++)
+        payload[i] = i;
+    memcpy(pkt.data, payload, sizeof(payload));
+
+    memset(expected, 0, sizeof(expected));
+    expected[0] = 3;
+    AV_WB24(expected + 4, pkt.size);
+    expected[7] = RTMP_PT_INVOKE;
+    memcpy(expected + 12, payload, 128);
+    expected[140] = 0xc3;
+    memcpy(expected + 141, payload + 128, 128);
+    expected[269] = 0xc3;
+    memcpy(expected + 270, payload + 256, sizeof(payload) - 256);
+
+    ret = ff_rtmp_packet_write(&encrypted, &pkt, 128, &previous, &nb_previous);
+    if (ret < 0)
+        goto end;
+    av_rc4_crypt(&decrypt, out.data, out.data, out.size, NULL, 1);
+    if (out.size != sizeof(expected) || memcmp(out.data, expected, 
sizeof(expected)) ||
+        memcmp(pkt.data, payload, sizeof(payload))) {
+        printf("RTMPE corrupted a chunk header or the input packet\n");
+        ret = AVERROR_INVALIDDATA;
+    } else {
+        printf("RTMPE packet encryption ok\n");
+    }
+
+end:
+    ff_rtmp_packet_destroy(&pkt);
+    av_free(previous);
+    av_free(rt.write_buffer);
+    avformat_network_deinit();
+    return ret < 0;
+}
diff --git a/tests/fate/libavformat.mak b/tests/fate/libavformat.mak
index 70d5439437f..2a72a4314c6 100644
--- a/tests/fate/libavformat.mak
+++ b/tests/fate/libavformat.mak
@@ -60,7 +60,10 @@ FATE_LIBAVFORMAT-$(CONFIG_NETWORK) += fate-noproxy
 fate-noproxy: libavformat/tests/noproxy$(EXESUF)
 fate-noproxy: CMD = run libavformat/tests/noproxy$(EXESUF)
 
-FATE_LIBAVFORMAT-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += fate-rtmpdh
+FATE_LIBAVFORMAT-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += fate-rtmpcrypt fate-rtmpdh
+fate-rtmpcrypt: libavformat/tests/rtmpcrypt$(EXESUF)
+fate-rtmpcrypt: CMD = run libavformat/tests/rtmpcrypt$(EXESUF)
+
 fate-rtmpdh: libavformat/tests/rtmpdh$(EXESUF)
 fate-rtmpdh: CMD = run libavformat/tests/rtmpdh$(EXESUF)
 
diff --git a/tests/ref/fate/rtmpcrypt b/tests/ref/fate/rtmpcrypt
new file mode 100644
index 00000000000..874014108ec
--- /dev/null
+++ b/tests/ref/fate/rtmpcrypt
@@ -0,0 +1 @@
+RTMPE packet encryption ok
-- 
2.54.0


>From 767241fd97970c1ccc7becdafb474aa3b82b821c Mon Sep 17 00:00:00 2001
From: Ruonan <[email protected]>
Date: Fri, 13 Nov 2026 12:01:03 +0800
Subject: [PATCH 2/4] avformat/rtmpdh: reject public keys outside the valid
 range

Reject keys below 2 or above p - 2 before checking subgroup membership.
Checking only for equality with 1 and p - 1 can accept out-of-range
values whose residues pass the modular exponentiation check.

Extend the DH test with boundary values and deterministic public-key
vectors to cover both the range and subgroup checks.

Signed-off-by: Ruonan <[email protected]>
---
 libavformat/rtmpdh.c       |  7 ++--
 libavformat/tests/rtmpdh.c | 82 +++++++++++++++++++++++++++++++++++---
 2 files changed, 80 insertions(+), 9 deletions(-)

diff --git a/libavformat/rtmpdh.c b/libavformat/rtmpdh.c
index fb7aaf07c0e..19a336e0178 100644
--- a/libavformat/rtmpdh.c
+++ b/libavformat/rtmpdh.c
@@ -289,15 +289,14 @@ static int dh_is_valid_public_key(FFBigNum y, FFBigNum p, 
FFBigNum q)
     if (!bn)
         return AVERROR(ENOMEM);
 
-    /* y must lie in [2, p - 1] */
+    /* y must lie in [2, p - 2] */
     bn_set_word(bn, 1);
-    if (!bn_cmp(y, bn))
+    if (bn_cmp(y, bn) <= 0)
         goto fail;
 
-    /* bn = p - 2 */
     bn_copy(bn, p);
     bn_sub_word(bn, 1);
-    if (!bn_cmp(y, bn))
+    if (bn_cmp(y, bn) >= 0)
         goto fail;
 
     /* Verify with Sophie-Germain prime
diff --git a/libavformat/tests/rtmpdh.c b/libavformat/tests/rtmpdh.c
index 77139a539c8..f634e47a667 100644
--- a/libavformat/tests/rtmpdh.c
+++ b/libavformat/tests/rtmpdh.c
@@ -17,10 +17,24 @@
  */
 
 #include "libavformat/avformat.h"
+#include "libavformat/internal.h"
 #include "libavformat/rtmpdh.c"
 
 #include <stdio.h>
 
+static int set_key(FF_DH *dh, const char *priv, const char *pub)
+{
+    int ret;
+
+    bn_hex2bn(dh->priv_key, priv, ret);
+    if (!ret)
+        return AVERROR(ENOMEM);
+    bn_hex2bn(dh->pub_key, pub, ret);
+    if (!ret)
+        return AVERROR(ENOMEM);
+    return 0;
+}
+
 static int test_random_shared_secret(void)
 {
     FF_DH *peer1 = NULL, *peer2 = NULL;
@@ -120,11 +134,7 @@ static int test_ref_data(void)
     dh = ff_dh_init(1024);
     if (!dh)
         goto fail;
-    bn_hex2bn(dh->priv_key, private_key, ret);
-    if (!ret)
-        goto fail;
-    bn_hex2bn(dh->pub_key, public_key, ret);
-    if (!ret)
+    if ((ret = set_key(dh, private_key, public_key)) < 0)
         goto fail;
     if ((ret = ff_dh_write_public_key(dh, pubkey_test, sizeof(pubkey_test))) < 
0)
         goto fail;
@@ -149,6 +159,66 @@ fail:
     return ret;
 }
 
+static int test_public_keys(void)
+{
+    static const int valid[] = { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 };
+    /* Reference bits for y^((p - 1) / 2) mod p == 1. */
+    static const uint8_t valid_random[] = {
+        0x68, 0x68, 0xfc, 0x42, 0xab, 0xc8, 0xfa, 0xb4,
+        0x15, 0x98, 0x93, 0xc3, 0xa3, 0xa4, 0xfb, 0x7c,
+        0xbd, 0xb2, 0x42, 0x54, 0x73, 0x2a, 0xb8, 0xb9,
+        0x17, 0x42, 0xe6, 0xf4, 0x68, 0xbd, 0xba, 0x73,
+    };
+    uint8_t keys[10][128] = { { 0 } };
+    uint8_t secret[128], pub[128];
+    uint32_t state = 1;
+    FF_DH *dh = ff_dh_init(1024);
+    int i, j, ret = AVERROR(ENOMEM);
+
+    if (!dh)
+        return ret;
+    if ((ret = set_key(dh, "02", "04")) < 0)
+        goto fail;
+
+    keys[1][127] = 1;
+    keys[2][127] = 2;
+    keys[3][127] = 4;
+    keys[4][127] = 5;
+    for (i = 5; i < 9; i++)
+        ff_hex_to_data(keys[i], P1024);
+    keys[5][127] -= 2;
+    keys[6][127]--;
+    for (i = 127; i >= 0; i--)
+        if (++keys[8][i])
+            break;
+    memset(keys[9], 0xff, 128);
+
+    for (i = 0; i < FF_ARRAY_ELEMS(keys); i++) {
+        ret = ff_dh_compute_shared_secret_key(dh, keys[i], 128, secret, 128);
+        if ((ret >= 0) != valid[i]) {
+            printf("Unexpected public key validation result for vector %d\n", 
i);
+            ret = AVERROR_INVALIDDATA;
+            goto fail;
+        }
+    }
+    for (i = 0; i < 256; i++) {
+        for (j = 0; j < sizeof(pub); j++) {
+            state = state * 1664525U + 1013904223U;
+            pub[j] = state >> 24;
+        }
+        ret = ff_dh_compute_shared_secret_key(dh, pub, sizeof(pub), secret, 
sizeof(secret));
+        if ((ret >= 0) != ((valid_random[i / 8] >> (i % 8)) & 1)) {
+            printf("Unexpected public key validation result for random vector 
%d\n", i);
+            ret = AVERROR_INVALIDDATA;
+            goto fail;
+        }
+    }
+    ret = 0;
+fail:
+    ff_dh_free(dh);
+    return ret;
+}
+
 int main(void)
 {
     avformat_network_init();
@@ -156,5 +226,7 @@ int main(void)
         return 1;
     if (test_ref_data() < 0)
         return 1;
+    if (test_public_keys() < 0)
+        return 1;
     return 0;
 }
-- 
2.54.0


>From e2ea20af4f3bb3431f564a61c7cb7d9f3e378798 Mon Sep 17 00:00:00 2001
From: Ruonan <[email protected]>
Date: Fri, 13 Nov 2026 12:01:52 +0800
Subject: [PATCH 3/4] avformat/rtmpdh: make FF_DH opaque

Callers only use the DH context through pointers and do not need its
bignum representation or the external library headers. Keep these
details in the implementation so backends can use different context
layouts.

Signed-off-by: Ruonan <[email protected]>
---
 libavformat/rtmpdh.c | 21 ++++++++++++++++++++-
 libavformat/rtmpdh.h | 32 +-------------------------------
 2 files changed, 21 insertions(+), 32 deletions(-)

diff --git a/libavformat/rtmpdh.c b/libavformat/rtmpdh.c
index 19a336e0178..1a71dfc9612 100644
--- a/libavformat/rtmpdh.c
+++ b/libavformat/rtmpdh.c
@@ -38,9 +38,20 @@
 
 #include "rtmpdh.h"
 
-#if CONFIG_MBEDTLS
+#if CONFIG_GMP
+#include <gmp.h>
+typedef mpz_ptr FFBigNum;
+#elif CONFIG_GCRYPT
+#include <gcrypt.h>
+typedef gcry_mpi_t FFBigNum;
+#elif CONFIG_OPENSSL
+#include <openssl/bn.h>
+typedef BIGNUM *FFBigNum;
+#elif CONFIG_MBEDTLS
+#include <mbedtls/bignum.h>
 #include <mbedtls/ctr_drbg.h>
 #include <mbedtls/entropy.h>
+typedef mbedtls_mpi *FFBigNum;
 #endif
 
 #define P1024                                          \
@@ -59,6 +70,14 @@
     "F71C35FDAD44CFD2D74F9208BE258FF324943328F67329C0" \
     "FFFFFFFFFFFFFFFF"
 
+struct FF_DH {
+    FFBigNum p;
+    FFBigNum g;
+    FFBigNum pub_key;
+    FFBigNum priv_key;
+    long length;
+};
+
 #if CONFIG_GMP
 #define bn_new(bn)                      \
     do {                                \
diff --git a/libavformat/rtmpdh.h b/libavformat/rtmpdh.h
index 8cc1a42b633..f301e039a83 100644
--- a/libavformat/rtmpdh.h
+++ b/libavformat/rtmpdh.h
@@ -24,37 +24,7 @@
 
 #include <stdint.h>
 
-#include "config.h"
-
-#if CONFIG_GMP
-#include <gmp.h>
-
-typedef mpz_ptr FFBigNum;
-#elif CONFIG_GCRYPT
-#include <gcrypt.h>
-
-typedef gcry_mpi_t FFBigNum;
-
-#elif CONFIG_OPENSSL
-#include <openssl/bn.h>
-#include <openssl/dh.h>
-
-typedef BIGNUM *FFBigNum;
-#elif CONFIG_MBEDTLS
-#include <mbedtls/bignum.h>
-
-typedef mbedtls_mpi *FFBigNum;
-
-#endif
-
-typedef struct FF_DH {
-    FFBigNum p;
-    FFBigNum g;
-    FFBigNum pub_key;
-    FFBigNum priv_key;
-    long length;
-} FF_DH;
-
+typedef struct FF_DH FF_DH;
 
 /**
  * Initialize a Diffie-Hellmann context.
-- 
2.54.0


>From 3aa4244d3f34328a732e3c015aa86e5adc646988 Mon Sep 17 00:00:00 2001
From: Ruonan <[email protected]>
Date: Fri, 13 Nov 2026 12:02:44 +0800
Subject: [PATCH 4/4] avformat/rtmpdh: add a Windows CNG backend

Use BCrypt for RTMPE and RTMPTE Diffie-Hellman key exchange when none of
the existing external crypto backends is enabled. Reuse bcrypt detection
without adding a configure option or tying DH selection to the TLS
backend.

Validate peer public keys against the fixed group using a binary Jacobi
calculation. Convert the raw little-endian shared secret to the byte
representation used by the GMP backend, including short secrets.

Raw secret derivation requires Windows 8.1 or later. Report an error and
abort the handshake if the operation is unavailable at runtime, without
raising the build's Windows target version.

Extend the DH tests with CNG key import, short-secret vectors and error
cases, and document the runtime requirement.

Signed-off-by: Ruonan <[email protected]>
---
 Changelog                  |   1 +
 configure                  |   8 +-
 doc/protocols.texi         |   5 +
 libavformat/rtmpdh.c       | 236 +++++++++++++++++++++++++++++++++++++
 libavformat/tests/rtmpdh.c | 110 ++++++++++++++++-
 libavformat/version.h      |   2 +-
 6 files changed, 355 insertions(+), 7 deletions(-)

diff --git a/Changelog b/Changelog
index bce79b181f7..cf30befa6f1 100644
--- a/Changelog
+++ b/Changelog
@@ -6,6 +6,7 @@ version <next>:
 - LCEVC raw demuxer and muxer
 - AVS+ (AVS1-P16, Broadcasting profile) support in the Chinese AVS decoder
 - PCM PAMF decoder
+- Windows CNG support for native RTMPE and RTMPTE
 
 version 9.1:
 - ASTC image encoding and decoding via libastcenc, with .astc and KTX 1.0 
muxers and demuxers
diff --git a/configure b/configure
index 69793448886..9a498d17108 100755
--- a/configure
+++ b/configure
@@ -205,10 +205,8 @@ External library support:
   --disable-coreimage      disable Apple CoreImage framework [autodetect]
   --enable-chromaprint     enable audio fingerprinting with chromaprint [no]
   --enable-frei0r          enable frei0r video filtering [no]
-  --enable-gcrypt          enable gcrypt, needed for rtmp(t)e support
-                           if openssl, librtmp or gmp is not used [no]
-  --enable-gmp             enable gmp, needed for rtmp(t)e support
-                           if openssl or librtmp is not used [no]
+  --enable-gcrypt          enable gcrypt for rtmp(t)e support [no]
+  --enable-gmp             enable gmp for rtmp(t)e support [no]
   --enable-gnutls          enable gnutls, needed for https support
                            if openssl, libtls or mbedtls is not used [no]
   --disable-iconv          disable iconv [autodetect]
@@ -4052,7 +4050,7 @@ android_content_protocol_select="file_protocol"
 async_protocol_deps="threads"
 bluray_protocol_deps="libbluray"
 ffrtmpcrypt_protocol_conflict="librtmp_protocol"
-ffrtmpcrypt_protocol_deps_any="gcrypt gmp openssl mbedtls"
+ffrtmpcrypt_protocol_deps_any="gcrypt gmp openssl mbedtls bcrypt"
 ffrtmpcrypt_protocol_select="tcp_protocol"
 ffrtmphttp_protocol_conflict="librtmp_protocol"
 ffrtmphttp_protocol_select="http_protocol"
diff --git a/doc/protocols.texi b/doc/protocols.texi
index e802c9121b5..b21ba6b49b2 100644
--- a/doc/protocols.texi
+++ b/doc/protocols.texi
@@ -1073,6 +1073,11 @@ streaming multimedia content within standard 
cryptographic primitives,
 consisting of Diffie-Hellman key exchange and HMACSHA256, generating
 a pair of RC4 keys.
 
+The native RTMPE and RTMPTE protocols require GMP, libgcrypt, OpenSSL,
+mbedTLS, or Windows CNG. CNG support is detected automatically at build
+time and requires Windows 8.1 or later at runtime. Connections fail with
+an error if raw Diffie-Hellman shared-secret derivation is unavailable.
+
 @section rtmps
 
 Real-Time Messaging Protocol over a secure SSL connection.
diff --git a/libavformat/rtmpdh.c b/libavformat/rtmpdh.c
index 1a71dfc9612..af13bc9681b 100644
--- a/libavformat/rtmpdh.c
+++ b/libavformat/rtmpdh.c
@@ -38,6 +38,9 @@
 
 #include "rtmpdh.h"
 
+#define USE_BCRYPT (HAVE_BCRYPT && !CONFIG_GMP && !CONFIG_GCRYPT && \
+                    !CONFIG_OPENSSL && !CONFIG_MBEDTLS)
+
 #if CONFIG_GMP
 #include <gmp.h>
 typedef mpz_ptr FFBigNum;
@@ -52,6 +55,10 @@ typedef BIGNUM *FFBigNum;
 #include <mbedtls/ctr_drbg.h>
 #include <mbedtls/entropy.h>
 typedef mbedtls_mpi *FFBigNum;
+#elif USE_BCRYPT
+#include <windows.h>
+#include <bcrypt.h>
+#include "internal.h"
 #endif
 
 #define P1024                                          \
@@ -70,6 +77,8 @@ typedef mbedtls_mpi *FFBigNum;
     "F71C35FDAD44CFD2D74F9208BE258FF324943328F67329C0" \
     "FFFFFFFFFFFFFFFF"
 
+#if !USE_BCRYPT
+
 struct FF_DH {
     FFBigNum p;
     FFBigNum g;
@@ -442,3 +451,230 @@ fail:
 
     return ret;
 }
+
+#else
+
+typedef struct DHKeyBlob {
+    BCRYPT_DH_KEY_BLOB header;
+    uint8_t p[128];
+    uint8_t g[128];
+    uint8_t y[128];
+} DHKeyBlob;
+
+struct FF_DH {
+    BCRYPT_ALG_HANDLE algorithm;
+    BCRYPT_KEY_HANDLE key;
+    DHKeyBlob public_key;
+};
+
+static int dh_bcrypt_error(const char *name, NTSTATUS status)
+{
+    av_log(NULL, AV_LOG_ERROR, "%s failed: 0x%08lx\n", name, (unsigned 
long)status);
+    return AVERROR_EXTERNAL;
+}
+
+static int dh_is_valid_public_key(const uint8_t *y, const uint8_t *p)
+{
+    uint8_t a[128], b[128], tmp[128];
+    int i, sign = 1;
+
+    for (i = 0; i < 127 && !y[i]; i++);
+    if (i == 127 && y[i] < 2)
+        return AVERROR(EINVAL);
+
+    memcpy(a, y, sizeof(a));
+    memcpy(b, p, sizeof(b));
+    b[127]--;
+    if (memcmp(a, b, sizeof(a)) >= 0)
+        return AVERROR(EINVAL);
+    b[127]++;
+
+    /* For this prime, Jacobi(y, p) == 1 is equivalent to y^Q1024 mod p == 1.
+     * Binary reciprocity only needs shifts and subtraction of public values. 
*/
+    for (;;) {
+        int borrow = 0;
+
+        for (i = 0; i < 128 && !a[i]; i++);
+        if (i == 128)
+            break;
+
+        while (!(a[127] & 1)) {
+            for (i = 127; i > 0; i--)
+                a[i] = (a[i] >> 1) | (a[i - 1] << 7);
+            a[0] >>= 1;
+            if ((b[127] & 7) == 3 || (b[127] & 7) == 5)
+                sign = -sign;
+        }
+
+        if (memcmp(a, b, sizeof(a)) < 0) {
+            if ((a[127] & b[127] & 3) == 3)
+                sign = -sign;
+            memcpy(tmp, a, sizeof(a));
+            memcpy(a, b, sizeof(a));
+            memcpy(b, tmp, sizeof(a));
+        }
+
+        for (i = 127; i >= 0; i--) {
+            int diff = a[i] - b[i] - borrow;
+            a[i] = diff;
+            borrow = diff < 0;
+        }
+    }
+
+    return sign == 1 ? 0 : AVERROR(EINVAL);
+}
+
+av_cold FF_DH *ff_dh_init(int key_len)
+{
+    FF_DH *dh;
+    NTSTATUS status;
+
+    if (key_len != 1024)
+        return NULL;
+    dh = av_mallocz(sizeof(*dh));
+    if (!dh)
+        return NULL;
+
+    status = BCryptOpenAlgorithmProvider(&dh->algorithm, BCRYPT_DH_ALGORITHM,
+                                         MS_PRIMITIVE_PROVIDER, 0);
+    if (!BCRYPT_SUCCESS(status)) {
+        dh_bcrypt_error("BCryptOpenAlgorithmProvider", status);
+        av_free(dh);
+        return NULL;
+    }
+
+    dh->public_key.header.dwMagic = BCRYPT_DH_PUBLIC_MAGIC;
+    dh->public_key.header.cbKey   = 128;
+    ff_hex_to_data(dh->public_key.p, P1024);
+    dh->public_key.g[127] = 2;
+    return dh;
+}
+
+void ff_dh_free(FF_DH *dh)
+{
+    if (!dh)
+        return;
+    if (dh->key)
+        BCryptDestroyKey(dh->key);
+    BCryptCloseAlgorithmProvider(dh->algorithm, 0);
+    av_free(dh);
+}
+
+int ff_dh_generate_public_key(FF_DH *dh)
+{
+    struct {
+        BCRYPT_DH_PARAMETER_HEADER header;
+        uint8_t p[128];
+        uint8_t g[128];
+    } params = { { sizeof(params), BCRYPT_DH_PARAMETERS_MAGIC, 128 } };
+    BCRYPT_KEY_HANDLE key = NULL;
+    DHKeyBlob public_key;
+    NTSTATUS status;
+    ULONG len;
+    int ret;
+
+    memcpy(params.p, dh->public_key.p, sizeof(params.p));
+    memcpy(params.g, dh->public_key.g, sizeof(params.g));
+    status = BCryptGenerateKeyPair(dh->algorithm, &key, 1024, 0);
+    if (!BCRYPT_SUCCESS(status))
+        return dh_bcrypt_error("BCryptGenerateKeyPair", status);
+
+    status = BCryptSetProperty(key, BCRYPT_DH_PARAMETERS,
+                               (PUCHAR)&params, sizeof(params), 0);
+    if (!BCRYPT_SUCCESS(status)) {
+        ret = dh_bcrypt_error("BCryptSetProperty", status);
+        goto fail;
+    }
+    status = BCryptFinalizeKeyPair(key, 0);
+    if (!BCRYPT_SUCCESS(status)) {
+        ret = dh_bcrypt_error("BCryptFinalizeKeyPair", status);
+        goto fail;
+    }
+    status = BCryptExportKey(key, NULL, BCRYPT_DH_PUBLIC_BLOB,
+                             (PUCHAR)&public_key, sizeof(public_key), &len, 0);
+    if (!BCRYPT_SUCCESS(status)) {
+        ret = dh_bcrypt_error("BCryptExportKey", status);
+        goto fail;
+    }
+
+    if (dh->key)
+        BCryptDestroyKey(dh->key);
+    dh->key        = key;
+    dh->public_key = public_key;
+    return 0;
+
+fail:
+    BCryptDestroyKey(key);
+    return ret;
+}
+
+int ff_dh_write_public_key(FF_DH *dh, uint8_t *pub_key, int pub_key_len)
+{
+    if (!dh->key || pub_key_len < 128)
+        return AVERROR(EINVAL);
+    memset(pub_key, 0, pub_key_len - 128);
+    memcpy(pub_key + pub_key_len - 128, dh->public_key.y, 128);
+    return 0;
+}
+
+int ff_dh_compute_shared_secret_key(FF_DH *dh, const uint8_t *pub_key,
+                                    int pub_key_len, uint8_t *secret_key,
+                                    int secret_key_len)
+{
+    BCRYPT_KEY_HANDLE peer_key = NULL;
+    BCRYPT_SECRET_HANDLE secret = NULL;
+    DHKeyBlob peer_blob = dh->public_key;
+    uint8_t raw_secret[128];
+    NTSTATUS status;
+    ULONG len;
+    int i, ret;
+
+    if (!dh->key || pub_key_len != 128 || secret_key_len < 128)
+        return AVERROR(EINVAL);
+    if ((ret = dh_is_valid_public_key(pub_key, peer_blob.p)) < 0)
+        return ret;
+
+    memcpy(peer_blob.y, pub_key, 128);
+    status = BCryptImportKeyPair(dh->algorithm, NULL, BCRYPT_DH_PUBLIC_BLOB,
+                                 &peer_key, (PUCHAR)&peer_blob, 
sizeof(peer_blob), 0);
+    if (!BCRYPT_SUCCESS(status))
+        return dh_bcrypt_error("BCryptImportKeyPair", status);
+
+    status = BCryptSecretAgreement(dh->key, peer_key, &secret, 0);
+    if (!BCRYPT_SUCCESS(status)) {
+        ret = dh_bcrypt_error("BCryptSecretAgreement", status);
+        goto fail;
+    }
+    /* BCRYPT_KDF_RAW_SECRET is hidden by headers targeting older Windows. */
+    status = BCryptDeriveKey(secret, L"TRUNCATE", NULL,
+                             raw_secret, sizeof(raw_secret), &len, 0);
+    if (!BCRYPT_SUCCESS(status)) {
+        ret = dh_bcrypt_error("BCryptDeriveKey", status);
+        av_log(NULL, AV_LOG_ERROR,
+               "RTMPE with CNG requires raw DH secret derivation support "
+               "(Windows 8.1 or later).\n");
+        goto fail;
+    }
+    if (len != sizeof(raw_secret)) {
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
+    }
+
+    /* CNG returns little-endian bytes. Match GMP's unpadded big-endian
+     * integer followed by zeroes, as RTMPE uses the entire buffer. */
+    while (len > 0 && !raw_secret[len - 1])
+        len--;
+    memset(secret_key, 0, secret_key_len);
+    for (i = 0; i < len; i++)
+        secret_key[i] = raw_secret[len - i - 1];
+    ret = secret_key_len;
+
+fail:
+    SecureZeroMemory(raw_secret, sizeof(raw_secret));
+    if (secret)
+        BCryptDestroySecret(secret);
+    BCryptDestroyKey(peer_key);
+    return ret;
+}
+
+#endif
diff --git a/libavformat/tests/rtmpdh.c b/libavformat/tests/rtmpdh.c
index f634e47a667..85d618957ad 100644
--- a/libavformat/tests/rtmpdh.c
+++ b/libavformat/tests/rtmpdh.c
@@ -24,6 +24,23 @@
 
 static int set_key(FF_DH *dh, const char *priv, const char *pub)
 {
+#if USE_BCRYPT
+    struct {
+        DHKeyBlob public_key;
+        uint8_t private_key[128];
+    } blob = { .public_key = dh->public_key };
+    NTSTATUS status;
+
+    blob.public_key.header.dwMagic = BCRYPT_DH_PRIVATE_MAGIC;
+    ff_hex_to_data(blob.public_key.y + 128 - strlen(pub) / 2, pub);
+    ff_hex_to_data(blob.private_key + 128 - strlen(priv) / 2, priv);
+    status = BCryptImportKeyPair(dh->algorithm, NULL, BCRYPT_DH_PRIVATE_BLOB,
+                                 &dh->key, (PUCHAR)&blob, sizeof(blob), 0);
+    SecureZeroMemory(blob.private_key, sizeof(blob.private_key));
+    if (!BCRYPT_SUCCESS(status))
+        return dh_bcrypt_error("BCryptImportKeyPair", status);
+    memcpy(dh->public_key.y, blob.public_key.y, 128);
+#else
     int ret;
 
     bn_hex2bn(dh->priv_key, priv, ret);
@@ -32,6 +49,7 @@ static int set_key(FF_DH *dh, const char *priv, const char 
*pub)
     bn_hex2bn(dh->pub_key, pub, ret);
     if (!ret)
         return AVERROR(ENOMEM);
+#endif
     return 0;
 }
 
@@ -40,7 +58,7 @@ static int test_random_shared_secret(void)
     FF_DH *peer1 = NULL, *peer2 = NULL;
     int ret;
     uint8_t pubkey1[128], pubkey2[128];
-    uint8_t sharedkey1[128], sharedkey2[128];
+    uint8_t sharedkey1[128] = { 0 }, sharedkey2[128] = { 0 };
 
     peer1 = ff_dh_init(1024);
     peer2 = ff_dh_init(1024);
@@ -219,6 +237,90 @@ fail:
     return ret;
 }
 
+static int test_short_shared_secret(void)
+{
+    static const int bits[] = { 2, 500, 504, 508 };
+    FF_DH *dh = ff_dh_init(1024);
+    uint8_t pub[128], secret[128], expected[128];
+    int i, ret = AVERROR(ENOMEM);
+
+    if (!dh)
+        return ret;
+    if ((ret = set_key(dh, "02", "04")) < 0)
+        goto fail;
+
+    memset(expected, 0, sizeof(expected));
+    expected[127] = 4;
+    memset(pub, 0xa5, sizeof(pub));
+    if ((ret = ff_dh_write_public_key(dh, pub, sizeof(pub))) < 0)
+        goto fail;
+    if (memcmp(pub, expected, sizeof(pub))) {
+        printf("Mismatched padded public key\n");
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
+    }
+
+    for (i = 0; i < FF_ARRAY_ELEMS(bits); i++) {
+        memset(pub, 0, sizeof(pub));
+        pub[127 - bits[i] / 8] = 1 << (bits[i] % 8);
+        memset(expected, 0, sizeof(expected));
+#if CONFIG_MBEDTLS && !CONFIG_GMP && !CONFIG_GCRYPT && !CONFIG_OPENSSL
+        expected[127 - 2 * bits[i] / 8] = 1 << (2 * bits[i] % 8);
+#else
+        expected[0] = 1 << (2 * bits[i] % 8);
+#endif
+        /* OpenSSL and gcrypt leave the unused tail to the caller. */
+#if CONFIG_GMP || USE_BCRYPT
+        memset(secret, 0xa5, sizeof(secret));
+#else
+        memset(secret, 0, sizeof(secret));
+#endif
+        ret = ff_dh_compute_shared_secret_key(dh, pub, sizeof(pub), secret, 
sizeof(secret));
+        if (ret < 0)
+            goto fail;
+        if (ret != sizeof(secret) || memcmp(secret, expected, sizeof(secret))) 
{
+            printf("Mismatched shared secret for public key 2^%d\n", bits[i]);
+            ret = AVERROR_INVALIDDATA;
+            goto fail;
+        }
+    }
+    ret = 0;
+fail:
+    ff_dh_free(dh);
+    return ret;
+}
+
+#if USE_BCRYPT
+static int test_bcrypt_errors(void)
+{
+    FF_DH *dh = ff_dh_init(1024);
+    uint8_t pub[129] = { 0 }, secret[128];
+    int ret = AVERROR(ENOMEM);
+
+    if (!dh)
+        return ret;
+    if (ff_dh_write_public_key(dh, pub, 128) != AVERROR(EINVAL) ||
+        ff_dh_compute_shared_secret_key(dh, pub, 128, secret, 128) != 
AVERROR(EINVAL)) {
+        ret = AVERROR_INVALIDDATA;
+        goto fail;
+    }
+    if ((ret = ff_dh_generate_public_key(dh)) < 0 ||
+        (ret = ff_dh_generate_public_key(dh)) < 0)
+        goto fail;
+    pub[127] = 4;
+    if (ff_dh_write_public_key(dh, pub, 127) != AVERROR(EINVAL) ||
+        ff_dh_compute_shared_secret_key(dh, pub, 127, secret, 128) != 
AVERROR(EINVAL) ||
+        ff_dh_compute_shared_secret_key(dh, pub, 129, secret, 128) != 
AVERROR(EINVAL) ||
+        ff_dh_compute_shared_secret_key(dh, pub, 128, secret, 127) != 
AVERROR(EINVAL))
+        ret = AVERROR_INVALIDDATA;
+fail:
+    if (ret < 0)
+        printf("BCrypt DH error handling test failed\n");
+    ff_dh_free(dh);
+    return ret;
+}
+#endif
+
 int main(void)
 {
     avformat_network_init();
@@ -228,5 +330,11 @@ int main(void)
         return 1;
     if (test_public_keys() < 0)
         return 1;
+    if (test_short_shared_secret() < 0)
+        return 1;
+#if USE_BCRYPT
+    if (test_bcrypt_errors() < 0)
+        return 1;
+#endif
     return 0;
 }
diff --git a/libavformat/version.h b/libavformat/version.h
index f4a26c28709..a2929069480 100644
--- a/libavformat/version.h
+++ b/libavformat/version.h
@@ -32,7 +32,7 @@
 #include "version_major.h"
 
 #define LIBAVFORMAT_VERSION_MINOR  20
-#define LIBAVFORMAT_VERSION_MICRO 101
+#define LIBAVFORMAT_VERSION_MICRO 102
 
 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
                                                LIBAVFORMAT_VERSION_MINOR, \
-- 
2.54.0

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to