diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 7e433f9..d642a0a 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -388,7 +388,9 @@ extension IORing.Request { } @inline(__always) @inlinable - internal consuming func makeRawRequest() -> RawIORequest { + internal consuming func makeRawRequest( + pathBuffers: PendingPathBuffers + ) -> RawIORequest { var request = RawIORequest() switch extractCore() { case .nop: @@ -400,27 +402,19 @@ extension IORing.Request { request.operation = .openAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( - UInt( - bitPattern: path.withPlatformString { ptr in - ptr //this is unsavory, but we keep it alive by storing path alongside it in the request - })) + UInt(bitPattern: pathBuffers.pin(path))) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.file_index = UInt32(fileSlot.index + 1) - request.path = path request.rawValue.user_data = context case .openat( let atDirectory, let path, let mode, let options, let permissions, let context): request.operation = .openAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( - UInt( - bitPattern: path.withPlatformString { ptr in - ptr //this is unsavory, but we keep it alive by storing path alongside it in the request - })) + UInt(bitPattern: pathBuffers.pin(path))) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 - request.path = path request.rawValue.user_data = context case .write(let file, let buffer, let offset, let context): request.operation = .writeFixed @@ -466,12 +460,7 @@ extension IORing.Request { request.operation = .unlinkAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( - UInt( - bitPattern: path.withPlatformString { ptr in - ptr //this is unsavory, but we keep it alive by storing path alongside it in the request - }) - ) - request.path = path + UInt(bitPattern: pathBuffers.pin(path))) request.rawValue.user_data = context case .cancelContext(let flags, let targetContext): request.operation = .asyncCancel diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 16c85a0..3570da6 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -41,6 +41,32 @@ extension UnsafeMutableRawBufferPointer { } } +/// Owns the FilePaths whose interior pointers have been written into pending +/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to +/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap +@usableFromInline +internal final class PendingPathBuffers { + @usableFromInline + var paths: [FilePath] = [] + + init(reservedCapacity: Int) { + paths.reserveCapacity(reservedCapacity) + } + + @usableFromInline + func pin(_ path: FilePath) -> UnsafePointer { + paths.append(path) + // Safe to escape: `paths` keeps the FilePath (and its underlying + // [SystemChar] buffer) alive until clear() or class deinit. + return paths.last!.withPlatformString { $0 } + } + + @usableFromInline + func clear() { + paths.removeAll(keepingCapacity: true) + } +} + // all pointers in this struct reference kernel-visible memory @usableFromInline struct SQRing: ~Copyable { @usableFromInline let kernelHead: UnsafePointer> @@ -200,7 +226,14 @@ private func setUpRing( throw err } - if params.features & IORing.Features.nonDroppingCompletions.rawValue == 0 + // We require IORING_FEAT_SUBMIT_STABLE so the kernel copies SQE-referenced + // pathnames (and other inline data) out of userspace before io_uring_enter + // returns; the path-buffer side store on IORing relies on this to free + // path buffers as soon as a submission completes. + let requiredFeatures = + IORing.Features.nonDroppingCompletions.rawValue + | IORing.Features.stableSubmissions.rawValue + if params.features & requiredFeatures != requiredFeatures { close(ringDescriptor) throw Errno.invalidArgument @@ -324,6 +357,8 @@ public struct IORing: ~Copyable { @usableFromInline var _registeredFiles: [UInt32] @usableFromInline var _registeredBuffers: [iovec] + @usableFromInline let _pendingPathBuffers: PendingPathBuffers + var features = Features(rawValue: 0) /// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them. @@ -444,6 +479,7 @@ public struct IORing: ~Copyable { self.completionRingSize = tmpCQSize self._registeredFiles = [] self._registeredBuffers = [] + self._pendingPathBuffers = PendingPathBuffers(reservedCapacity: Int(params.sq_entries)) self.submissionRing = submissionRing self.completionRing = completionRing self.submissionQueueEntries = submissionQueueEntries @@ -765,6 +801,10 @@ public struct IORing: ~Copyable { @inlinable public func submitPreparedRequests() throws(Errno) { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) + // IORING_FEAT_SUBMIT_STABLE guarantees the kernel has copied any + // SQE-referenced data (e.g. openat/unlinkAt pathnames) before + // io_uring_enter returns; safe to release path storage now. + _pendingPathBuffers.clear() } /// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available. @@ -790,9 +830,14 @@ public struct IORing: ~Copyable { /// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request @inlinable public mutating func prepare(request: __owned Request) -> Bool { - var raw: RawIORequest? = request.makeRawRequest() - return _tryWriteRequest( + guard _getRemainingSubmissionQueueCapacity(ring: submissionRing) >= 1 else { + return false + } + var raw: RawIORequest? = request.makeRawRequest(pathBuffers: _pendingPathBuffers) + let ok = _tryWriteRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + assert(ok) + return ok } /// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. @@ -806,18 +851,20 @@ public struct IORing: ~Copyable { return false } let last = linkedRequests.last! + var allAdded = true for req in linkedRequests.dropLast() { - var raw = req.makeRawRequest() + var raw = req.makeRawRequest(pathBuffers: _pendingPathBuffers) raw.linkToNextRequest() let successfullyAdded = _tryWriteRequest( raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) assert(successfullyAdded) + allAdded = allAdded && successfullyAdded } let successfullyAdded = _tryWriteRequest( - last.makeRawRequest(), ring: &submissionRing, + last.makeRawRequest(pathBuffers: _pendingPathBuffers), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) assert(successfullyAdded) - return true + return allAdded && successfullyAdded } /// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space. diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index 0bc4029..c9b80dc 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -8,7 +8,6 @@ internal struct RawIORequest: ~Copyable { // swift_io_uring_sqe is a typedef of io_uring_sqe on platforms where // IORing is supported (currently requires kernel version >= 5.15). @usableFromInline var rawValue: swift_io_uring_sqe - @usableFromInline var path: FilePath? //buffer owner for the path pointer that the sqe may have @inlinable public init() { self.rawValue = swift_io_uring_sqe() diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 9246d39..773a90c 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -22,7 +22,8 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { // which are known to work correctly. final class IORequestTests: XCTestCase { func testNop() { - let req = IORing.Request.nop().makeRawRequest() + let req = IORing.Request.nop().makeRawRequest( + pathBuffers: PendingPathBuffers(reservedCapacity: 0)) let sourceBytes = requestBytes(req) // convenient property of nop: it's all zeros! // for some unknown reason, liburing sets the fd field to -1. diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index c5d54d4..e001e69 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -127,6 +127,81 @@ final class IORingTests: XCTestCase { efdBuf.deallocate() rawBuffer.deallocate() } + + // Prior to the fix this is testing, prepare() escaped a pointer obtained + // inside `path.withPlatformString { ... }` into the SQE and dropped the + // owning FilePath before submit, so io_uring_enter handed the kernel a + // dangling pointer. Here we deliberately let the FilePath go out of scope + // between prepare and submit, then churn the heap to make UAFs observable. + func testPathBufferLifetimeAcrossPrepareSubmit() throws { + guard try uringEnabled() else { return } + let (parent, _) = try makeHelloWorldFile() + var ring = try IORing(queueDepth: 6) + + func enqueueOpen() { + let path: FilePath = "/tmp/IORingTests/test.txt" + let ok = ring.prepare(request: .open(path, in: parent, mode: .readOnly)) + XCTAssertTrue(ok) + } + enqueueOpen() + + var churn: [UnsafeMutableRawBufferPointer] = [] + for _ in 0..<256 { + let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1) + memset(buf.baseAddress!, 0x41, 64) + churn.append(buf) + } + for buf in churn { buf.deallocate() } + churn.removeAll() + + try ring.submitPreparedRequests() + let completion = try ring.blockingConsumeCompletion() + XCTAssertGreaterThanOrEqual( + completion.result, 0, + "open should succeed; got \(completion.result)") + + if completion.result >= 0 { + let fd = FileDescriptor(rawValue: Int32(completion.result)) + try fd.close() + } + try cleanUpHelloWorldFile(parent) + } + + func testPathBufferLifetimeAcrossLinkedRequests() throws { + guard try uringEnabled() else { return } + let (parent, _) = try makeHelloWorldFile() + let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) + var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) + + func enqueueLinkedReadback() { + let path: FilePath = "/tmp/IORingTests/test.txt" + let ok = ring.prepare(linkedRequests: + .open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly), + .read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]), + .close(ring.registeredFileSlots[0])) + XCTAssertTrue(ok) + } + enqueueLinkedReadback() + + var churn: [UnsafeMutableRawBufferPointer] = [] + for _ in 0..<256 { + let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 1) + memset(buf.baseAddress!, 0x41, 64) + churn.append(buf) + } + for buf in churn { buf.deallocate() } + + try ring.submitPreparedRequests() + _ = try ring.blockingConsumeCompletion() // open + _ = try ring.blockingConsumeCompletion() // read + _ = try ring.blockingConsumeCompletion() // close + + let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) + XCTAssertEqual(result, "Hello, World!") + + try cleanUpHelloWorldFile(parent) + rawBuffer.deallocate() + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes