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
extern crate serde;
extern crate serde_json;
extern crate argparse;
extern crate memmap;
use memmap::Mmap;
extern crate reqwest;
extern crate url;
extern crate pdb;
#[macro_use]
extern crate nom;
use nom::{be_u64, le_u32, le_u16};
extern crate xori;
use xori::configuration::*;
use xori::analysis::formats::pe::*;
use xori::arch::x86::analyzex86::{Symbol, Export, ExportDirectory};
extern crate base64;
use std::path::Path;
use argparse::{ArgumentParser, Store};
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
use url::Url;
use reqwest::Client;
use reqwest::header::UserAgent;
#[allow(dead_code)]
fn download_pdb(
url: &String,
user_agent: &String,
_dll_basename: &String,
pdb_name: &String,
guid: &String,
output_dir: &Path) -> Option<::std::path::PathBuf>
{
let mut output_pdb = pdb_name.clone();
output_pdb.pop();
output_pdb.push('_');
let output_path = Path::new(output_dir).join(output_pdb);
if output_path.exists()
{
return Some(output_path);
}
let url = Url::parse(&format!("{}{}/{}/{}",url, pdb_name, guid, pdb_name))
.expect("error: Url perser failed");
println!("{}\n{}", url, user_agent);
let mut response = Client::new()
.get(url)
.header(UserAgent::new(user_agent.clone()))
.send()
.expect("Failed to send request");
if response.status() == reqwest::StatusCode::Unregistered(200)
{
let mut buffer: Vec<u8> = Vec::new();
response.read_to_end(&mut buffer)
.expect("Failed to read response");
let mut f = File::create(&output_path)
.expect("error: filed to create file");
let _result = f.write_all(&buffer);
} else {
println!("error: response failed. {:?}", response.status());
return None;
}
return Some(output_path);
}
fn extract_exports(dll_path: &Path) -> Option<(Vec<Export>, SectionTable, String, ExportDirectory)>
{
let file = std::fs::File::open(dll_path).expect("failed to open the file");
let mmap = unsafe { Mmap::map(&file).expect("failed to map the file") };
let pe_offset;
let mut dll_exports: Vec<Export> = Vec::new();
match dos_header(&mmap){
Ok((_cursor, o))=> {
pe_offset = o.e_lfanew as usize;
},
_=> {
println!("error or incomplete DOS Header");
panic!("cannot parse DOS Header");
}
}
let export_table_offset;
let export_table_size;
let _bits;
match pe_header(&mmap[pe_offset..])
{
Ok((cursor, peh)) => {
match peh.image_optional_header {
ImageOptionalHeaderKind::Pe32(ioh) => {
export_table_offset = ioh.image_data_directory[ImageDataIndex::ExportTable as usize]
.virtual_address;
export_table_size = ioh.image_data_directory[ImageDataIndex::ExportTable as usize]
.size;
_bits = 32;
}
ImageOptionalHeaderKind::Pe32Plus(ioh) => {
export_table_offset = ioh.image_data_directory[ImageDataIndex::ExportTable as usize]
.virtual_address;
export_table_size = ioh.image_data_directory[ImageDataIndex::ExportTable as usize]
.size;
_bits = 64;
}
}
let dll_section_table: SectionTable = match section_table(cursor, peh.coff_header.num_sections)
{
Ok((_i, section_table))=>section_table,
Err(_err)=> return None,
};
let (header_copy, export_dir) = build_dll_header_with_exportrva(
&mmap,
export_table_offset as usize,
rva_to_file_offset(export_table_offset as usize, &dll_section_table) as usize,
export_table_size as usize);
let export_descriptor: ImageExportDescriptor = match image_export_descriptor(
&mmap[rva_to_file_offset(export_table_offset as usize, &dll_section_table)..])
{
Ok((_i, export_desc))=> export_desc,
Err(_err)=> return None,
};
let _dllname = match import_dll_name(
&mmap[rva_to_file_offset(export_descriptor.name as usize, &dll_section_table,)..],)
{
Ok((_i, dllname)) => dllname,
Err(_err)=> return None,
};
let address_of_functions = match export_table_entry(
&mmap[rva_to_file_offset(export_descriptor.address_of_functions as usize, &dll_section_table,)..],
export_descriptor.number_of_functions as usize)
{
Ok((_i, func_addr)) => func_addr,
Err(_err)=> return None,
};
let address_of_names = match export_table_entry(
&mmap[rva_to_file_offset(export_descriptor.address_of_names as usize, &dll_section_table,)..],
export_descriptor.number_of_names as usize)
{
Ok((_i, addr_names)) => addr_names,
Err(_err)=> return None,
};
let address_of_name_ordinals = match export_table_ord(
&mmap[rva_to_file_offset(export_descriptor.address_of_name_ordinals as usize, &dll_section_table,)..],
export_descriptor.number_of_names as usize)
{
Ok((_i, func_addr)) => func_addr,
Err(_err)=> return None,
};
for i in 0..export_descriptor.number_of_names as usize
{
let mut forwarder = false;
let mut forwarder_name = String::new();
let name_addr = address_of_names.as_slice()[i];
let func_ordinal = address_of_name_ordinals.as_slice()[i];
let func_addr = address_of_functions.as_slice()[func_ordinal as usize];
if func_addr >= export_table_offset &&
func_addr < export_table_offset+export_table_size
{
forwarder = true;
forwarder_name = match import_dll_name(
&mmap[rva_to_file_offset(func_addr as usize, &dll_section_table,)..],)
{
Ok((_i, export_name)) => export_name.name,
Err(_err)=>String::new(),
};
}
let export_name = match import_dll_name(
&mmap[rva_to_file_offset(name_addr as usize, &dll_section_table,)..],)
{
Ok((_i, export_name)) => export_name.name,
Err(_err)=>String::new(),
};
dll_exports.push(
Export
{
name: export_name,
rva: func_addr as u64,
ordinal: func_ordinal + export_descriptor.base as u16,
forwarder: forwarder,
forwarder_name: forwarder_name,
});
}
return Some((dll_exports, dll_section_table,header_copy, export_dir));
},
_=>{},
}
return None;
}
#[derive(Debug)]
pub struct PdbDir {
guid: String,
path: String
}
#[allow(dead_code)]
fn get_guid(path: &Path) -> PdbDir
{
let file = File::open(path)
.expect("failed to open the file");
let mmap = unsafe { Mmap::map(&file)
.expect("failed to map the file") };
named!(find_dir, take_until_and_consume!("RSDS"));
named!(guid<&[u8], (u32, u16, u16, u64, u32) >,
tuple!(
le_u32,
le_u16,
le_u16,
be_u64,
le_u32
)
);
named!(pdb_path<&[u8], &[u8]>,
take_until_and_consume!("\0"));
let res = find_dir(&mmap);
let guid_res;
match res {
Ok((i, _o)) => { guid_res = guid(i).unwrap() }
_ => return PdbDir{ guid: "".to_string(), path: "".to_string() }
}
return PdbDir {
guid: format!("{:08X}{:04X}{:04X}{:08X}{}",
(guid_res.1).0,
(guid_res.1).1,
(guid_res.1).2,
(guid_res.1).3,
(guid_res.1).4),
path: String::from_utf8(pdb_path(guid_res.0)
.unwrap().1.to_vec()).unwrap_or("".to_string())
}
}
fn build_dll_header_with_exportrva(
_binary: &[u8],
export_table_rva: usize,
export_table_offset: usize,
export_table_size: usize) -> (String, ExportDirectory)
{
let length = 0x320;
let mut new_header: Vec<u8> = Vec::with_capacity(length);
let mut new_exp_dir: Vec<u8> = Vec::with_capacity(export_table_size);
new_header.extend_from_slice(&_binary[0..length]);
let export_table_length = export_table_offset + export_table_size;
new_exp_dir.extend_from_slice(&_binary[export_table_offset..export_table_length]);
let header_encoded = base64::encode(&new_header);
let export_dir_encoded = base64::encode(&new_exp_dir);
return (header_encoded, ExportDirectory{
offset: export_table_rva,
size: export_table_size,
data_b64: export_dir_encoded,
data: Vec::new(),
})
}
fn main()
{
let mut config_file: String = String::new();
{
let mut ap = ArgumentParser::new();
ap.set_description("downloads pdb files to output json");
ap.refer(&mut config_file).add_option(
&["--config", "-c"],
Store,
"load a specific configuration or else default values are used.",
);
ap.parse_args_or_exit();
}
let mut config_map: Config = Config::new();
let conf_path = Path::new(&config_file);
if conf_path.exists()
{
config_map = read_config(&conf_path);
}
else if Path::new("xori.json").exists()
{
config_map = read_config(&Path::new("xori.json"));
}
else {
println!("error: config file does not exist, using default configurations.");
}
let _url = config_map.x86.pe_file.symbol_server.url;
let _url = config_map.x86.pe_file.symbol_server.user_agent;
let dllfolder32 = config_map.x86.pe_file.symbol_server.dll_folder32;
let dllfolder64 = config_map.x86.pe_file.symbol_server.dll_folder64;
let dll32 = Path::new(&dllfolder32);
let dll64 = Path::new(&dllfolder64);
if dll32.exists()
{
println!("Getting 32bit symbols.");
let mut symbols32: Vec<Symbol> = Vec::new();
let paths = fs::read_dir(dll32).expect("error: dll folder32 is empty");
for path in paths
{
let dll_path = path.unwrap().path();
match dll_path.extension()
{
Some(ref extension)=>{
if *extension == "dll"
{
let (dll_exports, _section_table, header_copy, export_dir) = match extract_exports(&dll_path)
{
Some((exports, section_table, header_copy, export_dir))=>(exports, section_table,header_copy,export_dir),
None=>return,
};
let dll_basename = String::from(dll_path
.file_name().unwrap().to_str().unwrap_or(""));
symbols32.push(Symbol
{
name: dll_basename.to_lowercase(),
exports: dll_exports,
virtual_address: 0,
is_imported: false,
header_b64: header_copy,
header: Vec::new(),
export_dir: export_dir,
})
}
},
_=>{},
}
}
if symbols32.len() > 0
{
let symbols_output = config_map.x86.pe_file.function_symbol32;
let symbols = serde_json::to_string_pretty(&symbols32).unwrap();
let mut file = File::create(symbols_output)
.expect("error: Could not create symbols json file");
let _result = file.write_all(symbols.as_bytes());
}
}
else {
println!("error: Dll folder does not exist.");
}
if dll64.exists()
{
println!("Getting 64bit symbols.");
let mut symbols64: Vec<Symbol> = Vec::new();
let paths = fs::read_dir(dll64).expect("error: dll folder64 is empty");
for path in paths
{
let dll_path = path.unwrap().path();
match dll_path.extension()
{
Some(ref extension)=>{
if *extension == "dll"
{
let (dll_exports, _section_table, header_copy, export_dir) = match extract_exports(&dll_path)
{
Some((exports, section_table, header_copy, export_dir))=>(exports, section_table,header_copy,export_dir),
None=>return,
};
let dll_basename = String::from(dll_path
.file_name().unwrap().to_str().unwrap_or(""));
symbols64.push(Symbol
{
name: dll_basename.to_lowercase(),
exports: dll_exports,
virtual_address: 0,
is_imported: false,
header_b64: header_copy,
header: Vec::new(),
export_dir: export_dir,
})
}
},
_=>{},
}
}
if symbols64.len() > 0
{
let symbols_output = config_map.x86.pe_file.function_symbol64;
let symbols = serde_json::to_string_pretty(&symbols64).unwrap();
let mut file = File::create(symbols_output)
.expect("error: Could not create symbols json file");
let _result = file.write_all(symbols.as_bytes());
}
}
else {
println!("error: Dll folder does not exist.");
}
}