Skip to main content

powershell_pro_obfuscator/
lib.rs

1/******************************************************************************
2 * PowerShell Pro Obfuscator WebApi interface
3 *
4 * Version        : v1.0.0
5 * Language       : Rust
6 * Author         : Bartosz Wójcik
7 * Web page       : https://www.pelock.com
8 *
9 *****************************************************************************/
10
11use base64::engine::general_purpose::STANDARD as B64_ENGINE;
12use base64::Engine;
13use flate2::read::ZlibDecoder;
14use flate2::write::ZlibEncoder;
15use flate2::Compression;
16use serde::{Deserialize, Serialize};
17use std::collections::HashMap;
18use std::io::{Read, Write};
19
20/// Error code (see [`PowerShellProObfuscator::ERROR_SUCCESS`] and related constants).
21#[derive(Debug, Clone, Deserialize, Serialize)]
22pub struct PowerShellProObfuscatorResult {
23    /// Error code (see `ERROR_*` constants on [`PowerShellProObfuscator`]).
24    pub error: i64,
25    /// Obfuscated source when error is [`PowerShellProObfuscator::ERROR_SUCCESS`].
26    #[serde(default)]
27    pub output: Option<String>,
28    /// Demo mode when key is invalid or empty.
29    #[serde(default)]
30    pub demo: Option<bool>,
31    /// Credits remaining after the operation.
32    #[serde(default, rename = "credits_left")]
33    pub credits_left: Option<i64>,
34    /// Total credits for the activation key.
35    #[serde(default, rename = "credits_total")]
36    pub credits_total: Option<i64>,
37    /// True when the last credit was used.
38    #[serde(default)]
39    pub expired: Option<bool>,
40    /// Max. source size (bytes), e.g. demo limit.
41    #[serde(default, rename = "string_limit")]
42    pub string_limit: Option<i64>,
43}
44
45/// Parsed API response: either a structured object or the raw JSON string (when `return_as_object` is `false`).
46#[derive(Debug, Clone)]
47pub enum PowerShellProObfuscatorResponse {
48    /// Structured result (after optional output decompression).
49    Object(PowerShellProObfuscatorResult),
50    /// JSON encoded string (original body, or re-encoded after decompression).
51    Json(String),
52}
53
54/// PowerShell Pro Obfuscator WebApi client.
55#[derive(Debug, Clone)]
56pub struct PowerShellProObfuscator {
57    api_key: Option<String>,
58    client: reqwest::Client,
59    /// Should the source code be compressed.
60    pub enable_compression: bool,
61    /// Protection against tampering with protected code (integrity verification).
62    pub self_defending: bool,
63    /// Protection linker (decoy call graph).
64    pub protection_linker: bool,
65    /// Rename variable names to random string values.
66    pub rename_variables: bool,
67    /// Rename parameter names to random string values.
68    pub rename_parameters: bool,
69    /// Rename function names to random string values.
70    pub rename_functions: bool,
71    /// Shuffle function order in the output source.
72    pub shuffle_functions: bool,
73    /// Change linear code execution flow via control-flow flattening.
74    pub control_flow_flatten: bool,
75    /// Rewrite statement blocks into finite-state automata (state-machine obfuscation).
76    pub state_machine: bool,
77    /// Lift selected statements into a VM engine (virtualized statements).
78    pub vm_strategy: bool,
79    /// Encrypt integers.
80    pub encrypt_integers: bool,
81    /// Split strings into concatenated chunks.
82    pub split_strings: bool,
83    /// Encrypt strings using randomly generated polymorphic encryption algorithms.
84    pub encrypt_strings: bool,
85    /// Move integers to arrays.
86    pub integers_to_arrays: bool,
87    /// Move floats to arrays.
88    pub floats_to_arrays: bool,
89    /// Insert dead code.
90    pub insert_dead_code: bool,
91    /// Replace boolean conditions with equivalent complex expressions.
92    pub complexify_booleans: bool,
93    /// Represent integers via floating-point math.
94    pub integers_to_floating: bool,
95    /// Encrypt floating point numbers.
96    pub encrypt_floating: bool,
97    /// Insert decoy functions.
98    pub decoy_functions: bool,
99    /// Insert anti-debugging detections.
100    pub detect_debugger: bool,
101    /// Insert fake dot-source comment markers.
102    pub fake_dot_source_markers: bool,
103    /// Insert opaque predicate branches.
104    pub opaque_branches: bool,
105    /// Insert scriptblock decoys.
106    pub scriptblock_decoys: bool,
107    /// Insert here-string padding.
108    pub literal_padding: bool,
109    /// Use indirect command invocation.
110    pub reflect_invoke_commands: bool,
111    /// Store string fragments in char-code array vaults.
112    pub string_char_array_vault: bool,
113    /// Wrap code in try/finally blocks with dead noise.
114    pub try_finally_noise: bool,
115    /// Apply redundant xor / affine integer masks.
116    pub affine_integer_mask: bool,
117    /// Insert dead event/timer stubs.
118    pub event_stub: bool,
119    /// Strip comments from the output source.
120    pub remove_comments: bool,
121}
122
123impl PowerShellProObfuscator {
124    /// Default PowerShell Pro Obfuscator WebApi endpoint.
125    pub const API_URL: &'static str = "https://www.pelock.com/api/powershell-pro-obfuscator/v1";
126
127    /// Success.
128    pub const ERROR_SUCCESS: i64 = 0;
129
130    /// Invalid size for source code (it's 1000 bytes max. for demo version).
131    pub const ERROR_INPUT_SIZE: i64 = 1;
132
133    /// Input source is empty.
134    pub const ERROR_INPUT: i64 = 2;
135
136    /// PowerShell source code parsing error.
137    pub const ERROR_PARSING: i64 = 3;
138
139    /// PowerShell parsed code obfuscation error.
140    pub const ERROR_OBFUSCATION: i64 = 4;
141
142    /// An error occurred while generating output code.
143    pub const ERROR_OUTPUT: i64 = 5;
144
145    /// Initialize PowerShell Pro Obfuscator client.
146    ///
147    /// `api_key` — activation key for the service (it can be empty for demo mode).
148    pub fn new(api_key: Option<String>) -> Self {
149        Self {
150            api_key,
151            client: reqwest::Client::new(),
152            enable_compression: false,
153            self_defending: true,
154            protection_linker: true,
155            rename_variables: true,
156            rename_parameters: true,
157            rename_functions: true,
158            shuffle_functions: true,
159            control_flow_flatten: true,
160            state_machine: true,
161            vm_strategy: true,
162            encrypt_integers: true,
163            split_strings: true,
164            encrypt_strings: true,
165            integers_to_arrays: true,
166            floats_to_arrays: true,
167            insert_dead_code: true,
168            complexify_booleans: true,
169            integers_to_floating: true,
170            encrypt_floating: true,
171            decoy_functions: true,
172            detect_debugger: true,
173            fake_dot_source_markers: true,
174            opaque_branches: true,
175            scriptblock_decoys: true,
176            literal_padding: true,
177            reflect_invoke_commands: true,
178            string_char_array_vault: true,
179            try_finally_noise: true,
180            affine_integer_mask: true,
181            event_stub: true,
182            remove_comments: true,
183        }
184    }
185
186    /// Login to the service and get the information about the current license limits.
187    ///
188    /// `return_as_object` — return result as an object or JSON encoded string.
189    pub async fn login(&self, return_as_object: bool) -> Option<PowerShellProObfuscatorResponse> {
190        let mut params = HashMap::new();
191        params.insert("command".to_string(), "login".to_string());
192        self.post_request(params, return_as_object).await
193    }
194
195    /// Obfuscate PowerShell script source code file using provided parameters.
196    ///
197    /// `return_as_object` — return result as an object or JSON encoded string.
198    pub async fn obfuscate_script_file(
199        &self,
200        script_file_path: &std::path::Path,
201        return_as_object: bool,
202    ) -> Option<PowerShellProObfuscatorResponse> {
203        let source = tokio::fs::read_to_string(script_file_path).await.ok()?;
204        if source.is_empty() {
205            return None;
206        }
207        self.obfuscate_script_source(&source, return_as_object).await
208    }
209
210    /// Obfuscate PowerShell script source code (string) using provided parameters.
211    ///
212    /// `return_as_object` — return result as an object or JSON encoded string.
213    pub async fn obfuscate_script_source(
214        &self,
215        script_source: &str,
216        return_as_object: bool,
217    ) -> Option<PowerShellProObfuscatorResponse> {
218        let mut params = HashMap::new();
219        params.insert("command".to_string(), "obfuscate".to_string());
220        params.insert("source".to_string(), script_source.to_string());
221        self.post_request(params, return_as_object).await
222    }
223
224    /// Send a POST request to the server.
225    async fn post_request(
226        &self,
227        mut params: HashMap<String, String>,
228        return_as_object: bool,
229    ) -> Option<PowerShellProObfuscatorResponse> {
230        //
231        // add activation key to the parameters array
232        //
233        if let Some(ref key) = self.api_key {
234            if !key.is_empty() {
235                params.insert("key".to_string(), key.clone());
236            }
237        }
238
239        //
240        // obfuscation strategies
241        //
242        if self.self_defending {
243            params.insert("self_defending".to_string(), "1".to_string());
244        }
245        if self.protection_linker {
246            params.insert("protection_linker".to_string(), "1".to_string());
247        }
248        if self.rename_variables {
249            params.insert("rename_variables".to_string(), "1".to_string());
250        }
251        if self.rename_parameters {
252            params.insert("rename_parameters".to_string(), "1".to_string());
253        }
254        if self.rename_functions {
255            params.insert("rename_functions".to_string(), "1".to_string());
256        }
257        if self.shuffle_functions {
258            params.insert("shuffle_functions".to_string(), "1".to_string());
259        }
260        if self.control_flow_flatten {
261            params.insert("control_flow_flatten".to_string(), "1".to_string());
262        }
263        if self.state_machine {
264            params.insert("state_machine".to_string(), "1".to_string());
265        }
266        if self.vm_strategy {
267            params.insert("vm_strategy".to_string(), "1".to_string());
268        }
269        if self.encrypt_integers {
270            params.insert("encrypt_integers".to_string(), "1".to_string());
271        }
272        if self.split_strings {
273            params.insert("split_strings".to_string(), "1".to_string());
274        }
275        if self.encrypt_strings {
276            params.insert("encrypt_strings".to_string(), "1".to_string());
277        }
278        if self.integers_to_arrays {
279            params.insert("integers_to_arrays".to_string(), "1".to_string());
280        }
281        if self.floats_to_arrays {
282            params.insert("floats_to_arrays".to_string(), "1".to_string());
283        }
284        if self.insert_dead_code {
285            params.insert("insert_dead_code".to_string(), "1".to_string());
286        }
287        if self.complexify_booleans {
288            params.insert("complexify_booleans".to_string(), "1".to_string());
289        }
290        if self.integers_to_floating {
291            params.insert("integers_to_floating".to_string(), "1".to_string());
292        }
293        if self.encrypt_floating {
294            params.insert("encrypt_floating".to_string(), "1".to_string());
295        }
296        if self.decoy_functions {
297            params.insert("decoy_functions".to_string(), "1".to_string());
298        }
299        if self.detect_debugger {
300            params.insert("detect_debugger".to_string(), "1".to_string());
301        }
302        if self.fake_dot_source_markers {
303            params.insert("fake_dot_source_markers".to_string(), "1".to_string());
304        }
305        if self.opaque_branches {
306            params.insert("opaque_branches".to_string(), "1".to_string());
307        }
308        if self.scriptblock_decoys {
309            params.insert("scriptblock_decoys".to_string(), "1".to_string());
310        }
311        if self.literal_padding {
312            params.insert("literal_padding".to_string(), "1".to_string());
313        }
314        if self.reflect_invoke_commands {
315            params.insert("reflect_invoke_commands".to_string(), "1".to_string());
316        }
317        if self.string_char_array_vault {
318            params.insert("string_char_array_vault".to_string(), "1".to_string());
319        }
320        if self.try_finally_noise {
321            params.insert("try_finally_noise".to_string(), "1".to_string());
322        }
323        if self.affine_integer_mask {
324            params.insert("affine_integer_mask".to_string(), "1".to_string());
325        }
326        if self.event_stub {
327            params.insert("event_stub".to_string(), "1".to_string());
328        }
329        if self.remove_comments {
330            params.insert("remove_comments".to_string(), "1".to_string());
331        }
332
333        //
334        // check if compression is enabled
335        //
336        if self.enable_compression {
337            if let Some(source) = params.get("source").cloned() {
338                let mut enc = ZlibEncoder::new(Vec::new(), Compression::best());
339                enc.write_all(source.as_bytes()).ok()?;
340                let compressed = enc.finish().ok()?;
341                params.insert("source".to_string(), B64_ENGINE.encode(compressed));
342                params.insert("compression".to_string(), "1".to_string());
343            }
344        }
345
346        let mut form = reqwest::multipart::Form::new();
347        for (k, v) in params {
348            form = form.text(k, v);
349        }
350
351        let response_text = self
352            .client
353            .post(Self::API_URL)
354            .header("User-Agent", "PELock PowerShell Pro Obfuscator")
355            .multipart(form)
356            .send()
357            .await
358            .ok()?
359            .text()
360            .await
361            .ok()?;
362
363        //
364        // check the result
365        //
366        if response_text.is_empty() {
367            return None;
368        }
369
370        let mut result: PowerShellProObfuscatorResult =
371            serde_json::from_str(&response_text).ok()?;
372
373        //
374        // depack output code back into the string
375        //
376        let mut depacked = false;
377
378        if self.enable_compression
379            && result.error == Self::ERROR_SUCCESS
380            && result.output.as_ref().is_some_and(|s| !s.is_empty())
381        {
382            let b64 = result.output.as_ref()?;
383            let buf = B64_ENGINE.decode(b64.as_bytes()).ok()?;
384            let mut decoder = ZlibDecoder::new(&buf[..]);
385            let mut out = String::new();
386            decoder.read_to_string(&mut out).ok()?;
387            result.output = Some(out);
388            depacked = true;
389        }
390
391        if return_as_object {
392            return Some(PowerShellProObfuscatorResponse::Object(result));
393        }
394
395        //
396        // if output was depacked - pack it again to JSON format
397        //
398        if depacked {
399            let s = serde_json::to_string(&result).ok()?;
400            return Some(PowerShellProObfuscatorResponse::Json(s));
401        }
402
403        //
404        // return original JSON response code
405        //
406        Some(PowerShellProObfuscatorResponse::Json(response_text))
407    }
408}