lazy_importer 0.1.3

Rust port of Justas Masiulis's lazy_importer for Windows module and export resolution.
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
use crate::hash;
use crate::types::{
    ApiSetNamespace, ApiSetNamespaceEntry, ApiSetValueEntry, LdrDataTableEntry, ListEntry, Peb,
    PebLdrData, UnicodeString,
};

const MAX_API_SET_ENTRIES: u32 = 8192;
const MAX_API_SET_VALUES: u32 = 64;
const MAX_MODULES: usize = 4096;

#[cfg(all(windows, target_arch = "x86_64"))]
#[inline]
pub(crate) unsafe fn peb() -> *const Peb {
    let peb: *const Peb;
    unsafe {
        core::arch::asm!(
            "mov {}, gs:[0x60]",
            out(reg) peb,
            options(nostack, preserves_flags, readonly)
        );
    }
    peb
}

#[cfg(all(windows, target_arch = "x86"))]
#[inline]
pub(crate) unsafe fn peb() -> *const Peb {
    let peb: *const Peb;
    unsafe {
        core::arch::asm!(
            "mov {}, fs:[0x30]",
            out(reg) peb,
            options(nostack, preserves_flags, readonly)
        );
    }
    peb
}

#[cfg(all(windows, target_arch = "aarch64"))]
#[inline]
pub(crate) unsafe fn peb() -> *const Peb {
    let teb: usize;
    unsafe {
        core::arch::asm!(
            "mov {}, x18",
            out(reg) teb,
            options(nostack, preserves_flags)
        );
    }

    unsafe { *((teb + 0x60) as *const *const Peb) }
}

#[cfg(not(windows))]
#[inline]
pub(crate) unsafe fn peb() -> *const Peb {
    core::ptr::null()
}

#[cfg(all(
    windows,
    not(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))
))]
compile_error!("lazy_importer currently supports Windows x86, x86_64, and aarch64 targets.");

#[inline]
unsafe fn ldr() -> Option<*const PebLdrData> {
    let peb = unsafe { peb() };
    if peb.is_null() {
        return None;
    }

    let ldr = unsafe { (*peb).ldr };
    if ldr.is_null() { None } else { Some(ldr) }
}

#[inline]
unsafe fn api_set_map() -> Option<*const ApiSetNamespace> {
    let peb = unsafe { peb() };
    if peb.is_null() {
        return None;
    }

    let api_set_map = unsafe { (*peb).api_set_map };
    if api_set_map.is_null() {
        None
    } else {
        Some(api_set_map)
    }
}

pub(crate) struct LoadedModules {
    head: *const ListEntry,
    current: *const ListEntry,
    remaining: usize,
}

impl LoadedModules {
    #[inline]
    pub(crate) unsafe fn new() -> Option<Self> {
        let ldr = unsafe { ldr()? };
        let head = unsafe { core::ptr::addr_of!((*ldr).in_load_order_module_list) };
        let current = unsafe { (*head).flink };

        if current.is_null() {
            return None;
        }

        Some(Self {
            head,
            current,
            remaining: MAX_MODULES,
        })
    }
}

impl Iterator for LoadedModules {
    type Item = *const LdrDataTableEntry;

    fn next(&mut self) -> Option<Self::Item> {
        while self.remaining > 0 {
            self.remaining -= 1;

            if self.current.is_null() || self.current == self.head {
                return None;
            }

            let entry = self.current.cast::<LdrDataTableEntry>();
            self.current = unsafe { (*self.current).flink };

            if !entry.is_null() && !unsafe { (*entry).dll_base }.is_null() {
                return Some(entry);
            }
        }

        None
    }
}

#[inline]
pub(crate) unsafe fn hash_unicode_string(name: UnicodeString, offset: u32) -> Option<u32> {
    if name.buffer.is_null() {
        return None;
    }

    Some(unsafe { hash::hash_wide(name.buffer, name.len_u16(), offset) })
}

#[inline]
pub(crate) unsafe fn hash_unicode_string_without_dll(
    name: UnicodeString,
    offset: u32,
) -> Option<u32> {
    if name.buffer.is_null() {
        return None;
    }

    Some(unsafe { hash::hash_wide_without_dll(name.buffer, name.len_u16(), offset) })
}

#[inline]
pub(crate) unsafe fn hash_unicode_string_without_dll_case_insensitive(
    name: UnicodeString,
    offset: u32,
) -> Option<u32> {
    if name.buffer.is_null() {
        return None;
    }

    Some(unsafe {
        hash::hash_wide_without_dll_case_insensitive(name.buffer, name.len_u16(), offset)
    })
}

pub(crate) unsafe fn api_set_host_hash_by_name(
    contract_name: *const u8,
    contract_name_len: usize,
    parent_name: Option<UnicodeString>,
    offset: u32,
) -> Option<u32> {
    if contract_name.is_null() || contract_name_len == 0 {
        return None;
    }

    let namespace = unsafe { api_set_map()? };
    let count = unsafe { (*namespace).count };

    if count == 0 || count > MAX_API_SET_ENTRIES {
        return None;
    }

    let base = namespace.cast::<u8>();
    let entries = unsafe {
        base.add((*namespace).entry_offset as usize)
            .cast::<ApiSetNamespaceEntry>()
    };

    let mut index = 0;
    while index < count {
        let entry = unsafe { &*entries.add(index as usize) };
        let name = unsafe { base.add(entry.name_offset as usize).cast::<u16>() };
        let name_len = (entry.name_length as usize) / core::mem::size_of::<u16>();
        let hashed_len = (entry.hashed_length as usize) / core::mem::size_of::<u16>();

        if !name.is_null()
            && unsafe {
                api_set_name_matches(name, name_len, hashed_len, contract_name, contract_name_len)
            }
        {
            return unsafe { host_hash_from_api_set_entry(base, entry, parent_name, offset) };
        }

        index += 1;
    }

    None
}

unsafe fn api_set_name_matches(
    name: *const u16,
    name_len: usize,
    hashed_len: usize,
    contract_name: *const u8,
    contract_name_len: usize,
) -> bool {
    if unsafe {
        wide_equals_ascii_case_insensitive(name, name_len, contract_name, contract_name_len)
    } {
        return true;
    }

    hashed_len != 0
        && hashed_len <= name_len
        && hashed_len <= contract_name_len
        && unsafe {
            wide_equals_ascii_case_insensitive(name, hashed_len, contract_name, hashed_len)
        }
}

unsafe fn wide_equals_ascii_case_insensitive(
    wide: *const u16,
    wide_len: usize,
    ascii: *const u8,
    ascii_len: usize,
) -> bool {
    if wide_len != ascii_len {
        return false;
    }

    let mut index = 0;
    while index < wide_len {
        let wide_byte = unsafe { *wide.add(index) } as u8;
        let ascii_byte = unsafe { *ascii.add(index) };

        if fold_ascii(wide_byte) != fold_ascii(ascii_byte) {
            return false;
        }

        index += 1;
    }

    true
}

unsafe fn wide_equals_wide_case_insensitive(
    left: *const u16,
    left_len: usize,
    right: *const u16,
    right_len: usize,
) -> bool {
    if left_len != right_len {
        return false;
    }

    let mut index = 0;
    while index < left_len {
        let left_byte = unsafe { *left.add(index) } as u8;
        let right_byte = unsafe { *right.add(index) } as u8;

        if fold_ascii(left_byte) != fold_ascii(right_byte) {
            return false;
        }

        index += 1;
    }

    true
}

unsafe fn wide_equals_wide_case_insensitive_without_dll(
    left: *const u16,
    left_len: usize,
    right: *const u16,
    right_len: usize,
) -> bool {
    unsafe {
        wide_equals_wide_case_insensitive(
            left,
            len_without_dll(left, left_len),
            right,
            len_without_dll(right, right_len),
        )
    }
}

unsafe fn len_without_dll(ptr: *const u16, len: usize) -> usize {
    if len < 4 {
        return len;
    }

    let suffix = len - 4;
    let dot = unsafe { *ptr.add(suffix) } as u8;
    let d = unsafe { *ptr.add(suffix + 1) } as u8;
    let l1 = unsafe { *ptr.add(suffix + 2) } as u8;
    let l2 = unsafe { *ptr.add(suffix + 3) } as u8;

    if dot == b'.' && fold_ascii(d) == b'd' && fold_ascii(l1) == b'l' && fold_ascii(l2) == b'l' {
        suffix
    } else {
        len
    }
}

#[inline]
const fn fold_ascii(byte: u8) -> u8 {
    if byte >= b'A' && byte <= b'Z' {
        byte | (1 << 5)
    } else {
        byte
    }
}

unsafe fn host_hash_from_api_set_entry(
    base: *const u8,
    entry: &ApiSetNamespaceEntry,
    parent_name: Option<UnicodeString>,
    offset: u32,
) -> Option<u32> {
    if entry.value_count == 0 || entry.value_count > MAX_API_SET_VALUES {
        return None;
    }

    let values = unsafe {
        base.add(entry.value_offset as usize)
            .cast::<ApiSetValueEntry>()
    };
    let mut default_host = None;
    let mut first_host = None;
    let mut index = 0;

    while index < entry.value_count {
        let value = unsafe { &*values.add(index as usize) };

        if value.value_length != 0 {
            let host = unsafe { base.add(value.value_offset as usize).cast::<u16>() };
            let host_len = (value.value_length as usize) / core::mem::size_of::<u16>();
            let host_hash =
                unsafe { hash::hash_wide_without_dll_case_insensitive(host, host_len, offset) };

            first_host = first_host.or(Some(host_hash));

            if value.name_length == 0 {
                default_host = Some(host_hash);
                index += 1;
                continue;
            }

            if let Some(parent_name) = parent_name {
                let name = unsafe { base.add(value.name_offset as usize).cast::<u16>() };
                let name_len = (value.name_length as usize) / core::mem::size_of::<u16>();

                if !name.is_null()
                    && !parent_name.buffer.is_null()
                    && unsafe {
                        wide_equals_wide_case_insensitive_without_dll(
                            name,
                            name_len,
                            parent_name.buffer,
                            parent_name.len_u16(),
                        )
                    }
                {
                    return Some(host_hash);
                }
            }
        }

        index += 1;
    }

    default_host.or(first_host)
}

pub(crate) unsafe fn base_name_for_module(
    module_base: *mut core::ffi::c_void,
) -> Option<UnicodeString> {
    let modules = unsafe { LoadedModules::new()? };

    for entry in modules {
        if unsafe { (*entry).dll_base } == module_base {
            return Some(unsafe { (*entry).base_dll_name });
        }
    }

    None
}