Repository navigation
Expand file tree
/
Copy pathMachineBootPayload.swift
More file actions
256 lines (234 loc) · 9.2 KB
/
Copy pathMachineBootPayload.swift
File metadata and controls
256 lines (234 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import CryptoKit
import Darwin
import Foundation
/// Exact authority for one anonymous, read-only boot blob inherited from the daemon.
///
/// `maximumByteCount` is a local allocation ceiling, not caller-controlled evidence. The child
/// validates the descriptor before allocating and uses `pread` so supervised restarts never share
/// or depend on an open-file-description offset.
public struct MachineInheritedBootBlob: Sendable, Equatable {
public let descriptor: Int32
public let byteCount: UInt64
public let sha256: String
public let maximumByteCount: UInt64
public init(
descriptor: Int32,
byteCount: UInt64,
sha256: String,
maximumByteCount: UInt64
) {
self.descriptor = descriptor
self.byteCount = byteCount
self.sha256 = sha256
self.maximumByteCount = maximumByteCount
}
}
/// Single-use ownership of resolved boot bytes.
///
/// Every `MachineBootPayload` copy shares this authority. Consumption removes the authority's
/// references before invoking the guest-memory loader and permanently retires the authority when
/// that loader returns or throws. Consequently a retained `MachineConfiguration` cannot keep a
/// second kernel/initrd copy alive or replay partially loaded resolved authority.
public final class MachineImmutableBootAuthority: @unchecked Sendable, Equatable {
private struct Bytes {
let kernel: Data
let initrd: Data?
}
private enum State {
case available(Bytes)
case consuming
case consumed
}
private let lock = NSLock()
private var state: State
fileprivate init(kernel: Data, initrd: Data?) {
self.state = .available(Bytes(kernel: kernel, initrd: initrd))
}
public static func == (
lhs: MachineImmutableBootAuthority,
rhs: MachineImmutableBootAuthority
) -> Bool {
lhs === rhs
}
fileprivate func consumeForGuestLoad(
_ load: (Data, () throws -> Data?) throws -> Void
) throws {
let bytes: Bytes
lock.lock()
switch state {
case .available(let available):
bytes = available
state = .consuming
lock.unlock()
case .consuming:
lock.unlock()
throw VMError.invalidConfiguration(
"resolved immutable boot payload is already being consumed"
)
case .consumed:
lock.unlock()
throw VMError.invalidConfiguration(
"resolved immutable boot payload has already been consumed"
)
}
defer {
lock.lock()
state = .consumed
lock.unlock()
}
try load(bytes.kernel) { bytes.initrd }
}
/// Test-visible accounting of bytes retained by the authority itself. The count becomes zero
/// before guest loading begins and remains zero after either success or failure.
var retainedByteCount: UInt64 {
lock.lock()
defer { lock.unlock() }
guard case .available(let bytes) = state else { return 0 }
return UInt64(bytes.kernel.count) + UInt64(bytes.initrd?.count ?? 0)
}
var isConsumed: Bool {
lock.lock()
defer { lock.unlock() }
guard case .consumed = state else { return false }
return true
}
}
/// A typed split between repeatable legacy pathname boot and one-shot resolved immutable-byte boot.
public enum MachineBootPayload: Sendable, Equatable {
case legacyPaths(kernel: String, initrd: String?)
case immutableBytes(authority: MachineImmutableBootAuthority)
/// Source-compatible construction spelling for callers with already-verified bytes. Copies of
/// the returned enum share one consumable authority rather than retaining independent `Data`.
public static func immutableBytes(kernel: Data, initrd: Data?) -> Self {
.immutableBytes(
authority: MachineImmutableBootAuthority(kernel: kernel, initrd: initrd)
)
}
public static func inheritedReadOnlyDescriptors(
kernel: MachineInheritedBootBlob,
initrd: MachineInheritedBootBlob?
) throws -> Self {
var descriptors = [kernel.descriptor]
if let initrd { descriptors.append(initrd.descriptor) }
let ownedDescriptors = Set(descriptors.filter { $0 >= 3 })
defer { ownedDescriptors.forEach { Darwin.close($0) } }
guard descriptors.allSatisfy({ $0 >= 3 }),
Set(descriptors).count == descriptors.count else {
throw VMError.invalidConfiguration(
"resolved boot descriptors must be unique inherited descriptors"
)
}
let kernelData = try readExactAnonymousBlob(kernel, kind: "linuxKernel")
let initrdData = try initrd.map {
try readExactAnonymousBlob($0, kind: "linuxInitrd")
}
return .immutableBytes(kernel: kernelData, initrd: initrdData)
}
func consumeForGuestLoad(
_ load: (Data, () throws -> Data?) throws -> Void
) throws {
switch self {
case .legacyPaths(let kernelPath, let initrdPath):
let kernel = try Data(contentsOf: URL(fileURLWithPath: kernelPath))
try load(kernel) {
try Self.readLegacyInitrd(at: initrdPath)
}
case .immutableBytes(let authority):
try authority.consumeForGuestLoad(load)
}
}
var retainedImmutableByteCount: UInt64 {
guard case .immutableBytes(let authority) = self else { return 0 }
return authority.retainedByteCount
}
var immutableBytesWereConsumed: Bool {
guard case .immutableBytes(let authority) = self else { return false }
return authority.isConsumed
}
private static func readLegacyInitrd(at path: String?) throws -> Data? {
guard let path else { return nil }
let data = try Data(
contentsOf: URL(fileURLWithPath: path),
options: .mappedIfSafe
)
guard !data.isEmpty else {
throw VMError.bootFailure("initrd is empty: \(path)")
}
return data
}
private static func readExactAnonymousBlob(
_ authority: MachineInheritedBootBlob,
kind: String
) throws -> Data {
guard authority.byteCount > 0,
authority.byteCount <= authority.maximumByteCount,
let allocationCount = Int(exactly: authority.byteCount),
isLowercaseSHA256(authority.sha256) else {
throw VMError.invalidConfiguration(
"resolved \(kind) metadata is outside its allocation or digest bounds"
)
}
let accessFlags = fcntl(authority.descriptor, F_GETFL)
var before = stat()
guard accessFlags >= 0,
accessFlags & O_ACCMODE == O_RDONLY,
fstat(authority.descriptor, &before) == 0,
before.st_mode & S_IFMT == S_IFREG,
before.st_uid == geteuid(),
before.st_nlink == 0,
before.st_size > 0,
UInt64(before.st_size) == authority.byteCount,
before.st_mode & 0o077 == 0 else {
throw VMError.invalidConfiguration(
"resolved \(kind) is not the exact private anonymous read-only blob"
)
}
var data = Data(count: allocationCount)
try data.withUnsafeMutableBytes { raw in
guard let base = raw.baseAddress else {
throw VMError.bootFailure("resolved \(kind) allocation is empty")
}
var offset = 0
while offset < raw.count {
let result = pread(
authority.descriptor,
base.advanced(by: offset),
raw.count - offset,
off_t(offset)
)
if result > 0 {
offset += result
} else if result < 0, errno == EINTR {
continue
} else {
throw VMError.bootFailure(
"resolved \(kind) changed or ended during exact descriptor read"
)
}
}
}
var after = stat()
guard fstat(authority.descriptor, &after) == 0,
before.st_dev == after.st_dev,
before.st_ino == after.st_ino,
before.st_size == after.st_size,
before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec,
before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,
before.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec,
before.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else {
throw VMError.bootFailure(
"resolved \(kind) identity changed during descriptor read"
)
}
let actual = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
guard actual == authority.sha256 else {
throw VMError.bootFailure("resolved \(kind) failed exact SHA-256 validation")
}
return data
}
private static func isLowercaseSHA256(_ value: String) -> Bool {
value.utf8.count == 64 && value.utf8.allSatisfy {
(48...57).contains($0) || (97...102).contains($0)
}
}
}