Commit 66b6d3fe06 for openssl.org

commit 66b6d3fe06c4c2666d499f69bdd837eedbcd2558
Author: Dmitry Belyavskiy <beldmit@gmail.com>
Date:   Fri Oct 2 16:52:41 2026 +0200

    Add multi-derive mode to openssl-kdf command

    Add -multi and -purpose options to the openssl kdf command, enabling
    CLI testing of EVP_KDF_derive_SKEYs multi-key derivation. In multi
    mode, individual keys are retrieved via EVP_KDF_CTX_get1_SKEY and IVs
    via EVP_KDF_CTX_get0_IV using the specified purpose string.

    Add 6 CLI tests covering all TLS 1.2 purpose strings with known
    expected values. Update openssl-kdf.pod.in with option documentation
    and a multi-derive example.

    Assisted-By: Claude Opus 4.6 <noreply@anthropic.com>

    Reviewed-by: Mounir Idrassi <mounir.idrassi@idrix.fr>
    Reviewed-by: Simo Sorce <simo@redhat.com>
    MergeDate: Wed Nov 18 12:11:51 2026
    (Merged from https://github.com/openssl/openssl/pull/33082)

diff --git a/apps/kdf.c b/apps/kdf.c
index c8674afec5..5d6386ee0d 100644
--- a/apps/kdf.c
+++ b/apps/kdf.c
@@ -27,6 +27,8 @@ typedef enum OPTION_choice {
     OPT_CIPHER,
     OPT_DIGEST,
     OPT_MAC,
+    OPT_MULTI,
+    OPT_PURPOSE,
     OPT_PROV_ENUM
 } OPTION_CHOICE;

@@ -41,6 +43,9 @@ const OPTIONS kdf_options[] = {
     { "mac", OPT_MAC, 's', "MAC" },
     { OPT_MORE_STR, 1, '-', "See 'Supported Controls' in the EVP_KDF_ docs\n" },
     { "keylen", OPT_KEYLEN, 'p', "The size of the output derived key" },
+    { "multi", OPT_MULTI, '-', "Use multi-key derivation" },
+    { "purpose", OPT_PURPOSE, 's',
+        "Purpose string for retrieving a specific key or IV from multi-derive" },

     OPT_SECTION("Output"),
     { "out", OPT_OUT, '>', "Output to filename rather than stdout" },
@@ -75,11 +80,12 @@ static char *alloc_kdf_algorithm_name(STACK_OF(OPENSSL_STRING) **optp,

 int kdf_main(int argc, char **argv)
 {
-    int ret = 1, out_bin = 0;
+    int ret = 1, out_bin = 0, multi = 0;
     OPTION_CHOICE o;
     STACK_OF(OPENSSL_STRING) *opts = NULL;
     char *prog, *hexout = NULL;
     const char *outfile = NULL;
+    const char *purpose = NULL;
     unsigned char *dkm_bytes = NULL;
     int dkm_len = 0;
     BIO *out = NULL;
@@ -131,6 +137,12 @@ int kdf_main(int argc, char **argv)
             if (mac == NULL)
                 goto opthelp;
             break;
+        case OPT_MULTI:
+            multi = 1;
+            break;
+        case OPT_PURPOSE:
+            purpose = opt_arg();
+            break;
         case OPT_PROV_CASES:
             if (!opt_provider(o))
                 goto err;
@@ -144,6 +156,16 @@ int kdf_main(int argc, char **argv)
     if (argc != 1)
         goto opthelp;

+    /* Validate option combinations */
+    if (purpose != NULL && !multi) {
+        BIO_puts(bio_err, "-purpose requires -multi\n");
+        goto opthelp;
+    }
+    if (multi && dkm_len > 0) {
+        BIO_puts(bio_err, "-keylen cannot be used with -multi\n");
+        goto opthelp;
+    }
+
     if ((kdf = EVP_KDF_fetch(app_get0_libctx(), argv[0],
              app_get0_propq()))
         == NULL) {
@@ -176,17 +198,61 @@ int kdf_main(int argc, char **argv)
     if (out == NULL)
         goto err;

-    if (dkm_len <= 0) {
-        BIO_puts(bio_err, "Derived key length is mandatory!\n");
-        goto err;
-    }
-    dkm_bytes = app_malloc(dkm_len, "out buffer");
-    if (dkm_bytes == NULL)
-        goto err;
+    if (multi) {
+        EVP_SKEY *skey = NULL;
+        const unsigned char *raw = NULL;
+        const unsigned char *iv = NULL;
+        size_t len = 0;

-    if (!EVP_KDF_derive(ctx, dkm_bytes, dkm_len, NULL)) {
-        BIO_puts(bio_err, "EVP_KDF_derive failed\n");
-        goto err;
+        if (purpose == NULL) {
+            BIO_puts(bio_err, "Multi-derive requires -purpose\n");
+            goto err;
+        }
+
+        if (!EVP_KDF_derive_SKEYs(ctx, NULL)) {
+            BIO_puts(bio_err, "EVP_KDF_derive_SKEYs failed\n");
+            goto err;
+        }
+
+        skey = EVP_KDF_CTX_get1_SKEY(ctx, purpose, app_get0_propq());
+        if (skey != NULL) {
+            if (!EVP_SKEY_get0_raw_key(skey, &raw, &len)) {
+                BIO_puts(bio_err, "Failed to get raw key bytes\n");
+                EVP_SKEY_free(skey);
+                goto err;
+            }
+            dkm_bytes = app_malloc(len, "out buffer");
+            if (dkm_bytes == NULL) {
+                EVP_SKEY_free(skey);
+                goto err;
+            }
+            memcpy(dkm_bytes, raw, len);
+            dkm_len = (int)len;
+            EVP_SKEY_free(skey);
+        } else if (EVP_KDF_CTX_get0_IV(ctx, purpose, &iv, &len)) {
+            dkm_bytes = app_malloc(len, "out buffer");
+            if (dkm_bytes == NULL)
+                goto err;
+            memcpy(dkm_bytes, iv, len);
+            dkm_len = (int)len;
+        } else {
+            BIO_printf(bio_err, "Failed to get key or IV for purpose '%s'\n",
+                purpose);
+            goto err;
+        }
+    } else {
+        if (dkm_len <= 0) {
+            BIO_puts(bio_err, "Derived key length is mandatory!\n");
+            goto err;
+        }
+        dkm_bytes = app_malloc(dkm_len, "out buffer");
+        if (dkm_bytes == NULL)
+            goto err;
+
+        if (!EVP_KDF_derive(ctx, dkm_bytes, dkm_len, NULL)) {
+            BIO_puts(bio_err, "EVP_KDF_derive failed\n");
+            goto err;
+        }
     }

     if (out_bin) {
diff --git a/doc/man1/openssl-kdf.pod.in b/doc/man1/openssl-kdf.pod.in
index 61113846c8..ac15b9858b 100644
--- a/doc/man1/openssl-kdf.pod.in
+++ b/doc/man1/openssl-kdf.pod.in
@@ -14,6 +14,8 @@ B<openssl kdf>
 [B<-mac>]
 [B<-kdfopt> I<nm>:I<v>]
 [B<-keylen> I<num>]
+[B<-multi>]
+[B<-purpose> I<string>]
 [B<-out> I<filename>]
 [B<-binary>]
 {- $OpenSSL::safe::opt_provider_synopsis -}
@@ -34,7 +36,36 @@ Print a usage message.

 =item B<-keylen> I<num>

-The output size of the derived key. This field is required.
+The output size of the derived key. This field is required unless B<-multi> is used.
+
+=item B<-multi>
+
+Use multi-key derivation mode. Instead of deriving a single key buffer via
+EVP_KDF_derive(), this calls EVP_KDF_derive_SKEYs() to derive multiple keys
+and IVs simultaneously. The B<-purpose> option must be specified to select
+which derived key or IV to output.
+
+The KDF-specific size parameters (e.g., B<mac_key_len>, B<cipher_key_len>,
+B<iv_len> for TLS1-PRF) should be passed via B<-kdfopt>.
+
+B<-cipher> and B<-mac> name the algorithms the derived keys are for, rather
+than any algorithm the KDF itself uses. The provider takes the cipher key
+length from the named cipher, so B<cipher_key_len> is then unnecessary and it
+is an error to give one that contradicts it. A MAC does not determine its own
+key length, so B<mac_key_len> is still required.
+
+=item B<-purpose> I<string>
+
+Specifies which key or IV to retrieve from a multi-key derivation.
+Must be used together with B<-multi>.
+The available purpose strings depend on the KDF algorithm; for example,
+TLS1-PRF supports B<client_MAC_key>, B<server_MAC_key>, B<client_cipher_key>,
+B<server_cipher_key>, B<client_IV>, and B<server_IV>.
+See the documentation of the specific KDF for the supported purpose strings.
+
+If the purpose identifies a key, it is retrieved via EVP_KDF_CTX_get1_SKEY()
+and its raw bytes are output. If it identifies an IV, it is retrieved via
+EVP_KDF_CTX_get0_IV().

 =item B<-out> I<filename>

@@ -152,6 +183,33 @@ Use TLS1-PRF to create a hex-encoded derived key from a secret key and seed:
     openssl kdf -keylen 16 -kdfopt digest:SHA2-256 -kdfopt key:secret \
                 -kdfopt seed:seed TLS1-PRF

+Use TLS1-PRF multi-key derivation to extract the client cipher key from a
+TLS 1.2 key block (with 10-byte MAC keys, 16-byte cipher keys, and 6-byte IVs):
+
+    openssl kdf -multi -kdfopt digest:SHA2-256 -kdfopt secret:secret \
+                -kdfopt seed:seed -kdfopt mac_key_len:10 \
+                -kdfopt cipher_key_len:16 -kdfopt iv_len:6 \
+                -purpose client_cipher_key TLS1-PRF
+
+Name the cipher and MAC the keys are for instead of giving the cipher key
+length. AES-128-CBC states that its key is 16 bytes, so this derives the same
+client cipher key as the command above:
+
+    openssl kdf -multi -kdfopt digest:SHA2-256 -kdfopt secret:secret \
+                -kdfopt seed:seed -cipher AES-128-CBC -mac HMAC \
+                -kdfopt mac_key_len:10 -kdfopt iv_len:6 \
+                -purpose client_cipher_key TLS1-PRF
+
+Naming the cipher also decides the type of the derived key: with the default
+provider the command above yields an AES key, where leaving the cipher out
+yields a generic secret. Switching to AES-256-CBC derives a 32-byte key from
+the same command, and because the key block grows the IVs move with it:
+
+    openssl kdf -multi -kdfopt digest:SHA2-256 -kdfopt secret:secret \
+                -kdfopt seed:seed -cipher AES-256-CBC -mac HMAC \
+                -kdfopt mac_key_len:10 -kdfopt iv_len:6 \
+                -purpose server_iv TLS1-PRF
+
 Use HKDF to create a hex-encoded derived key from a secret key, salt and info:

     openssl kdf -keylen 10 -kdfopt digest:SHA2-256 -kdfopt key:secret \
diff --git a/test/recipes/20-test_kdf.t b/test/recipes/20-test_kdf.t
index 3f6a1e7ab8..86cdd9d6e8 100755
--- a/test/recipes/20-test_kdf.t
+++ b/test/recipes/20-test_kdf.t
@@ -88,6 +88,65 @@ my @krb5kdf_tests = (
       desc => 'KRB5KDF AES-128-CBC'},
 );

+my @multi_common = (qw{openssl kdf -multi -digest SHA256
+    -kdfopt secret:secret -kdfopt seed:seed
+    -kdfopt mac_key_len:10 -kdfopt cipher_key_len:16 -kdfopt iv_len:6});
+
+my @kdf_multi_tests = (
+    { cmd => [@multi_common, '-purpose', 'client_MAC_key', 'TLS1-PRF'],
+      expected => '8E:4D:93:25:30:D7:65:A0:AA:E9',
+      desc => 'TLS1-PRF multi-derive client_MAC_key' },
+    { cmd => [@multi_common, '-purpose', 'server_MAC_key', 'TLS1-PRF'],
+      expected => '74:C3:04:73:5E:CC:12:02:A8:19',
+      desc => 'TLS1-PRF multi-derive server_MAC_key' },
+    { cmd => [@multi_common, '-purpose', 'client_cipher_key', 'TLS1-PRF'],
+      expected => 'F8:0A:DB:D5:AD:09:C1:A3:4F:C0:69:18:E3:D0:77:95',
+      desc => 'TLS1-PRF multi-derive client_cipher_key' },
+    { cmd => [@multi_common, '-purpose', 'server_cipher_key', 'TLS1-PRF'],
+      expected => '21:4D:94:C6:A1:97:6C:AE:A5:A0:B6:44:C5:B0:4D:1A',
+      desc => 'TLS1-PRF multi-derive server_cipher_key' },
+    { cmd => [@multi_common, '-purpose', 'client_iv', 'TLS1-PRF'],
+      expected => 'D3:E0:9C:61:11:C3',
+      desc => 'TLS1-PRF multi-derive client_iv' },
+    { cmd => [@multi_common, '-purpose', 'server_iv', 'TLS1-PRF'],
+      expected => '7A:FC:00:DF:0B:6D',
+      desc => 'TLS1-PRF multi-derive server_iv' },
+);
+
+# Naming the cipher the keys are for tells the provider how long the cipher
+# key is, so cipher_key_len need not be given.  A MAC does not determine its
+# own key length, so mac_key_len is still required.
+my @alg_common = (qw{openssl kdf -multi -digest SHA256
+    -kdfopt secret:secret -kdfopt seed:seed
+    -kdfopt mac_key_len:10 -kdfopt iv_len:6});
+
+my @kdf_multi_alg_tests = (
+    # Same value as the cipher_key_len:16 test above, reached via the cipher name
+    { cmd => [@alg_common, qw{-cipher AES-128-CBC -purpose client_cipher_key TLS1-PRF}],
+      expected => 'F8:0A:DB:D5:AD:09:C1:A3:4F:C0:69:18:E3:D0:77:95',
+      desc => 'TLS1-PRF multi-derive takes the key length from AES-128-CBC' },
+    { cmd => [@alg_common, qw{-cipher AES-256-CBC -purpose client_cipher_key TLS1-PRF}],
+      expected => 'F8:0A:DB:D5:AD:09:C1:A3:4F:C0:69:18:E3:D0:77:95:'
+                  . '21:4D:94:C6:A1:97:6C:AE:A5:A0:B6:44:C5:B0:4D:1A',
+      desc => 'TLS1-PRF multi-derive takes the key length from AES-256-CBC' },
+    { cmd => [@alg_common, qw{-cipher AES-128-CBC -mac HMAC
+                              -purpose client_MAC_key TLS1-PRF}],
+      expected => '8E:4D:93:25:30:D7:65:A0:AA:E9',
+      desc => 'TLS1-PRF multi-derive MAC key length still comes from mac_key_len' },
+    # A longer cipher key moves the IVs further down the key block
+    { cmd => [@alg_common, qw{-cipher AES-256-CBC -purpose server_iv TLS1-PRF}],
+      expected => '6E:5D:B1:41:53:72',
+      desc => 'TLS1-PRF multi-derive IV placement follows the cipher key length' },
+);
+
+my @kdf_multi_fail_tests = (
+    { cmd => [@alg_common, qw{-cipher AES-128-CBC -kdfopt cipher_key_len:10
+                              -purpose client_cipher_key TLS1-PRF}],
+      desc => 'TLS1-PRF multi-derive rejects a length the named cipher cannot take' },
+    { cmd => [@alg_common, qw{-cipher AES-128-CBC -purpose nonexistent TLS1-PRF}],
+      desc => 'TLS1-PRF multi-derive rejects an unknown purpose' },
+);
+
 my @kdf_bin_tests = (
     { cmd => [qw{openssl kdf -keylen 10 -binary -out hkdf-sha256.bin -kdfopt digest:SHA256 -kdfopt key:secret -kdfopt salt:salt -kdfopt info:label HKDF}],
       outfile => 'hkdf-sha256.bin',
@@ -106,12 +165,26 @@ push @kdf_tests, @scrypt_tests unless disabled("scrypt");
 push @kdf_tests, @sshkdf_tests unless disabled("sshkdf");
 push @kdf_tests, @sskdf_tests unless disabled("sskdf");

-plan tests => scalar @kdf_tests + scalar @kdf_bin_tests;
+plan tests => scalar @kdf_tests + scalar @kdf_multi_tests
+    + scalar @kdf_multi_alg_tests + scalar @kdf_multi_fail_tests
+    + scalar @kdf_bin_tests;

 foreach (@kdf_tests) {
     ok(compareline($_->{cmd}, $_->{expected}), $_->{desc});
 }

+foreach (@kdf_multi_tests) {
+    ok(compareline($_->{cmd}, $_->{expected}), $_->{desc});
+}
+
+foreach (@kdf_multi_alg_tests) {
+    ok(compareline($_->{cmd}, $_->{expected}), $_->{desc});
+}
+
+foreach (@kdf_multi_fail_tests) {
+    ok(checkfail($_->{cmd}), $_->{desc});
+}
+
 foreach (@kdf_bin_tests) {
     ok(comparebinary($_->{cmd}, $_->{outfile}, $_->{expected}), $_->{desc});
 }
@@ -137,6 +210,15 @@ sub compareline {
     return 0;
 }

+# Check that the command fails rather than producing output.
+sub checkfail {
+    my ($cmdarray) = @_;
+    my $status = 1;
+
+    run(app($cmdarray), capture => 1, statusvar => \$status);
+    return !$status;
+}
+
 # Check that the binary output file matches the expected value.
 sub comparebinary {
     my ($cmdarray, $outfile, $expect) = @_;