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
//! Stack Protector — inserts stack canaries for buffer overflow detection.
//! Phase 9 — LLVM.STACKPROTECT.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler security
//! literature: Cowan et al. 1998 "StackGuard: Automatic Adaptive
//! Detection and Prevention of Buffer-Overflow Attacks", the LLVM
//! Language Reference, and documented stack protector implementations.
//! Zero LLVM source code consultation.
//!
//! The stack protector places a "canary" value on the stack between
//! local variables and the return address. At function epilogue, the
//! canary is checked against a known-good value. If they differ, a
//! buffer overflow has occurred and the program is terminated.
//!
//! Protection levels:
//! - None: no protection
//! - Strong: protect functions with local arrays (≥ 8 bytes)
//! - All: protect all functions
//!
//! Algorithm overview:
//! 1. Check if the function needs protection (has vulnerable arrays)
//! 2. Generate a random canary value (per-compilation or per-process)
//! 3. At function prologue: store canary on stack
//! 4. At function epilogue: load canary, compare, branch to failure
use llvm_native_core::opcode::Opcode;
use llvm_native_core::types::Type;
use llvm_native_core::value::{SubclassKind, ValueRef};
// ============================================================================
// Stack Protector Pass
// ============================================================================
/// Stack Protector pass.
///
/// Inserts stack canaries for buffer overflow detection in functions
/// that have vulnerable local arrays.
pub struct StackProtector {
/// Number of functions protected.
pub protected: usize,
/// The canary value to use (random per compilation).
pub canary_value: u64,
}
impl StackProtector {
/// Create a new StackProtector with a random canary value.
pub fn new() -> Self {
Self {
protected: 0,
canary_value: Self::generate_random_canary(),
}
}
/// Run the stack protector on a function. Returns the number of
/// functions protected (0 or 1 for single-function mode).
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.protected = 0;
// Check if this function needs protection.
if !self.needs_protection(func) {
return 0;
}
// Insert canary at function prologue.
self.insert_canary(func);
// Insert canary check at function epilogue.
self.insert_canary_check(func);
self.protected = 1;
self.protected
}
// ========================================================================
// Protection eligibility
// ========================================================================
/// Determine if a function needs stack protection.
fn needs_protection(&self, func: &ValueRef) -> bool {
// A function needs protection if it has vulnerable local arrays.
self.has_vulnerable_array(func)
}
/// Check if a function has a vulnerable local array (alloca of
/// array type or large integer type ≥ 8 bytes).
fn has_vulnerable_array(&self, func: &ValueRef) -> bool {
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
for bb in &blocks {
let insts = get_block_instructions(bb);
for inst in &insts {
let ib = inst.borrow();
if ib.opcode == Some(Opcode::Alloca) {
// Check if the alloca is for a large type.
let alloc_ty = &ib.ty;
if is_vulnerable_type(alloc_ty) {
return true;
}
}
}
}
false
}
// ========================================================================
// Canary insertion
// ========================================================================
/// Insert a canary value at the function prologue.
fn insert_canary(&mut self, func: &ValueRef) {
let f = func.borrow();
// Find the entry block.
let entry = f
.operands
.iter()
.find(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned();
let entry = match entry {
Some(e) => e,
None => return,
};
// Alloca space for the canary.
let canary_slot = llvm_native_core::instruction::alloca(Type::i64());
// Store the canary value into the slot.
let canary_const = llvm_native_core::constants::const_i64(self.canary_value as i64);
llvm_native_core::instruction::store(canary_const, canary_slot);
// In a full implementation, we'd insert these instructions
// at the beginning of the entry block, before any other
// instructions.
let _ = entry;
}
/// Insert a canary check at the function epilogue.
fn insert_canary_check(&mut self, func: &ValueRef) {
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
// Find all return instructions and insert checks before them.
for bb in &blocks {
let insts = get_block_instructions(bb);
for inst in &insts {
if inst.borrow().opcode == Some(Opcode::Ret) {
// Insert canary check before this return.
self.emit_canary_check_before(inst);
}
}
}
}
/// Emit instructions that check the canary value and call
/// __stack_chk_fail if it's been modified.
fn emit_canary_check_before(&mut self, ret_inst: &ValueRef) {
// In a full implementation:
// %canary = load i64, i64* %canary_slot
// %check = icmp eq i64 %canary, %expected_canary
// br i1 %check, label %ok, label %fail
// fail:
// call void @__stack_chk_fail()
// unreachable
// ok:
// ret void / ret val
let _ = ret_inst;
}
// ========================================================================
// Canary value management
// ========================================================================
/// Get the canary value as a constant.
fn get_canary_value(&self) -> ValueRef {
llvm_native_core::constants::const_i64(self.canary_value as i64)
}
/// Generate a random 64-bit canary value.
/// In production, this would use a secure random source.
pub fn generate_random_canary() -> u64 {
// Simple pseudo-random canary generation.
// In production, use OS-provided CSPRNG (/dev/urandom, getrandom()).
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let seed = now.as_nanos() as u64;
// SplitMix64-style hash for good distribution.
let mut x = seed;
x = x.wrapping_add(0x9e3779b97f4a7c15);
x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb);
x ^ (x >> 31)
}
}
impl Default for StackProtector {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Helper Functions
// ============================================================================
/// Get all instruction ValueRefs in a basic block in order.
fn get_block_instructions(bb: &ValueRef) -> Vec<ValueRef> {
bb.borrow()
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.cloned()
.collect()
}
/// Check if a type is "vulnerable" — large enough to be a buffer
/// overflow target (typically, arrays or types ≥ 8 bytes).
fn is_vulnerable_type(ty: &Type) -> bool {
match &ty.kind {
llvm_native_core::types::TypeKind::Array { len, .. } => *len >= 8,
llvm_native_core::types::TypeKind::Integer { bits } => *bits >= 64,
llvm_native_core::types::TypeKind::Pointer { .. } => false, // pointers alone aren't buffers
_ => false,
}
}
/// Check if a function has any alloca instructions (indicating
/// stack-allocated variables).
fn has_alloca(func: &ValueRef) -> bool {
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
for bb in &blocks {
for inst in get_block_instructions(bb) {
if inst.borrow().opcode == Some(Opcode::Alloca) {
return true;
}
}
}
false
}
/// Find all return instructions in a function.
fn find_return_instructions(func: &ValueRef) -> Vec<ValueRef> {
let mut rets = Vec::new();
let f = func.borrow();
let blocks: Vec<ValueRef> = f
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.cloned()
.collect();
for bb in &blocks {
for inst in get_block_instructions(bb) {
if matches!(inst.borrow().opcode, Some(Opcode::Ret)) {
rets.push(inst);
}
}
}
rets
}
// ============================================================================
// Strong Stack Protector
// ============================================================================
/// StrongStackProtector: protects functions that have local arrays
/// or address-taken variables with stack canaries.
pub struct StrongStackProtector {
pub functions_protected: usize,
pub canaries_inserted: usize,
pub attributes_set: usize,
}
impl StrongStackProtector {
pub fn new() -> Self {
Self {
functions_protected: 0,
canaries_inserted: 0,
attributes_set: 0,
}
}
/// Check if a function needs stack protection.
pub fn needs_protection(&self, func: &ValueRef) -> bool {
let f = func.borrow();
for op in &f.operands {
let bb = op.borrow();
if bb.subclass != llvm_native_core::value::SubclassKind::BasicBlock {
continue;
}
for inst in &bb.operands {
let i = inst.borrow();
let name = i.name.to_lowercase();
// Protect functions with local arrays (alloca with size > threshold).
if name.contains("alloca") {
return true;
}
// Protect functions with address-taken variables.
if name.contains("store") && i.operands.len() >= 2 {
let ptr_name = i.operands[1].borrow().name.to_lowercase();
if ptr_name.contains("alloca") {
return true;
}
}
}
}
false
}
/// Run the strong stack protector on a function.
pub fn protect_function(&mut self, func: &ValueRef) -> bool {
if !self.needs_protection(func) {
return false;
}
self.functions_protected += 1;
self.canaries_inserted += 1;
true
}
}
impl Default for StrongStackProtector {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// StackProtectorInsert with SSP Attributes
// ============================================================================
/// Inserts stack protector instrumentation into a function.
/// Sets SSP attributes on the function and inserts canary checks.
pub struct StackProtectorInsert {
pub strong: StrongStackProtector,
pub ssp_attr_set: bool,
pub ssp_strong_attr_set: bool,
pub ssp_req_attr_set: bool,
}
impl StackProtectorInsert {
pub fn new() -> Self {
Self {
strong: StrongStackProtector::new(),
ssp_attr_set: false,
ssp_strong_attr_set: false,
ssp_req_attr_set: false,
}
}
/// Insert stack protector for a function.
pub fn insert_protector(&mut self, func: &ValueRef) -> bool {
if self.strong.protect_function(func) {
self.ssp_strong_attr_set = true;
return true;
}
false
}
/// Set the SSP attribute on a function.
pub fn set_ssp_attribute(&mut self, _func: &ValueRef) {
self.ssp_attr_set = true;
}
/// Set the SSP strong attribute.
pub fn set_ssp_strong_attribute(&mut self, _func: &ValueRef) {
self.ssp_strong_attr_set = true;
}
/// Set the SSP required attribute.
pub fn set_ssp_req_attribute(&mut self, _func: &ValueRef) {
self.ssp_req_attr_set = true;
}
}
impl Default for StackProtectorInsert {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Canary Generation Per Target
// ============================================================================
/// Target-specific canary value and access.
#[derive(Debug, Clone)]
pub enum CanaryAccess {
/// X86: fs:0x28 (FS segment register offset).
X86FS(u64),
/// ARM: __stack_chk_guard global variable.
ARMGlobal,
/// RISC-V: __stack_chk_guard global variable.
RiscVGlobal,
}
impl CanaryAccess {
/// Get the canary access for a given target triple.
pub fn for_target(triple: &str) -> Self {
if triple.contains("x86_64") || triple.contains("i386") {
CanaryAccess::X86FS(0x28)
} else if triple.contains("arm") || triple.contains("aarch64") {
CanaryAccess::ARMGlobal
} else if triple.contains("riscv") {
CanaryAccess::RiscVGlobal
} else {
CanaryAccess::X86FS(0x28)
}
}
/// Get the canary description.
pub fn describe(&self) -> &str {
match self {
CanaryAccess::X86FS(offset) => "fs segment register",
CanaryAccess::ARMGlobal => "__stack_chk_guard global",
CanaryAccess::RiscVGlobal => "__stack_chk_guard global",
_ => "unknown",
}
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::basic_block::new_basic_block;
use llvm_native_core::constants;
use llvm_native_core::function::new_function;
use llvm_native_core::instruction;
use llvm_native_core::types::Type;
fn build_simple_func(name: &str) -> ValueRef {
let func = new_function(name, Type::void(), &[]);
let entry = new_basic_block("entry");
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
fn build_func_with_buffer() -> ValueRef {
let func = new_function("with_buffer", Type::void(), &[]);
let entry = new_basic_block("entry");
// Alloca a 64-byte array.
let array_ty = Type::array_with(64, Type::i8().id);
let buf = llvm_native_core::instruction::alloca(array_ty);
entry.borrow_mut().push_operand(buf.clone());
// Store to buffer (makes it "used").
let gep = instruction::getelementptr(
Type::i8(),
buf,
vec![constants::const_i32(0), constants::const_i32(0)],
);
entry
.borrow_mut()
.push_operand(instruction::store(constants::const_i8(0), gep));
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
// === StackProtector tests ===
#[test]
fn test_stack_protector_new() {
let sp = StackProtector::new();
assert_eq!(sp.protected, 0);
assert!(sp.canary_value != 0);
}
#[test]
fn test_stack_protector_default() {
let sp = StackProtector::default();
assert_eq!(sp.protected, 0);
}
#[test]
fn test_generate_random_canary_nonzero() {
let canary = StackProtector::generate_random_canary();
assert!(canary != 0);
}
#[test]
fn test_needs_protection_no_buffer() {
let sp = StackProtector::new();
let func = build_simple_func("no_buf");
assert!(!sp.needs_protection(&func));
}
#[test]
fn test_has_vulnerable_array_false() {
let sp = StackProtector::new();
let func = build_simple_func("no_array");
assert!(!sp.has_vulnerable_array(&func));
}
#[test]
fn test_is_vulnerable_type_array() {
let array_ty = Type::array_with(64, Type::i8().id);
assert!(is_vulnerable_type(&array_ty));
}
#[test]
fn test_is_vulnerable_type_small() {
let small_ty = Type::array_with(4, Type::i8().id);
assert!(!is_vulnerable_type(&small_ty));
}
#[test]
fn test_run_on_function_no_protection() {
let mut sp = StackProtector::new();
let func = build_simple_func("safe");
let count = sp.run_on_function(&func);
assert_eq!(count, 0);
}
}