libmwemu 0.24.5

x86 32/64bits and system internals emulator, for securely emulating malware and other stuff.
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! GDB Remote Debugging Support for mwemu
//!
//! This module provides GDB remote debugging protocol support, allowing debuggers
//! like GDB and IDA Pro to connect and debug emulated binaries.

mod breakpoints;
mod registers;
mod target;
mod target_xml;

use std::io::{self, Read as IoRead, Write as IoWrite};
use std::marker::PhantomData;
use std::net::{TcpListener, TcpStream};

use gdbstub::common::Signal;
use gdbstub::conn::ConnectionExt;
use gdbstub::stub::run_blocking::{BlockingEventLoop, Event, WaitForStopReasonError};
use gdbstub::stub::{DisconnectReason, GdbStub, SingleThreadStopReason};
use gdbstub::target::Target;

use crate::arch::Arch;
use crate::emu::Emu;
use target::{MwemuTarget32, MwemuTarget64, MwemuTargetAarch64};

/// Error type for GDB server operations
#[derive(Debug)]
pub enum GdbServerError {
    Io(io::Error),
    Connection(String),
    Protocol(String),
}

impl std::fmt::Display for GdbServerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GdbServerError::Io(e) => write!(f, "IO error: {}", e),
            GdbServerError::Connection(s) => write!(f, "Connection error: {}", s),
            GdbServerError::Protocol(s) => write!(f, "Protocol error: {}", s),
        }
    }
}

impl std::error::Error for GdbServerError {}

impl From<io::Error> for GdbServerError {
    fn from(e: io::Error) -> Self {
        GdbServerError::Io(e)
    }
}

/// GDB Server for mwemu
pub struct GdbServer {
    port: u16,
    arch: Arch,
}

impl GdbServer {
    /// Create a new GDB server instance
    pub fn new(port: u16, arch: Arch) -> Self {
        Self { port, arch }
    }

    /// Start the GDB server and wait for a connection
    pub fn run(&mut self, emu: &mut Emu) -> Result<(), GdbServerError> {
        let listener = TcpListener::bind(format!("127.0.0.1:{}", self.port))?;
        log::info!("GDB server listening on port {}...", self.port);
        log::info!("Connect with: target remote localhost:{}", self.port);

        let (stream, addr) = listener.accept()?;
        log::info!("GDB client connected from {}", addr);

        // Disable console spawning when in GDB mode
        emu.cfg.console_enabled = false;

        match self.arch {
            Arch::Aarch64 => run_aarch64(emu, stream),
            Arch::X86_64 => run_64bit(emu, stream),
            Arch::X86 => run_32bit(emu, stream),
        }
    }
}

fn run_64bit(emu: &mut Emu, stream: TcpStream) -> Result<(), GdbServerError> {
    let conn: Box<dyn ConnectionExt<Error = io::Error>> = Box::new(GdbConnection::new(stream));

    let mut target = MwemuTarget64::new(emu);

    let gdb = GdbStub::new(conn);

    match gdb.run_blocking::<MwemuEventLoop64<'_>>(&mut target) {
        Ok(disconnect_reason) => {
            match disconnect_reason {
                DisconnectReason::Disconnect => {
                    log::info!("GDB client disconnected");
                }
                DisconnectReason::TargetExited(code) => {
                    log::info!("Target exited with code {}", code);
                }
                DisconnectReason::TargetTerminated(sig) => {
                    log::info!("Target terminated with signal {:?}", sig);
                }
                DisconnectReason::Kill => {
                    log::info!("GDB sent kill command");
                }
            }
            Ok(())
        }
        Err(e) => Err(GdbServerError::Protocol(format!("GDB error: {:?}", e))),
    }
}

fn run_aarch64(emu: &mut Emu, stream: TcpStream) -> Result<(), GdbServerError> {
    let conn: Box<dyn ConnectionExt<Error = io::Error>> = Box::new(GdbConnection::new(stream));

    let mut target = MwemuTargetAarch64::new(emu);

    let gdb = GdbStub::new(conn);

    match gdb.run_blocking::<MwemuEventLoopAarch64<'_>>(&mut target) {
        Ok(disconnect_reason) => {
            match disconnect_reason {
                DisconnectReason::Disconnect => {
                    log::info!("GDB client disconnected");
                }
                DisconnectReason::TargetExited(code) => {
                    log::info!("Target exited with code {}", code);
                }
                DisconnectReason::TargetTerminated(sig) => {
                    log::info!("Target terminated with signal {:?}", sig);
                }
                DisconnectReason::Kill => {
                    log::info!("GDB sent kill command");
                }
            }
            Ok(())
        }
        Err(e) => Err(GdbServerError::Protocol(format!("GDB error: {:?}", e))),
    }
}

fn run_32bit(emu: &mut Emu, stream: TcpStream) -> Result<(), GdbServerError> {
    let conn: Box<dyn ConnectionExt<Error = io::Error>> = Box::new(GdbConnection::new(stream));

    let mut target = MwemuTarget32::new(emu);

    let gdb = GdbStub::new(conn);

    match gdb.run_blocking::<MwemuEventLoop32<'_>>(&mut target) {
        Ok(disconnect_reason) => {
            match disconnect_reason {
                DisconnectReason::Disconnect => {
                    log::info!("GDB client disconnected");
                }
                DisconnectReason::TargetExited(code) => {
                    log::info!("Target exited with code {}", code);
                }
                DisconnectReason::TargetTerminated(sig) => {
                    log::info!("Target terminated with signal {:?}", sig);
                }
                DisconnectReason::Kill => {
                    log::info!("GDB sent kill command");
                }
            }
            Ok(())
        }
        Err(e) => Err(GdbServerError::Protocol(format!("GDB error: {:?}", e))),
    }
}

/// Wrapper around TcpStream that implements ConnectionExt
struct GdbConnection {
    stream: TcpStream,
    peeked_byte: Option<u8>,
}

impl GdbConnection {
    fn new(stream: TcpStream) -> Self {
        Self {
            stream,
            peeked_byte: None,
        }
    }
}

impl gdbstub::conn::Connection for GdbConnection {
    type Error = io::Error;

    fn write(&mut self, byte: u8) -> Result<(), Self::Error> {
        IoWrite::write_all(&mut self.stream, &[byte])
    }

    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
        IoWrite::write_all(&mut self.stream, buf)
    }

    fn flush(&mut self) -> Result<(), Self::Error> {
        IoWrite::flush(&mut self.stream)
    }

    fn on_session_start(&mut self) -> Result<(), Self::Error> {
        // Set to blocking mode for session
        self.stream.set_nonblocking(false)?;
        Ok(())
    }
}

impl ConnectionExt for GdbConnection {
    fn read(&mut self) -> Result<u8, Self::Error> {
        if let Some(byte) = self.peeked_byte.take() {
            return Ok(byte);
        }
        let mut buf = [0u8; 1];
        IoRead::read_exact(&mut self.stream, &mut buf)?;
        Ok(buf[0])
    }

    fn peek(&mut self) -> Result<Option<u8>, Self::Error> {
        if self.peeked_byte.is_some() {
            return Ok(self.peeked_byte);
        }

        // Try non-blocking read
        self.stream.set_nonblocking(true)?;
        let mut buf = [0u8; 1];
        let result: io::Result<usize> = IoRead::read(&mut self.stream, &mut buf);
        match result {
            Ok(1) => {
                self.peeked_byte = Some(buf[0]);
                self.stream.set_nonblocking(false)?;
                Ok(Some(buf[0]))
            }
            Ok(_) => {
                self.stream.set_nonblocking(false)?;
                Ok(None)
            }
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                self.stream.set_nonblocking(false)?;
                Ok(None)
            }
            Err(e) => {
                let _ = self.stream.set_nonblocking(false);
                Err(e)
            }
        }
    }
}

/// Event loop implementation for 64-bit targets
struct MwemuEventLoop64<'a>(PhantomData<&'a mut Emu>);

impl<'a> BlockingEventLoop for MwemuEventLoop64<'a> {
    type Target = MwemuTarget64<'a>;
    type Connection = Box<dyn ConnectionExt<Error = io::Error>>;
    type StopReason = SingleThreadStopReason<u64>;

    fn wait_for_stop_reason(
        target: &mut Self::Target,
        conn: &mut Self::Connection,
    ) -> Result<
        Event<Self::StopReason>,
        WaitForStopReasonError<
            <Self::Target as Target>::Error,
            <Self::Connection as gdbstub::conn::Connection>::Error,
        >,
    > {
        loop {
            // Check for interrupt from GDB (Ctrl+C)
            match conn.peek() {
                Ok(Some(0x03)) => {
                    // Consume the byte
                    let _ = conn.read();
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Signal(Signal::SIGINT)));
                }
                Ok(Some(byte)) => {
                    return Ok(Event::IncomingData(byte));
                }
                Ok(None) => {}
                Err(e) => return Err(WaitForStopReasonError::Connection(e)),
            }

            // Check if we hit a breakpoint before executing
            let rip = target.emu.regs().rip;
            if target.emu.bp.is_bp(rip) && !target.single_step {
                return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(())));
            }

            // Single step mode - return after one instruction
            if target.single_step {
                target.single_step = false;
                return Ok(Event::TargetStopped(SingleThreadStopReason::DoneStep));
            }

            // Execute one instruction
            let result = target.emu.step();
            if !result {
                // Emulation ended
                return Ok(Event::TargetStopped(SingleThreadStopReason::Terminated(
                    Signal::SIGTERM,
                )));
            }

            // Check if a library was loaded during this step
            if target.emu.library_loaded {
                target.emu.library_loaded = false;
                return Ok(Event::TargetStopped(SingleThreadStopReason::Library(())));
            }

            // Check for memory watchpoints
            for mem_op in &target.emu.memory_operations {
                if target.emu.bp.is_bp_mem_read(mem_op.address) {
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Watch {
                        tid: (),
                        kind: gdbstub::target::ext::breakpoints::WatchKind::Read,
                        addr: mem_op.address,
                    }));
                }
                if target.emu.bp.is_bp_mem_write_addr(mem_op.address) {
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Watch {
                        tid: (),
                        kind: gdbstub::target::ext::breakpoints::WatchKind::Write,
                        addr: mem_op.address,
                    }));
                }
            }

            // Check for breakpoint after step
            let rip = target.emu.regs().rip;
            if target.emu.bp.is_bp(rip) {
                return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(())));
            }
        }
    }

    fn on_interrupt(
        _target: &mut Self::Target,
    ) -> Result<Option<Self::StopReason>, <Self::Target as Target>::Error> {
        Ok(Some(SingleThreadStopReason::Signal(Signal::SIGINT)))
    }
}

/// Event loop implementation for AArch64 targets
struct MwemuEventLoopAarch64<'a>(PhantomData<&'a mut Emu>);

impl<'a> BlockingEventLoop for MwemuEventLoopAarch64<'a> {
    type Target = MwemuTargetAarch64<'a>;
    type Connection = Box<dyn ConnectionExt<Error = io::Error>>;
    type StopReason = SingleThreadStopReason<u64>;

    fn wait_for_stop_reason(
        target: &mut Self::Target,
        conn: &mut Self::Connection,
    ) -> Result<
        Event<Self::StopReason>,
        WaitForStopReasonError<
            <Self::Target as Target>::Error,
            <Self::Connection as gdbstub::conn::Connection>::Error,
        >,
    > {
        loop {
            // Check for interrupt from GDB (Ctrl+C)
            match conn.peek() {
                Ok(Some(0x03)) => {
                    let _ = conn.read();
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Signal(Signal::SIGINT)));
                }
                Ok(Some(byte)) => {
                    return Ok(Event::IncomingData(byte));
                }
                Ok(None) => {}
                Err(e) => return Err(WaitForStopReasonError::Connection(e)),
            }

            // Check if we hit a breakpoint before executing
            let pc = target.emu.regs_aarch64().pc;
            if target.emu.bp.is_bp(pc) && !target.single_step {
                return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(())));
            }

            // Single step mode - return after one instruction
            if target.single_step {
                target.single_step = false;
                return Ok(Event::TargetStopped(SingleThreadStopReason::DoneStep));
            }

            // Execute one instruction
            let result = target.emu.step();
            if !result {
                return Ok(Event::TargetStopped(SingleThreadStopReason::Terminated(
                    Signal::SIGTERM,
                )));
            }

            // Check if a library was loaded during this step
            if target.emu.library_loaded {
                target.emu.library_loaded = false;
                return Ok(Event::TargetStopped(SingleThreadStopReason::Library(())));
            }

            // Check for memory watchpoints
            for mem_op in &target.emu.memory_operations {
                if target.emu.bp.is_bp_mem_read(mem_op.address) {
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Watch {
                        tid: (),
                        kind: gdbstub::target::ext::breakpoints::WatchKind::Read,
                        addr: mem_op.address,
                    }));
                }
                if target.emu.bp.is_bp_mem_write_addr(mem_op.address) {
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Watch {
                        tid: (),
                        kind: gdbstub::target::ext::breakpoints::WatchKind::Write,
                        addr: mem_op.address,
                    }));
                }
            }

            // Check for breakpoint after step
            let pc = target.emu.regs_aarch64().pc;
            if target.emu.bp.is_bp(pc) {
                return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(())));
            }
        }
    }

    fn on_interrupt(
        _target: &mut Self::Target,
    ) -> Result<Option<Self::StopReason>, <Self::Target as Target>::Error> {
        Ok(Some(SingleThreadStopReason::Signal(Signal::SIGINT)))
    }
}

/// Event loop implementation for 32-bit targets
struct MwemuEventLoop32<'a>(PhantomData<&'a mut Emu>);

impl<'a> BlockingEventLoop for MwemuEventLoop32<'a> {
    type Target = MwemuTarget32<'a>;
    type Connection = Box<dyn ConnectionExt<Error = io::Error>>;
    type StopReason = SingleThreadStopReason<u32>;

    fn wait_for_stop_reason(
        target: &mut Self::Target,
        conn: &mut Self::Connection,
    ) -> Result<
        Event<Self::StopReason>,
        WaitForStopReasonError<
            <Self::Target as Target>::Error,
            <Self::Connection as gdbstub::conn::Connection>::Error,
        >,
    > {
        loop {
            // Check for interrupt from GDB (Ctrl+C)
            match conn.peek() {
                Ok(Some(0x03)) => {
                    // Consume the byte
                    let _ = conn.read();
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Signal(Signal::SIGINT)));
                }
                Ok(Some(byte)) => {
                    return Ok(Event::IncomingData(byte));
                }
                Ok(None) => {}
                Err(e) => return Err(WaitForStopReasonError::Connection(e)),
            }

            // Check if we hit a breakpoint before executing
            let eip = target.emu.regs().get_eip() as u32;
            if target.emu.bp.is_bp(eip as u64) && !target.single_step {
                return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(())));
            }

            // Single step mode - return after one instruction
            if target.single_step {
                target.single_step = false;
                return Ok(Event::TargetStopped(SingleThreadStopReason::DoneStep));
            }

            // Execute one instruction
            let result = target.emu.step();
            if !result {
                // Emulation ended
                return Ok(Event::TargetStopped(SingleThreadStopReason::Terminated(
                    Signal::SIGTERM,
                )));
            }

            // Check if a library was loaded during this step
            if target.emu.library_loaded {
                target.emu.library_loaded = false;
                return Ok(Event::TargetStopped(SingleThreadStopReason::Library(())));
            }

            // Check for memory watchpoints
            for mem_op in &target.emu.memory_operations {
                if target.emu.bp.is_bp_mem_read(mem_op.address) {
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Watch {
                        tid: (),
                        kind: gdbstub::target::ext::breakpoints::WatchKind::Read,
                        addr: mem_op.address as u32,
                    }));
                }
                if target.emu.bp.is_bp_mem_write_addr(mem_op.address) {
                    return Ok(Event::TargetStopped(SingleThreadStopReason::Watch {
                        tid: (),
                        kind: gdbstub::target::ext::breakpoints::WatchKind::Write,
                        addr: mem_op.address as u32,
                    }));
                }
            }

            // Check for breakpoint after step
            let eip = target.emu.regs().get_eip() as u32;
            if target.emu.bp.is_bp(eip as u64) {
                return Ok(Event::TargetStopped(SingleThreadStopReason::SwBreak(())));
            }
        }
    }

    fn on_interrupt(
        _target: &mut Self::Target,
    ) -> Result<Option<Self::StopReason>, <Self::Target as Target>::Error> {
        Ok(Some(SingleThreadStopReason::Signal(Signal::SIGINT)))
    }
}