parse_hex_string

Function parse_hex_string 

Source
pub fn parse_hex_string(hex_string: &str) -> Result<Vec<u8>, String>
Expand description

Parse hex string in various formats:

  • “4D5A90” (continuous)
  • “4D 5A 90” (space separated)
  • “0x4D, 0x5A, 0x90” (C-style array)
  • “0x4D,0x5A,0x90” (C-style without spaces)
  • “\x4D\x5A\x90” (escaped format)
Examples found in repository?
examples/from_hex.rs (line 22)
6fn main() {
7    init();
8
9    println!("[*] From Hex String Example\n");
10
11    // Example: Various hex formats supported
12    let hex_formats = [
13        ("Continuous", "4D5A90000300000004000000FFFF0000"),
14        ("Spaced", "4D 5A 90 00 03 00 00 00"),
15        ("C-style", "0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00"),
16        ("Escaped", "\\x4D\\x5A\\x90\\x00\\x03\\x00"),
17    ];
18
19    println!("[*] Supported hex formats:\n");
20    
21    for (name, hex) in &hex_formats {
22        match parse_hex_string(hex) {
23            Ok(bytes) => {
24                println!("    {}: {} -> {:02X?}", name, hex, &bytes[..bytes.len().min(4)]);
25            }
26            Err(e) => {
27                println!("    {}: Error - {}", name, e);
28            }
29        }
30    }
31
32    println!();
33
34    // For actual execution, you would use a complete PE file in hex
35    // This is just a demonstration of the parsing
36    
37    let sample_hex = "0x4D, 0x5A, 0x90, 0x00"; // MZ header start
38    
39    match GhostingBuilder::from_hex_string(sample_hex) {
40        Ok(builder) => {
41            println!("[+] Successfully parsed hex string");
42            println!("[*] Payload size: {} bytes", builder.build().payload.len());
43            
44            // Note: This would fail with just the header
45            // In real usage, provide complete PE bytes
46            // builder.x64().execute();
47        }
48        Err(e) => {
49            eprintln!("[-] Failed to parse: {}", e);
50        }
51    }
52}
More examples
Hide additional examples
examples/error_handling.rs (line 21)
6fn main() {
7    init();
8
9    println!("[*] Error Handling Example\n");
10
11    // Test 1: Invalid file
12    println!("[Test 1] Loading non-existent file:");
13    match GhostingBuilder::from_file("nonexistent.exe") {
14        Ok(_) => println!("    Unexpected success"),
15        Err(e) => println!("    Expected error: {}", e),
16    }
17    println!();
18
19    // Test 2: Invalid hex string
20    println!("[Test 2] Parsing invalid hex:");
21    match parse_hex_string("ZZZZ") {
22        Ok(_) => println!("    Unexpected success"),
23        Err(e) => println!("    Expected error: {}", e),
24    }
25    println!();
26
27    // Test 3: Invalid PE (not MZ header)
28    println!("[Test 3] Executing invalid PE:");
29    let invalid_pe = vec![0x00, 0x00, 0x00, 0x00]; // Not MZ
30    match GhostingBuilder::new(&invalid_pe).x64().execute() {
31        Ok(_) => println!("    Unexpected success"),
32        Err(e) => println!("    Expected error: {}", e),
33    }
34    println!();
35
36    // Test 4: Empty payload
37    println!("[Test 4] Empty payload:");
38    match GhostingBuilder::new(&[]).x64().execute() {
39        Ok(_) => println!("    Unexpected success"),
40        Err(e) => println!("    Expected error: {}", e),
41    }
42    println!();
43
44    // Test 5: Truncated PE
45    println!("[Test 5] Truncated PE (only MZ header):");
46    let truncated_pe = vec![0x4D, 0x5A]; // Just MZ
47    match GhostingBuilder::new(&truncated_pe).x64().execute() {
48        Ok(_) => println!("    Unexpected success"),
49        Err(e) => println!("    Expected error: {}", e),
50    }
51    println!();
52
53    println!("[*] Error handling tests complete.");
54}
examples/full_demo.rs (line 44)
12fn main() {
13    // ========================================
14    // INITIALIZATION
15    // ========================================
16    init();
17    
18    println!("╔════════════════════════════════════════════╗");
19    println!("║     ProcessGhosting Full Demo              ║");
20    println!("║     By BlackTechX                          ║");
21    println!("╚════════════════════════════════════════════╝\n");
22
23    let args: Vec<String> = env::args().collect();
24    let test_file = if args.len() > 1 { &args[1] } else { "C:\\Windows\\System32\\notepad.exe" };
25
26    // ========================================
27    // SECTION 1: HEX UTILITIES
28    // ========================================
29    println!("┌────────────────────────────────────────────┐");
30    println!("│ Section 1: Hex Utilities                   │");
31    println!("└────────────────────────────────────────────┘\n");
32
33    // 1.1 Parse different hex formats
34    println!("[1.1] Parsing different hex formats:\n");
35    
36    let formats = [
37        "4D5A9000",
38        "4D 5A 90 00",
39        "0x4D, 0x5A, 0x90, 0x00",
40        "\\x4D\\x5A\\x90\\x00",
41    ];
42
43    for fmt in &formats {
44        match parse_hex_string(fmt) {
45            Ok(bytes) => println!("      '{}' -> {:02X?}", fmt, bytes),
46            Err(e) => println!("      '{}' -> Error: {}", fmt, e),
47        }
48    }
49    println!();
50
51    // 1.2 Convert bytes to hex
52    println!("[1.2] Converting bytes to hex string:");
53    let sample_bytes = vec![0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00];
54    let hex_string = bytes_to_hex_string(&sample_bytes);
55    println!("      {:?} -> {}\n", sample_bytes, hex_string);
56
57    // 1.3 Read file as hex (first 64 bytes)
58    println!("[1.3] Reading file header as hex:");
59    match read_exe_bytes(test_file) {
60        Ok(bytes) => {
61            let preview: Vec<u8> = bytes.iter().take(32).cloned().collect();
62            println!("      File: {}", test_file);
63            println!("      Size: {} bytes", bytes.len());
64            println!("      First 32 bytes: {}", bytes_to_hex_string(&preview));
65        }
66        Err(e) => println!("      Error: {}", e),
67    }
68    println!();
69
70    // ========================================
71    // SECTION 2: BUILDER PATTERNS
72    // ========================================
73    println!("┌────────────────────────────────────────────┐");
74    println!("│ Section 2: Builder Patterns                │");
75    println!("└────────────────────────────────────────────┘\n");
76
77    // 2.1 From raw bytes
78    println!("[2.1] Builder from raw bytes:");
79    let sample = vec![0x4D, 0x5A];
80    let config = GhostingBuilder::new(&sample)
81        .x64()
82        .with_logging()
83        .build();
84    println!("      Payload size: {} bytes", config.payload.len());
85    println!("      Architecture: {}", config.architecture);
86    println!("      Verbose: {}\n", config.verbose);
87
88    // 2.2 From file
89    println!("[2.2] Builder from file:");
90    match GhostingBuilder::from_file(test_file) {
91        Ok(builder) => {
92            let config = builder.x64().build();
93            println!("      Loaded: {} bytes\n", config.payload.len());
94        }
95        Err(e) => println!("      Error: {}\n", e),
96    }
97
98    // 2.3 From hex string
99    println!("[2.3] Builder from hex string:");
100    match GhostingBuilder::from_hex_string("0x4D, 0x5A, 0x90, 0x00") {
101        Ok(builder) => {
102            let config = builder.build();
103            println!("      Parsed: {} bytes\n", config.payload.len());
104        }
105        Err(e) => println!("      Error: {}\n", e),
106    }
107
108    // 2.4 Architecture selection
109    println!("[2.4] Architecture selection:");
110    
111    let x64_config = GhostingBuilder::new(&[0x4D, 0x5A])
112        .x64()
113        .build();
114    println!("      .x64() -> {}", x64_config.architecture);
115
116    let x86_config = GhostingBuilder::new(&[0x4D, 0x5A])
117        .x86()
118        .build();
119    println!("      .x86() -> {}", x86_config.architecture);
120
121    let arch_config = GhostingBuilder::new(&[0x4D, 0x5A])
122        .architecture(Architecture::X64)
123        .build();
124    println!("      .architecture(X64) -> {}\n", arch_config.architecture);
125
126    // 2.5 Verbose control
127    println!("[2.5] Verbose control:");
128    
129    let verbose = GhostingBuilder::new(&[0x4D, 0x5A])
130        .with_logging()
131        .build();
132    println!("      .with_logging() -> verbose: {}", verbose.verbose);
133
134    let silent = GhostingBuilder::new(&[0x4D, 0x5A])
135        .silent()
136        .build();
137    println!("      .silent() -> verbose: {}\n", silent.verbose);
138
139    // ========================================
140    // SECTION 3: QUICK FUNCTIONS
141    // ========================================
142    println!("┌────────────────────────────────────────────┐");
143    println!("│ Section 3: Quick Functions                 │");
144    println!("└────────────────────────────────────────────┘\n");
145
146    println!("[3.1] Available quick functions:");
147    println!("      ghost_payload(&bytes)      - Execute from bytes");
148    println!("      ghost_payload_file(path)   - Execute from file");
149    println!("      ghost_payload_hex(hex_str) - Execute from hex string\n");
150
151    // ========================================
152    // SECTION 4: EXECUTION (DISABLED BY DEFAULT)
153    // ========================================
154    println!("┌────────────────────────────────────────────┐");
155    println!("│ Section 4: Execution Demo                  │");
156    println!("└────────────────────────────────────────────┘\n");
157
158    println!("[4.1] To execute process ghosting:");
159    println!();
160    println!("      // Method 1: Builder pattern");
161    println!("      GhostingBuilder::from_file(\"payload.exe\")?");
162    println!("          .x64()");
163    println!("          .with_logging()");
164    println!("          .execute()?;");
165    println!();
166    println!("      // Method 2: Quick function");
167    println!("      ghost_payload_file(\"payload.exe\")?;");
168    println!();
169    println!("      // Method 3: From embedded bytes");
170    println!("      const PAYLOAD: &[u8] = include_bytes!(\"payload.exe\");");
171    println!("      ghost_payload(PAYLOAD)?;");
172    println!();
173
174    // Uncomment below to actually execute
175    /*
176    println!("[4.2] Executing ghosting...\n");
177    
178    match GhostingBuilder::from_file("your_payload.exe") {
179        Ok(builder) => {
180            match builder.x64().with_logging().execute() {
181                Ok(_) => println!("\n[+] Ghosting successful!"),
182                Err(e) => println!("\n[-] Ghosting failed: {}", e),
183            }
184        }
185        Err(e) => println!("[-] Failed to load payload: {}", e),
186    }
187    */
188
189    println!("┌────────────────────────────────────────────┐");
190    println!("│ Demo Complete                              │");
191    println!("└────────────────────────────────────────────┘\n");
192}