Commit c3d24d9121 for openssl.org

commit c3d24d9121ef12d8b1f2615e7655e07b5a624358
Author: huanghuihui0904 <625173@qq.com>
Date:   Mon Mar 16 11:05:36 2026 +0800

    crypto/x509/pcy_tree.c: fix leak of tree in X509_policy_check()

    When init_ret indicates both X509_PCY_TREE_EXPLICIT and X509_PCY_TREE_EMPTY,
    the function returns without freeing the initialized policy tree.
    Free the tree before returning, consistent with the earlier TREE_EMPTY branch.

    Also defer *ptree = tree assignment and free the tree when user policies
    are empty to avoid returning invalid memory.

    Fixes #30435

    Signed-off-by: huanghuihui0904 <625173@qq.com>

    Reviewed-by: Frederik Wedel-Heinen <fwh.openssl@gmail.com>
    Reviewed-by: Eugene Syromiatnikov <esyr@openssl.org>
    MergeDate: Fri Apr  3 15:03:37 2026
    (Merged from https://github.com/openssl/openssl/pull/30436)

diff --git a/crypto/x509/pcy_tree.c b/crypto/x509/pcy_tree.c
index cdf39ba5c7..ea3f8ae20b 100644
--- a/crypto/x509/pcy_tree.c
+++ b/crypto/x509/pcy_tree.c
@@ -680,8 +680,10 @@ int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy,
     } else {
         *pexplicit_policy = 1;
         /* Tree empty and requireExplicit True: Error */
-        if (init_ret & X509_PCY_TREE_EMPTY)
+        if (init_ret & X509_PCY_TREE_EMPTY) {
+            X509_policy_tree_free(tree);
             return X509_PCY_TREE_FAILURE;
+        }
     }

     ret = tree_evaluate(tree);
@@ -707,13 +709,15 @@ int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy,
     if (!ret)
         goto error;

-    *ptree = tree;
-
     if (init_ret & X509_PCY_TREE_EXPLICIT) {
         nodes = X509_policy_tree_get0_user_policies(tree);
-        if (sk_X509_POLICY_NODE_num(nodes) <= 0)
+        if (sk_X509_POLICY_NODE_num(nodes) <= 0) {
+            X509_policy_tree_free(tree);
             return X509_PCY_TREE_FAILURE;
+        }
     }
+
+    *ptree = tree;
     return X509_PCY_TREE_VALID;

 error: