Skip to content

Commit ed4d6e6

Browse files
Ensure fds are closed after exiting ioctl (#7061)
Co-authored-by: Amaury Chamayou <amchamay@microsoft.com>
1 parent ebc77e7 commit ed4d6e6

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

include/ccf/ds/nonstd.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <string>
99
#include <string_view>
1010
#include <type_traits>
11+
#include <unistd.h>
1112
#include <vector>
1213

1314
#define FMT_HEADER_ONLY
@@ -203,4 +204,18 @@ namespace ccf::nonstd
203204
tuple_for_each<I + 1>(t, f);
204205
}
205206
}
207+
208+
static void close_fd(int* fd)
209+
{
210+
if (fd != nullptr && *fd >= 0)
211+
{
212+
close(*fd);
213+
*fd = -1;
214+
}
215+
}
216+
using CloseFdGuard = std::unique_ptr<int, decltype(&close_fd)>;
217+
static inline CloseFdGuard make_close_fd_guard(int* fd)
218+
{
219+
return CloseFdGuard(fd, close_fd);
220+
}
206221
}

include/ccf/pal/snp_ioctl5.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the Apache 2.0 License.
33
#pragma once
44

5+
#include "ccf/ds/nonstd.h"
56
#include "ccf/pal/attestation_sev_snp.h"
67

78
#include <fcntl.h>
@@ -106,8 +107,10 @@ namespace ccf::pal::snp::ioctl5
106107
int fd = open(DEVICE, O_RDWR | O_CLOEXEC);
107108
if (fd < 0)
108109
{
109-
throw std::logic_error(fmt::format("Failed to open \"{}\"", DEVICE));
110+
throw std::logic_error(
111+
fmt::format("Failed to open \"{}\" ({})", DEVICE, fd));
110112
}
113+
auto close_guard = nonstd::make_close_fd_guard(&fd);
111114

112115
// Documented at
113116
// https://www.kernel.org/doc/html/latest/virt/coco/sev-guest.html

include/ccf/pal/snp_ioctl6.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the Apache 2.0 License.
33
#pragma once
44

5+
#include "ccf/ds/nonstd.h"
56
#include "ccf/pal/attestation_sev_snp.h"
67

78
#include <algorithm>
@@ -229,6 +230,7 @@ namespace ccf::pal::snp::ioctl6
229230
throw std::logic_error(
230231
fmt::format("Failed to open \"{}\" ({})", DEVICE, fd));
231232
}
233+
auto close_guard = nonstd::make_close_fd_guard(&fd);
232234

233235
// Documented at
234236
// https://www.kernel.org/doc/html/latest/virt/coco/sev-guest.html
@@ -283,6 +285,7 @@ namespace ccf::pal::snp::ioctl6
283285
throw std::logic_error(
284286
fmt::format("Failed to open \"{}\" ({})", DEVICE, fd));
285287
}
288+
auto close_guard = nonstd::make_close_fd_guard(&fd);
286289

287290
// This req by default mixes in HostData and the CPU VCEK
288291
DerivedKeyReq req = {};

0 commit comments

Comments
 (0)