forked from vbpf/prevail
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_elf_loader.cpp
More file actions
592 lines (499 loc) · 25.9 KB
/
test_elf_loader.cpp
File metadata and controls
592 lines (499 loc) · 25.9 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
// Copyright (c) Prevail Verifier contributors.
// SPDX-License-Identifier: MIT
#include <catch2/catch_all.hpp>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <elfio/elfio.hpp>
#include "config.hpp"
#include "io/elf_loader.hpp"
#include "io/elf_reader.hpp"
#include "platform.hpp"
using namespace prevail;
namespace {
std::vector<uint8_t> read_file_bytes(const std::filesystem::path& path) {
std::ifstream file(path, std::ios::binary);
if (!file) {
throw std::runtime_error("Failed to open test input: " + path.string());
}
return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
}
void write_file_bytes(const std::filesystem::path& path, const std::vector<uint8_t>& bytes) {
std::ofstream file(path, std::ios::binary | std::ios::trunc);
if (!file) {
throw std::runtime_error("Failed to open test output: " + path.string());
}
file.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
if (!file) {
throw std::runtime_error("Failed to write mutated test input: " + path.string());
}
}
uint32_t read_u32_le(const std::vector<uint8_t>& bytes, const size_t offset) {
if (offset + sizeof(uint32_t) > bytes.size()) {
throw std::runtime_error("u32 read out of bounds");
}
return static_cast<uint32_t>(bytes[offset] | (static_cast<uint32_t>(bytes[offset + 1]) << 8U) |
(static_cast<uint32_t>(bytes[offset + 2]) << 16U) |
(static_cast<uint32_t>(bytes[offset + 3]) << 24U));
}
uint64_t read_u64_le(const std::vector<uint8_t>& bytes, const size_t offset) {
if (offset + sizeof(uint64_t) > bytes.size()) {
throw std::runtime_error("u64 read out of bounds");
}
uint64_t value = 0;
for (size_t i = 0; i < sizeof(uint64_t); ++i) {
value |= static_cast<uint64_t>(bytes[offset + i]) << (8U * i);
}
return value;
}
void write_u16_le(std::vector<uint8_t>& bytes, const size_t offset, const uint16_t value) {
if (offset + sizeof(uint16_t) > bytes.size()) {
throw std::runtime_error("u16 write out of bounds");
}
bytes[offset] = static_cast<uint8_t>(value & 0xffU);
bytes[offset + 1] = static_cast<uint8_t>((value >> 8U) & 0xffU);
}
void write_u32_le(std::vector<uint8_t>& bytes, const size_t offset, const uint32_t value) {
if (offset + sizeof(uint32_t) > bytes.size()) {
throw std::runtime_error("u32 write out of bounds");
}
bytes[offset] = static_cast<uint8_t>(value & 0xffU);
bytes[offset + 1] = static_cast<uint8_t>((value >> 8U) & 0xffU);
bytes[offset + 2] = static_cast<uint8_t>((value >> 16U) & 0xffU);
bytes[offset + 3] = static_cast<uint8_t>((value >> 24U) & 0xffU);
}
void write_u64_le(std::vector<uint8_t>& bytes, const size_t offset, const uint64_t value) {
if (offset + sizeof(uint64_t) > bytes.size()) {
throw std::runtime_error("u64 write out of bounds");
}
for (size_t i = 0; i < sizeof(uint64_t); ++i) {
bytes[offset + i] = static_cast<uint8_t>((value >> (8U * i)) & 0xffU);
}
}
class TempElfFile {
public:
TempElfFile(const std::filesystem::path& source, const std::string_view tag) {
const auto temp_dir = std::filesystem::temp_directory_path();
const auto seed = std::random_device{}();
for (size_t attempt = 0; attempt < 4096; ++attempt) {
path_ = temp_dir /
("prevail-" + std::string(tag) + "-" + std::to_string(seed) + "-" + std::to_string(attempt) + ".o");
if (std::filesystem::exists(path_)) {
continue;
}
std::filesystem::copy_file(source, path_);
return;
}
throw std::runtime_error("Failed to create temporary ELF copy");
}
~TempElfFile() {
std::error_code ec;
std::filesystem::remove(path_, ec);
}
TempElfFile(const TempElfFile&) = delete;
TempElfFile& operator=(const TempElfFile&) = delete;
const std::filesystem::path& path() const { return path_; }
private:
std::filesystem::path path_;
};
std::optional<KsymBtfId> resolve_no_ksym_symbols(const std::string&) { return std::nullopt; }
struct SectionHeaderInfo {
unsigned char elf_class;
size_t section_header_offset;
};
SectionHeaderInfo get_section_header_info(const std::filesystem::path& path, const std::string& section_name) {
ELFIO::elfio reader;
if (!reader.load(path.string())) {
throw std::runtime_error("Failed to parse test ELF copy: " + path.string());
}
const auto* section = reader.sections[section_name];
if (!section) {
throw std::runtime_error("Section not found in test ELF copy: " + section_name);
}
return {
.elf_class = reader.get_class(),
.section_header_offset =
static_cast<size_t>(reader.get_sections_offset()) +
static_cast<size_t>(section->get_index()) * static_cast<size_t>(reader.get_section_entry_size()),
};
}
void patch_machine(const std::filesystem::path& path, const uint16_t machine) {
auto bytes = read_file_bytes(path);
if (bytes.size() < 20) {
throw std::runtime_error("ELF header is truncated");
}
// e_machine field in ELF header (both 32-bit and 64-bit).
write_u16_le(bytes, 18, machine);
write_file_bytes(path, bytes);
}
void patch_section_offset(const std::filesystem::path& path, const std::string& section_name, const uint64_t offset) {
const auto info = get_section_header_info(path, section_name);
auto bytes = read_file_bytes(path);
if (info.elf_class == ELFIO::ELFCLASS32) {
write_u32_le(bytes, info.section_header_offset + 16, static_cast<uint32_t>(offset));
} else if (info.elf_class == ELFIO::ELFCLASS64) {
write_u64_le(bytes, info.section_header_offset + 24, offset);
} else {
throw std::runtime_error("Unexpected ELF class");
}
write_file_bytes(path, bytes);
}
void patch_section_size(const std::filesystem::path& path, const std::string& section_name, const uint64_t size) {
const auto info = get_section_header_info(path, section_name);
auto bytes = read_file_bytes(path);
if (info.elf_class == ELFIO::ELFCLASS32) {
write_u32_le(bytes, info.section_header_offset + 20, static_cast<uint32_t>(size));
} else if (info.elf_class == ELFIO::ELFCLASS64) {
write_u64_le(bytes, info.section_header_offset + 32, size);
} else {
throw std::runtime_error("Unexpected ELF class");
}
write_file_bytes(path, bytes);
}
struct RelocationSectionInfo {
unsigned char elf_class;
ELFIO::Elf_Word section_type;
size_t section_offset;
size_t section_size;
size_t entry_size;
};
RelocationSectionInfo get_relocation_section_info(const std::filesystem::path& path, const std::string& section_name) {
ELFIO::elfio reader;
if (!reader.load(path.string())) {
throw std::runtime_error("Failed to parse test ELF copy: " + path.string());
}
const auto* section = reader.sections[section_name];
if (!section) {
throw std::runtime_error("Relocation section not found in test ELF copy: " + section_name);
}
if (section->get_type() != ELFIO::SHT_REL && section->get_type() != ELFIO::SHT_RELA) {
throw std::runtime_error("Section is not a relocation section: " + section_name);
}
if (section->get_entry_size() == 0 || section->get_size() < section->get_entry_size()) {
throw std::runtime_error("Relocation section has no entries: " + section_name);
}
return {
.elf_class = reader.get_class(),
.section_type = section->get_type(),
.section_offset = static_cast<size_t>(section->get_offset()),
.section_size = static_cast<size_t>(section->get_size()),
.entry_size = static_cast<size_t>(section->get_entry_size()),
};
}
void patch_first_core_access_string_offset(const std::filesystem::path& path, const uint32_t new_offset) {
ELFIO::elfio reader;
if (!reader.load(path.string())) {
throw std::runtime_error("Failed to parse test ELF copy: " + path.string());
}
const auto* btf_ext = reader.sections[".BTF.ext"];
if (!btf_ext) {
throw std::runtime_error("Section .BTF.ext not found in test ELF copy");
}
auto bytes = read_file_bytes(path);
const size_t section_offset = static_cast<size_t>(btf_ext->get_offset());
const size_t section_size = static_cast<size_t>(btf_ext->get_size());
if (section_offset > bytes.size() || section_size > bytes.size() - section_offset) {
throw std::runtime_error(".BTF.ext section out of file bounds in test ELF copy");
}
const size_t ext_base = section_offset;
const uint32_t hdr_len = read_u32_le(bytes, ext_base + 4);
const uint32_t core_relo_off = read_u32_le(bytes, ext_base + 24);
const uint32_t core_relo_len = read_u32_le(bytes, ext_base + 28);
const size_t core_start = ext_base + static_cast<size_t>(hdr_len) + static_cast<size_t>(core_relo_off);
const size_t core_end = core_start + static_cast<size_t>(core_relo_len);
if (core_start > ext_base + section_size || core_end > ext_base + section_size || core_end < core_start) {
throw std::runtime_error("Invalid core_relo bounds in test ELF copy");
}
if (core_end - core_start < sizeof(uint32_t)) {
throw std::runtime_error("core_relo subsection is truncated in test ELF copy");
}
const uint32_t record_size = read_u32_le(bytes, core_start);
size_t cursor = core_start + sizeof(uint32_t);
bool patched = false;
while (cursor + 8 <= core_end) {
const uint32_t num_info = read_u32_le(bytes, cursor + 4);
cursor += 8;
const size_t records_size = static_cast<size_t>(num_info) * static_cast<size_t>(record_size);
if (records_size > core_end - cursor) {
throw std::runtime_error("Invalid CO-RE records bounds in test ELF copy");
}
if (num_info > 0) {
// bpf_core_relo.access_str_off is the third u32 field in a relocation record.
write_u32_le(bytes, cursor + 8, new_offset);
patched = true;
break;
}
cursor += records_size;
}
if (!patched) {
throw std::runtime_error("No CO-RE relocation records found in test ELF copy");
}
write_file_bytes(path, bytes);
}
void patch_first_relocation_symbol_index(const std::filesystem::path& path, const std::string& section_name,
const uint32_t new_symbol_index) {
const auto info = get_relocation_section_info(path, section_name);
auto bytes = read_file_bytes(path);
const size_t entry_offset = info.section_offset;
if (entry_offset + info.entry_size > bytes.size()) {
throw std::runtime_error("Relocation entry out of bounds in test ELF copy");
}
if (info.elf_class == ELFIO::ELFCLASS64) {
constexpr size_t r_info_offset = 8;
const auto old_info = read_u64_le(bytes, entry_offset + r_info_offset);
const uint64_t new_info = (static_cast<uint64_t>(new_symbol_index) << 32U) | (old_info & 0xffffffffULL);
write_u64_le(bytes, entry_offset + r_info_offset, new_info);
} else if (info.elf_class == ELFIO::ELFCLASS32) {
constexpr size_t r_info_offset = 4;
const auto old_info = read_u32_le(bytes, entry_offset + r_info_offset);
const uint32_t new_info = (new_symbol_index << 8U) | (old_info & 0xffU);
write_u32_le(bytes, entry_offset + r_info_offset, new_info);
} else {
throw std::runtime_error("Unexpected ELF class");
}
write_file_bytes(path, bytes);
}
void patch_first_relocation_type(const std::filesystem::path& path, const std::string& section_name,
const uint32_t new_relocation_type) {
const auto info = get_relocation_section_info(path, section_name);
auto bytes = read_file_bytes(path);
const size_t entry_offset = info.section_offset;
if (entry_offset + info.entry_size > bytes.size()) {
throw std::runtime_error("Relocation entry out of bounds in test ELF copy");
}
if (info.elf_class == ELFIO::ELFCLASS64) {
constexpr size_t r_info_offset = 8;
const auto old_info = read_u64_le(bytes, entry_offset + r_info_offset);
const uint64_t new_info = (old_info & 0xffffffff00000000ULL) | static_cast<uint64_t>(new_relocation_type);
write_u64_le(bytes, entry_offset + r_info_offset, new_info);
} else if (info.elf_class == ELFIO::ELFCLASS32) {
constexpr size_t r_info_offset = 4;
const auto old_info = read_u32_le(bytes, entry_offset + r_info_offset);
const uint32_t new_info = (old_info & 0xffffff00U) | (new_relocation_type & 0xffU);
write_u32_le(bytes, entry_offset + r_info_offset, new_info);
} else {
throw std::runtime_error("Unexpected ELF class");
}
write_file_bytes(path, bytes);
}
} // namespace
#define FAIL_LOAD_ELF_BASE(test_name, dirname, filename, sectionname) \
TEST_CASE(test_name, "[elf]") { \
thread_local_options = {}; \
REQUIRE_THROWS_AS( \
([&]() { \
ElfObject{"ebpf-samples/" dirname "/" filename, {}, &g_ebpf_platform_linux}.get_programs(sectionname); \
}()), \
std::runtime_error); \
}
#define FAIL_LOAD_ELF(dirname, filename, sectionname) \
FAIL_LOAD_ELF_BASE("Try loading nonexisting program: " dirname "/" filename, dirname, filename, sectionname)
// Like FAIL_LOAD_ELF, but includes sectionname in the test name to avoid collisions
// when multiple sections of the same file fail to load.
#define FAIL_LOAD_ELF_SECTION(dirname, filename, sectionname) \
FAIL_LOAD_ELF_BASE("Try loading bad section: " dirname "/" filename " " sectionname, dirname, filename, sectionname)
#define LOAD_ELF_SECTION(dirname, filename, sectionname) \
TEST_CASE("Try loading section: " dirname "/" filename " " sectionname, "[elf]") { \
thread_local_options = {}; \
const auto progs = \
ElfObject{"ebpf-samples/" dirname "/" filename, {}, &g_ebpf_platform_linux}.get_programs(sectionname); \
REQUIRE_FALSE(progs.empty()); \
}
// Intentional loader failures.
FAIL_LOAD_ELF("cilium", "not-found.o", "2/1")
FAIL_LOAD_ELF("cilium", "bpf_lxc.o", "not-found")
FAIL_LOAD_ELF("invalid", "badsymsize.o", "xdp_redirect_map")
// Sections that used to be loader failures and now load successfully (verification may still reject later).
LOAD_ELF_SECTION("build", "badrelo.o", ".text")
LOAD_ELF_SECTION("linux-selftests", "bpf_cubic.o", "struct_ops")
LOAD_ELF_SECTION("linux-selftests", "bpf_dctcp.o", "struct_ops")
LOAD_ELF_SECTION("linux-selftests", "map_ptr_kern.o", "cgroup_skb/egress")
LOAD_ELF_SECTION("cilium-ebpf", "errors-el.elf", "socket")
LOAD_ELF_SECTION("cilium-ebpf", "fwd_decl-el.elf", "socket")
LOAD_ELF_SECTION("cilium-ebpf", "invalid-kfunc-el.elf", "tc")
LOAD_ELF_SECTION("cilium-ebpf", "kfunc-el.elf", "tc")
LOAD_ELF_SECTION("cilium-ebpf", "kfunc-el.elf", "fentry/bpf_fentry_test2")
LOAD_ELF_SECTION("cilium-ebpf", "kfunc-el.elf", "tp_btf/task_newtask")
LOAD_ELF_SECTION("cilium-ebpf", "kfunc-kmod-el.elf", "tc")
LOAD_ELF_SECTION("cilium-ebpf", "ksym-el.elf", "socket")
LOAD_ELF_SECTION("cilium-ebpf", "linked-el.elf", "socket")
LOAD_ELF_SECTION("cilium-ebpf", "linked1-el.elf", "socket")
LOAD_ELF_SECTION("cilium-ebpf", "linked2-el.elf", "socket")
LOAD_ELF_SECTION("cilium-ebpf", "loader-el.elf", "xdp")
LOAD_ELF_SECTION("cilium-ebpf", "loader-el.elf", "socket/2")
LOAD_ELF_SECTION("cilium-ebpf", "loader-clang-14-el.elf", "xdp")
LOAD_ELF_SECTION("cilium-ebpf", "loader-clang-14-el.elf", "socket/2")
LOAD_ELF_SECTION("cilium-ebpf", "loader-clang-17-el.elf", "xdp")
LOAD_ELF_SECTION("cilium-ebpf", "loader-clang-17-el.elf", "socket/2")
LOAD_ELF_SECTION("cilium-ebpf", "loader-clang-20-el.elf", "xdp")
LOAD_ELF_SECTION("cilium-ebpf", "loader-clang-20-el.elf", "socket/2")
LOAD_ELF_SECTION("cilium-ebpf", "loader_nobtf-el.elf", "socket/2")
TEST_CASE("CO-RE relocations are parsed from .BTF.ext core_relo subsection", "[elf][core]") {
thread_local_options = {};
constexpr auto fentry_path = "ebpf-samples/cilium-examples/tcprtt_bpf_bpfel.o";
constexpr auto fentry_section = "fentry/tcp_close";
ElfObject fentry_elf{fentry_path, {}, &g_ebpf_platform_linux};
const auto& fentry_progs = fentry_elf.get_programs(fentry_section);
REQUIRE(fentry_progs.size() == 1);
REQUIRE(fentry_progs[0].core_relocation_count > 0);
constexpr auto sockops_path = "ebpf-samples/cilium-examples/tcprtt_sockops_bpf_bpfel.o";
constexpr auto sockops_section = "sockops";
ElfObject sockops_elf{sockops_path, {}, &g_ebpf_platform_linux};
const auto& sockops_progs = sockops_elf.get_programs(sockops_section);
REQUIRE(sockops_progs.size() == 1);
REQUIRE(sockops_progs[0].core_relocation_count > 0);
}
TEST_CASE("ELF loader rejects non-BPF e_machine", "[elf][hardening]") {
thread_local_options = {};
TempElfFile elf{"ebpf-samples/build/twomaps.o", "bad-machine"};
patch_machine(elf.path(), ELFIO::EM_X86_64);
REQUIRE_THROWS_WITH((ElfObject{elf.path().string(), {}, &g_ebpf_platform_linux}.get_programs(".text")),
Catch::Matchers::ContainsSubstring("Unsupported ELF machine"));
}
TEST_CASE("ELF loader rejects relocation sections with out-of-bounds file offsets", "[elf][hardening]") {
thread_local_options = {};
TempElfFile elf{"ebpf-samples/build/twomaps.o", "bad-reloc-offset"};
const auto file_size = std::filesystem::file_size(elf.path());
patch_section_offset(elf.path(), ".rel.BTF", file_size + 4096);
REQUIRE_THROWS_WITH((ElfObject{elf.path().string(), {}, &g_ebpf_platform_linux}.get_programs(".text")),
Catch::Matchers::ContainsSubstring("out-of-bounds file range"));
}
TEST_CASE("ELF loader rejects malformed legacy maps section record size", "[elf][hardening]") {
thread_local_options = {};
TempElfFile elf{"ebpf-samples/bpf_cilium_test/bpf_lb-DLB_L3.o", "bad-maps-size"};
// Keep the section in-bounds but make each inferred map record too small.
patch_section_size(elf.path(), "maps", 24);
REQUIRE_THROWS_WITH((ElfObject{elf.path().string(), {}, &g_ebpf_platform_linux}.get_programs("2/1")),
Catch::Matchers::ContainsSubstring("Malformed legacy maps section"));
}
TEST_CASE("CO-RE access string offset out-of-bounds fails cleanly", "[elf][core][hardening]") {
thread_local_options = {};
TempElfFile elf{"ebpf-samples/cilium-examples/tcprtt_bpf_bpfel.o", "bad-core-access"};
patch_first_core_access_string_offset(elf.path(), 0xfffffff0U);
REQUIRE_THROWS_WITH((ElfObject{elf.path().string(), {}, &g_ebpf_platform_linux}.get_programs("fentry/tcp_close")),
Catch::Matchers::ContainsSubstring("Unsupported or invalid CO-RE/BTF relocation data"));
}
TEST_CASE("ELF loader rejects relocation entries with invalid symbol index", "[elf][hardening]") {
thread_local_options = {};
TempElfFile elf{"ebpf-samples/build/twomaps.o", "bad-reloc-symbol-index"};
patch_first_relocation_symbol_index(elf.path(), ".rel.text", 0x00ffffffU);
REQUIRE_THROWS_WITH((ElfObject{elf.path().string(), {}, &g_ebpf_platform_linux}.get_programs(".text")),
Catch::Matchers::ContainsSubstring("Invalid relocation symbol index"));
}
TEST_CASE("ELF loader rejects unsupported relocation types", "[elf][hardening]") {
thread_local_options = {};
TempElfFile elf{"ebpf-samples/build/twomaps.o", "bad-reloc-type"};
patch_first_relocation_type(elf.path(), ".rel.text", 0xffU);
REQUIRE_THROWS_WITH((ElfObject{elf.path().string(), {}, &g_ebpf_platform_linux}.get_programs(".text")),
Catch::Matchers::ContainsSubstring("Unsupported relocation type"));
}
TEST_CASE("ELF loader rewrites .ksyms function calls to call_btf", "[elf]") {
thread_local_options = {};
ElfObject elf{"ebpf-samples/cilium-ebpf/kfunc-kmod-el.elf", {}, &g_ebpf_platform_linux};
const auto& progs = elf.get_programs("tc", "call_kfunc");
REQUIRE(progs.size() == 1);
const auto resolver = g_ebpf_platform_linux.resolve_ksym_btf_id;
REQUIRE(resolver != nullptr);
const auto expected = resolver("bpf_testmod_test_mod_kfunc");
REQUIRE(expected.has_value());
const auto& instructions = progs[0].prog;
const auto call_it = std::find_if(instructions.begin(), instructions.end(),
[](const EbpfInst& inst) { return inst.opcode == INST_OP_CALL; });
REQUIRE(call_it != instructions.end());
REQUIRE(call_it->src == INST_CALL_BTF_HELPER);
REQUIRE(call_it->offset == expected->module);
REQUIRE(call_it->imm == expected->btf_id);
}
TEST_CASE("ELF loader fails unresolved .ksyms function calls before builtin fallback", "[elf]") {
thread_local_options = {};
ebpf_platform_t platform = g_ebpf_platform_linux;
platform.resolve_ksym_btf_id = resolve_no_ksym_symbols;
REQUIRE_THROWS_WITH((ElfObject{"ebpf-samples/cilium-ebpf/kfunc-kmod-el.elf", {}, &platform}.get_programs("tc")),
Catch::Matchers::ContainsSubstring("Unresolved symbols found."));
}
TEST_CASE("ELF loader ignores non-function .ksyms entries", "[elf]") {
thread_local_options = {};
ebpf_platform_t platform = g_ebpf_platform_linux;
platform.resolve_ksym_btf_id = resolve_no_ksym_symbols;
ElfObject elf{"ebpf-samples/cilium-ebpf/ksym-el.elf", {}, &platform};
const auto& progs = elf.get_programs("socket", "ksym_test");
REQUIRE(progs.size() == 1);
}
// Regression test: rewrite_extern_constant_load must not crash when the resolved value
// exceeds INT32_MAX and the load instruction is 8-byte width (LDX DW).
// BPF MOV imm only has a 32-bit immediate; values that don't fit must cause a
// graceful bail-out (return false), not a gsl::narrowing_error exception.
TEST_CASE("rewrite_extern_constant_load bails out on values exceeding int32 range", "[elf][hardening]") {
// Build a 3-instruction sequence: LDDW pair + LDX DW r2, [r1+0].
// This is the pattern clang emits for: extern uint64_t LINUX_KERNEL_VERSION;
auto make_instructions = []() {
std::vector<EbpfInst> insts(3);
insts[0].opcode = INST_OP_LDDW_IMM;
insts[0].dst = 1;
insts[0].src = 0;
insts[0].offset = 0;
insts[0].imm = 0;
insts[1] = {};
// LDX DW = INST_CLS_LDX | INST_MODE_MEM | INST_SIZE_DW = 0x79
insts[2].opcode = static_cast<uint8_t>(INST_CLS_LDX | INST_MODE_MEM | INST_SIZE_DW);
insts[2].dst = 2;
insts[2].src = 1;
insts[2].offset = 0;
insts[2].imm = 0;
return insts;
};
SECTION("small value fits in int32 — rewrite succeeds") {
auto insts = make_instructions();
REQUIRE(rewrite_extern_constant_load(insts, 0, 42));
}
SECTION("INT32_MAX fits — rewrite succeeds") {
auto insts = make_instructions();
REQUIRE(rewrite_extern_constant_load(insts, 0, 0x7FFFFFFF));
}
SECTION("0x80000000 exceeds int32 — returns false without throwing") {
auto insts = make_instructions();
CHECK_NOTHROW(rewrite_extern_constant_load(insts, 0, 0x80000000ULL));
// Verify the function returns false (bail out, don't rewrite).
auto insts2 = make_instructions();
CHECK_FALSE(rewrite_extern_constant_load(insts2, 0, 0x80000000ULL));
}
SECTION("0x100000000 exceeds int32 — returns false without throwing") {
auto insts = make_instructions();
CHECK_NOTHROW(rewrite_extern_constant_load(insts, 0, 0x100000000ULL));
auto insts2 = make_instructions();
CHECK_FALSE(rewrite_extern_constant_load(insts2, 0, 0x100000000ULL));
}
SECTION("0xFFFFFFFF exceeds int32 as uint64 — returns false without throwing") {
auto insts = make_instructions();
CHECK_NOTHROW(rewrite_extern_constant_load(insts, 0, 0xFFFFFFFFULL));
auto insts2 = make_instructions();
CHECK_FALSE(rewrite_extern_constant_load(insts2, 0, 0xFFFFFFFFULL));
}
SECTION("large 64-bit value — returns false without throwing") {
auto insts = make_instructions();
CHECK_NOTHROW(rewrite_extern_constant_load(insts, 0, 0xDEADBEEFCAFEBABEULL));
auto insts2 = make_instructions();
CHECK_FALSE(rewrite_extern_constant_load(insts2, 0, 0xDEADBEEFCAFEBABEULL));
}
}
// Regression test: read_elf(istream, path) must work when path is not a real file.
// The load_elf function uses file_size(path) for section-bounds validation, which
// fails for non-file paths like "memory". The fix falls back to stream size.
TEST_CASE("read_elf succeeds with istream and non-file path", "[elf]") {
thread_local_options = {};
// Read a valid ELF file into memory.
const auto bytes = read_file_bytes("ebpf-samples/build/twomaps.o");
std::string data(reinterpret_cast<const char*>(bytes.data()), bytes.size());
std::istringstream stream(data);
// Use a non-file path — this is how ebpf-for-windows loads ELF from memory.
ebpf_verifier_options_t options{};
auto programs = read_elf(stream, "memory", ".text", "", options, &g_ebpf_platform_linux);
REQUIRE(!programs.empty());
}