From 766e6cda8af38d4ef4194b283b3043b1dd056c5d Mon Sep 17 00:00:00 2001 From: Viktor Dukhovni Date: Tue, 22 Aug 2017 21:56:19 +0000 Subject: [PATCH] Avoid potential memory leak in krb5_sendto_set_hostname If the hostname was already set, a typo in a test meant we were not freeing it. While we're at it, handle the unlikely possibility that the existing pointer is passed as the new value. --- lib/krb5/send_to_kdc.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/krb5/send_to_kdc.c b/lib/krb5/send_to_kdc.c index 066b849a7..c92a5978a 100644 --- a/lib/krb5/send_to_kdc.c +++ b/lib/krb5/send_to_kdc.c @@ -228,13 +228,19 @@ krb5_sendto_set_hostname(krb5_context context, krb5_sendto_ctx ctx, const char *hostname) { - if (ctx->hostname == NULL) - free(ctx->hostname); - ctx->hostname = strdup(hostname); - if (ctx->hostname == NULL) { + char *newname; + + /* + * Handle the case where hostname == ctx->hostname by copying it first, and + * disposing of any previous value after. + */ + newname = strdup(hostname); + if (newname == NULL) { krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "")); return ENOMEM; } + free(ctx->hostname); + ctx->hostname = newname; return 0; }