From 6bc90214830cb5239aa397c20763902f10f11786 Mon Sep 17 00:00:00 2001
From: ChenChen Zhou <357726167@qq.com>
Date: Sun, 27 Nov 2022 22:57:14 +0800
Subject: [PATCH] Fix gic_keytab crash on memory exhaustion

get_as_key_keytab() does not check the result of krb5_copy_keyblock(),
and dereferences a null pointer if it fails.  Remove the call and
steal the memory from kt_ent instead.

[ghudson@mit.edu: rewrote commit message; fixed comments]

ticket: 9080 (new)
---
 src/lib/krb5/krb/gic_keytab.c | 12 ++++--------
 1 file changed, 4 insertions(+), 8 deletions(-)

diff --git a/src/lib/krb5/krb/gic_keytab.c b/src/lib/krb5/krb/gic_keytab.c
index b8b7c1506..f9baabbf9 100644
--- a/src/lib/krb5/krb/gic_keytab.c
+++ b/src/lib/krb5/krb/gic_keytab.c
@@ -45,7 +45,6 @@ get_as_key_keytab(krb5_context context,
     krb5_keytab keytab = (krb5_keytab) gak_data;
     krb5_error_code ret;
     krb5_keytab_entry kt_ent;
-    krb5_keyblock *kt_key;
 
     /* We don't need the password from the responder to create the AS key. */
     if (as_key == NULL)
@@ -71,16 +70,13 @@ get_as_key_keytab(krb5_context context,
                                  etype, &kt_ent)))
         return(ret);
 
-    ret = krb5_copy_keyblock(context, &kt_ent.key, &kt_key);
-
-    /* again, krb5's memory management is lame... */
-
-    *as_key = *kt_key;
-    free(kt_key);
+    /* Steal the keyblock from kt_ent for the caller. */
+    *as_key = kt_ent.key;
+    memset(&kt_ent.key, 0, sizeof(kt_ent.key));
 
     (void) krb5_kt_free_entry(context, &kt_ent);
 
-    return(ret);
+    return 0;
 }
 
 /* Return the list of etypes available for client in keytab. */
-- 
2.32.0.windows.1

