debugoff 0.2.2

Linux anti-analysis and anti-debugging Rust library
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
// DebugOff
// Copyright (C) 2022 0xor0ne
//
// Licensed under:
// - GPL-3.0 when "obfuscate" feature is enabled;
// - MIT when "obfuscate" feature IS NOT enabled;

// use std::mem::MaybeUninit;
// use std::sync::Mutex;
use std::cell::{RefCell, RefMut};
// use std::sync::Once;
use const_random::const_random;
use crunchy::*;
#[cfg(feature = "obfuscate")]
use goldberg::*;
use unroll::*;

#[allow(non_camel_case_types)]
enum PtraceRequest {
    PTRACE_TRACEME = 0,
}

#[derive(Debug)]
struct PtraceState {
    traceme_done: bool,
    traceme_ctr: u64,
}

const SRSIZE: usize = 10;

#[derive(Debug)]
struct Aa {
    // ptrace_state: Mutex<PtraceState>,
    ptrace_state: PtraceState,
    r: Rand,
    sr: [u32; SRSIZE],
}

thread_local!(static AA: RefCell<Aa> = RefCell::new(Aa::new()));

impl Aa {
    // fn ptrace_singleton() -> &'static Aa {
    //     static mut SINGLETON: MaybeUninit<Aa> = MaybeUninit::uninit();
    //     static ONCE: Once = Once::new();

    //     unsafe {
    //         ONCE.call_once(|| {
    //             let singleton = Aa {
    //                 ptrace_state: Mutex::new(PtraceState {
    //                     traceme_done: false,
    //                     traceme_ctr: 0,
    //                 }),
    //             };
    //             SINGLETON.write(singleton);
    //         });

    //         SINGLETON.assume_init_ref()
    //     }
    // }

    fn new() -> Aa {
        let tmp = std::time::SystemTime::now().duration_since(std::time::SystemTime::UNIX_EPOCH);

        #[cfg(feature = "obfuscate")]
        goldberg_stmts! {
            let r: u128 = match tmp {
                Ok(x) => x.as_nanos(),
                _ => 0u128,
            };
        }
        #[cfg(not(feature = "obfuscate"))]
        let r: u128 = match tmp {
            Ok(x) => x.as_nanos(),
            _ => 0u128,
        };

        #[cfg(feature = "obfuscate")]
        goldberg_stmts! {
            Aa {
                ptrace_state : PtraceState {
                    traceme_done: false,
                    traceme_ctr: 0u64,
                },
                r: Rand::new(r as u32),
                sr: [
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                    const_random!(u32),
                ],
            }
        }
        #[cfg(not(feature = "obfuscate"))]
        Aa {
            ptrace_state: PtraceState {
                traceme_done: false,
                traceme_ctr: 0u64,
            },
            r: Rand::new(r as u32),
            sr: [
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
                const_random!(u32),
            ],
        }
    }
}

/// Sets the process as traceable, as with `ptrace(PTRACE_TRACEME, ...)`
#[inline(always)]
fn ptraceme() -> Result<(), crate::DebugOffErr> {
    #[cfg(feature = "obfuscate")]
    let res: usize = unsafe {
        crate::arch::syscall4(
            crate::arch::SysNo::SYS_PTRACE,
            PtraceRequest::PTRACE_TRACEME as usize,
            goldberg_int! {0usize},
            goldberg_int! {0usize},
            goldberg_int! {0usize},
        )
    };
    #[cfg(not(feature = "obfuscate"))]
    let res: usize = unsafe {
        crate::arch::syscall4(
            crate::arch::SysNo::SYS_PTRACE,
            PtraceRequest::PTRACE_TRACEME as usize,
            0,
            0,
            0,
        )
    };

    match res {
        0 => Ok(()),
        _ => Err(crate::DebugOffErr {
            err_type: crate::DebugOffErrType::AlreadyTraced,
        }),
    }
}

/// Call `ptrace(PTRACE_TRACEME, ...)` one time to detect the presence of a debugger.
///
/// This function can be called multiple times.
///
/// At the first invocation, the function expects a return value of 0 from `ptrace(PTRACE_TRACEME, ...)`.
/// In subsequent calls, `ptrace(PTRACE_TRACEME, ...)` should return -1.
///
/// If the above is not satisfied, the function calls `exit_group(0)`.
///
/// To be more effective, the function should be called at least once for each thread.
///
/// ## Examples
///
/// ```rust
/// // Import only on Linux and for "release builds"
/// #[cfg(target_os = "linux")]
/// #[cfg(not(debug_assertions))]
/// use debugoff;
///
/// // Call only on Linux and for "release" builds.
/// #[cfg(target_os = "linux")]
/// #[cfg(not(debug_assertions))]
/// debugoff::ptraceme_or_die();
/// ```
#[inline(always)]
pub fn ptraceme_or_die() {
    let res = ptraceme();
    // println!("{:?}", res);

    // The first time this function is called, res should be Ok(_). Subsequent calls should
    // return Err(_)
    #[cfg(feature = "obfuscate")]
    AA.with(|f| {
        let mut aa: RefMut<Aa> = f.borrow_mut();
        match aa.ptrace_state.traceme_done {
            false => match res {
                Ok(_) => aa.ptrace_state.traceme_done = true,
                Err(_) => the_end(),
            },
            true => {
                if res.is_ok() {
                    the_end()
                }
            }
        }

        goldberg_stmts! {
            let mut tmp: u64 = aa.ptrace_state.traceme_ctr;
            tmp = tmp.saturating_add(1);
            aa.ptrace_state.traceme_ctr = tmp;
        }
    });
    #[cfg(not(feature = "obfuscate"))]
    AA.with(|f| {
        let mut aa: RefMut<Aa> = f.borrow_mut();
        match aa.ptrace_state.traceme_done {
            false => match res {
                Ok(_) => aa.ptrace_state.traceme_done = true,
                Err(_) => the_end(),
            },
            true => {
                if res.is_ok() {
                    the_end()
                }
            }
        }

        aa.ptrace_state.traceme_ctr = aa.ptrace_state.traceme_ctr.saturating_add(1);
    });
}

/// Call `ptrace(PTRACE_TRACEME, ...)` multiple times in nested loops.
///
/// The loop iterations are unrolled and the number of iterations is randomized for each
/// compilation (just remember to clean you project before compiling again: `cargo clean`).
///
/// For each iteration, if the value returned by `ptrace` is not the expected one, the function
/// calls `exit_group(0)`. If the value returned by `ptrace` is the expected one (0 at the first
/// call in a thread and -1 thereafter) then a random value (sum of a dynamic random value and a
/// compilation time random value) is added to an `offset` value. At the end of all the iterations
/// the `offset` value is checked. If the check fails, the function calls
/// `exit_group(0)`
///
/// If `debugoff` is included as a dependency with `obfuscate` feature enabled, the code is even
/// more obfuscated by [goldberg](https://crates.io/crates/goldberg).
///
/// This function can be called multiple times.
/// To be more effective, the function should be called at least once for each thread.
///
/// ## Examples
///
/// ```rust
/// // Import only on Linux and for "release builds"
/// #[cfg(target_os = "linux")]
/// #[cfg(not(debug_assertions))]
/// use debugoff;
///
/// // Call only on Linux and for "release" builds.
/// #[cfg(target_os = "linux")]
/// #[cfg(not(debug_assertions))]
/// debugoff::multi_ptraceme_or_die();
/// ```
#[unroll_for_loops]
#[inline(always)]
pub fn multi_ptraceme_or_die() {
    unroll! {
        for j in 0..16 {
            let mut v: Vec<u32> = Vec::new();
            let mut offset: u32 = 0;
            for _i in 1..((const_random!(usize) % 4) + 2) {
                let res = ptraceme();
                #[cfg(feature="obfuscate")]
                AA.with (|f| {
                    let mut aa: RefMut<Aa> = f.borrow_mut();
                    goldberg_stmts! {
                        let r = aa.r.rand();
                        match aa.ptrace_state.traceme_done {
                            false => match res {
                                Ok(_) => {
                                    aa.ptrace_state.traceme_done = true;
                                    v.push(r);
                                    for idx in 0..SRSIZE {
                                        offset = offset.wrapping_add(r.wrapping_add(aa.sr[idx % SRSIZE]));
                                    }
                                },
                                Err(_) => the_end(),
                            },
                            true => match res {
                                Ok(_) => the_end(),
                                _ => {
                                    v.push(r);
                                    for idx in 0..SRSIZE {
                                        offset = offset.wrapping_add(r.wrapping_add(aa.sr[idx % SRSIZE]));
                                    }
                                }
                            },
                        }
                        aa.ptrace_state.traceme_ctr = aa.ptrace_state.traceme_ctr.saturating_add(1);
                    }
                });
                #[cfg(not(feature="obfuscate"))]
                AA.with (|f| {
                    let mut aa: RefMut<Aa> = f.borrow_mut();
                    let r = aa.r.rand();
                    match aa.ptrace_state.traceme_done {
                        false => match res {
                            Ok(_) => {
                                aa.ptrace_state.traceme_done = true;
                                v.push(r);
                                for idx in 0..SRSIZE {
                                    offset = offset.wrapping_add(r.wrapping_add(aa.sr[idx % SRSIZE]));
                                }
                            },
                            Err(_) => the_end(),
                        },
                        true => match res {
                            Ok(_) => the_end(),
                            _ => {
                                v.push(r);
                                for idx in 0..SRSIZE {
                                    offset = offset.wrapping_add(r.wrapping_add(aa.sr[idx % SRSIZE]));
                                }
                            }
                        },
                    }
                    aa.ptrace_state.traceme_ctr = aa.ptrace_state.traceme_ctr.saturating_add(1);
                });
            }

            let mut check: u32 = 0;
            AA.with (|f| {
                let aa: RefMut<Aa> = f.borrow_mut();
                for r in v {
                    for idx in 0..SRSIZE {
                        check = check.wrapping_add(r.wrapping_add(aa.sr[idx % SRSIZE]));
                    }
                }
            });

            if check != offset {
                the_end();
            }
        }
    }
}

#[cfg(feature = "obfuscate")]
#[inline(always)]
fn the_end() {
    // Be carefull, optimizer in release mode can decide to remove the following code.
    // let p: *mut u32 = core::ptr::null_mut();
    // unsafe {
    //     *p = 0xFF;
    // }

    let _res =
        unsafe { crate::arch::syscall1(crate::arch::SysNo::SYS_EXIT_GROUP, goldberg_int!(0usize)) };
}
#[cfg(not(feature = "obfuscate"))]
#[inline(always)]
fn the_end() {
    // Be carefull, optimizer in release mode can decide to remove the following code.
    // let p: *mut u32 = core::ptr::null_mut();
    // unsafe {
    //     *p = 0xFF;
    // }

    let _res = unsafe { crate::arch::syscall1(crate::arch::SysNo::SYS_EXIT_GROUP, 0) };
}

#[derive(Debug)]
pub struct Rand {
    x: u32,
    y: u32,
    z: u32,
    w: u32,
}

impl Rand {
    #[cfg(feature = "obfuscate")]
    fn new(seed: u32) -> Rand {
        goldberg_stmts! {
            let kx: u32 = 123456789u32;
            let ky: u32 = 362436069u32;
            let kz: u32 = 521288629u32;
            let kw: u32 = 88675123u32;
            Rand{
                x: kx^seed, y: ky^seed,
                z: kz, w: kw
            }
        }
    }
    #[cfg(not(feature = "obfuscate"))]
    fn new(seed: u32) -> Rand {
        let kx: u32 = 123456789u32;
        let ky: u32 = 362436069u32;
        let kz: u32 = 521288629u32;
        let kw: u32 = 88675123u32;
        Rand {
            x: kx ^ seed,
            y: ky ^ seed,
            z: kz,
            w: kw,
        }
    }

    #[cfg(feature = "obfuscate")]
    fn rand(&mut self) -> u32 {
        goldberg_stmts! {
            let t = self.x^self.x.wrapping_shl(11);
            self.x = self.y; self.y = self.z; self.z = self.w;
            self.w ^= self.w.wrapping_shr(19)^t^t.wrapping_shr(8);
            return self.w;
        }
    }
    #[cfg(not(feature = "obfuscate"))]
    fn rand(&mut self) -> u32 {
        let t = self.x ^ self.x.wrapping_shl(11);
        self.x = self.y;
        self.y = self.z;
        self.z = self.w;
        self.w ^= self.w.wrapping_shr(19) ^ t ^ t.wrapping_shr(8);
        self.w
    }
}

#[cfg(target_os = "linux")]
#[cfg(test)]
mod test {

    use std::thread;
    use std::time::Duration;

    #[test]
    fn multiple_ptraceme_or_die() {
        for i in 0..10 {
            super::Aa::ptraceme_or_die();
            println!("{}", i);
        }

        super::AA.with(|f| {
            assert_eq!(10, f.borrow().ptrace_state.traceme_ctr);
        });
    }

    #[test]
    fn multiple_threads_ptraceme_or_die() {
        let tmp = super::AA.with(|f| f.borrow().ptrace_state.traceme_ctr);

        let threads: Vec<_> = (0..10)
            .map(|i| {
                thread::spawn(move || {
                    super::Aa::ptraceme_or_die();
                    thread::sleep(Duration::from_millis(i * 10));
                    println!("Thread #{}", i);
                    super::Aa::ptraceme_or_die();
                    super::AA.with(|f| {
                        assert_eq!(2, f.borrow().ptrace_state.traceme_ctr);
                    });
                })
            })
            .collect();

        for thread in threads.into_iter() {
            thread.join().unwrap();
        }

        super::AA.with(|f| {
            assert_eq!(tmp, f.borrow().ptrace_state.traceme_ctr);
        });

        println!("END");
        std::process::exit(0);
    }
}