Blob Blame History Raw
From 68a7867198c84111bac3068c33d28e320df6a6f6 Mon Sep 17 00:00:00 2001
From: JerryDevis <seclab@huawei.com>
Date: Wed, 13 Oct 2021 11:26:03 +0800
Subject: [PATCH 08/23] Fix file descriptor leak when tcti initialization
 failed

Signed-off-by: JerryDevis <seclab@huawei.com>
---
 src/tss2-tcti/tcti-device.c | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/src/tss2-tcti/tcti-device.c b/src/tss2-tcti/tcti-device.c
index 94db070c..364297be 100644
--- a/src/tss2-tcti/tcti-device.c
+++ b/src/tss2-tcti/tcti-device.c
@@ -309,6 +309,16 @@ out:
     return rc;
 }
 
+static void close_tpm(int *fd)
+{
+    if (fd == NULL || *fd < 0) {
+        return;
+    }
+
+    close(*fd);
+    *fd = -1;
+}
+
 void
 tcti_device_finalize (
     TSS2_TCTI_CONTEXT *tctiContext)
@@ -319,7 +329,7 @@ tcti_device_finalize (
     if (tcti_dev == NULL) {
         return;
     }
-    close (tcti_dev->fd);
+    close_tpm (&tcti_dev->fd);
     tcti_common->state = TCTI_STATE_FINAL;
 }
 
@@ -455,6 +465,7 @@ Tss2_Tcti_Device_Init (
     ssize_t sz = write_all (tcti_dev->fd, cmd, sizeof(cmd));
     if (sz < 0 || sz != sizeof(cmd)) {
         LOG_ERROR ("Could not probe device for partial response read support");
+        close_tpm (&tcti_dev->fd);
         return TSS2_TCTI_RC_IO_ERROR;
     }
     LOG_DEBUG ("Command sent, reading header");
@@ -465,12 +476,14 @@ Tss2_Tcti_Device_Init (
     if (rc_poll < 0 || rc_poll == 0) {
         LOG_ERROR ("Failed to poll for response from fd %d, rc %d, errno %d: %s",
                    tcti_dev->fd, rc_poll, errno, strerror(errno));
+        close_tpm (&tcti_dev->fd);
         return TSS2_TCTI_RC_IO_ERROR;
     } else if (fds.revents == POLLIN) {
         TEMP_RETRY (sz, read (tcti_dev->fd, rsp, TPM_HEADER_SIZE));
         if (sz < 0 || sz != TPM_HEADER_SIZE) {
             LOG_ERROR ("Failed to read response header fd %d, got errno %d: %s",
                        tcti_dev->fd, errno, strerror (errno));
+            close_tpm (&tcti_dev->fd);
             return TSS2_TCTI_RC_IO_ERROR;
         }
     }
@@ -482,6 +495,7 @@ Tss2_Tcti_Device_Init (
     if (rc_poll < 0) {
         LOG_DEBUG ("Failed to poll for response from fd %d, rc %d, errno %d: %s",
                    tcti_dev->fd, rc_poll, errno, strerror(errno));
+        close_tpm (&tcti_dev->fd);
         return TSS2_TCTI_RC_IO_ERROR;
 	} else if (rc_poll == 0) {
         LOG_ERROR ("timeout waiting for response from fd %d", tcti_dev->fd);
@@ -495,7 +509,7 @@ Tss2_Tcti_Device_Init (
         LOG_DEBUG ("Failed to get response tail fd %d, got errno %d: %s",
                    tcti_dev->fd, errno, strerror (errno));
         tcti_common->partial_read_supported = 0;
-        close(tcti_dev->fd);
+        close_tpm (&tcti_dev->fd);
         tcti_dev->fd = open_tpm (used_conf);
         if (tcti_dev->fd < 0) {
             LOG_ERROR ("Failed to open specified TCTI device file %s: %s",
-- 
2.34.3