powershell-pro-obfuscator 1.0.0

PowerShell Pro Obfuscator Web API interface can help you obfuscate, virtualize and protect PowerShell .ps1 scripts against analysis, reverse engineering and technology theft. PowerShell Pro Obfuscator provides advanced PowerShell source code parsing based on AST trees, multiple advanced obfuscation, virtualization and protection strategies are available.
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
/******************************************************************************
 * PowerShell Pro Obfuscator WebApi interface
 *
 * Version        : v1.0.0
 * Language       : Rust
 * Author         : Bartosz Wójcik
 * Web page       : https://www.pelock.com
 *
 *****************************************************************************/

use base64::engine::general_purpose::STANDARD as B64_ENGINE;
use base64::Engine;
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use flate2::Compression;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};

/// Error code (see [`PowerShellProObfuscator::ERROR_SUCCESS`] and related constants).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PowerShellProObfuscatorResult {
    /// Error code (see `ERROR_*` constants on [`PowerShellProObfuscator`]).
    pub error: i64,
    /// Obfuscated source when error is [`PowerShellProObfuscator::ERROR_SUCCESS`].
    #[serde(default)]
    pub output: Option<String>,
    /// Demo mode when key is invalid or empty.
    #[serde(default)]
    pub demo: Option<bool>,
    /// Credits remaining after the operation.
    #[serde(default, rename = "credits_left")]
    pub credits_left: Option<i64>,
    /// Total credits for the activation key.
    #[serde(default, rename = "credits_total")]
    pub credits_total: Option<i64>,
    /// True when the last credit was used.
    #[serde(default)]
    pub expired: Option<bool>,
    /// Max. source size (bytes), e.g. demo limit.
    #[serde(default, rename = "string_limit")]
    pub string_limit: Option<i64>,
}

/// Parsed API response: either a structured object or the raw JSON string (when `return_as_object` is `false`).
#[derive(Debug, Clone)]
pub enum PowerShellProObfuscatorResponse {
    /// Structured result (after optional output decompression).
    Object(PowerShellProObfuscatorResult),
    /// JSON encoded string (original body, or re-encoded after decompression).
    Json(String),
}

/// PowerShell Pro Obfuscator WebApi client.
#[derive(Debug, Clone)]
pub struct PowerShellProObfuscator {
    api_key: Option<String>,
    client: reqwest::Client,
    /// Should the source code be compressed.
    pub enable_compression: bool,
    /// Protection against tampering with protected code (integrity verification).
    pub self_defending: bool,
    /// Protection linker (decoy call graph).
    pub protection_linker: bool,
    /// Rename variable names to random string values.
    pub rename_variables: bool,
    /// Rename parameter names to random string values.
    pub rename_parameters: bool,
    /// Rename function names to random string values.
    pub rename_functions: bool,
    /// Shuffle function order in the output source.
    pub shuffle_functions: bool,
    /// Change linear code execution flow via control-flow flattening.
    pub control_flow_flatten: bool,
    /// Rewrite statement blocks into finite-state automata (state-machine obfuscation).
    pub state_machine: bool,
    /// Lift selected statements into a VM engine (virtualized statements).
    pub vm_strategy: bool,
    /// Encrypt integers.
    pub encrypt_integers: bool,
    /// Split strings into concatenated chunks.
    pub split_strings: bool,
    /// Encrypt strings using randomly generated polymorphic encryption algorithms.
    pub encrypt_strings: bool,
    /// Move integers to arrays.
    pub integers_to_arrays: bool,
    /// Move floats to arrays.
    pub floats_to_arrays: bool,
    /// Insert dead code.
    pub insert_dead_code: bool,
    /// Replace boolean conditions with equivalent complex expressions.
    pub complexify_booleans: bool,
    /// Represent integers via floating-point math.
    pub integers_to_floating: bool,
    /// Encrypt floating point numbers.
    pub encrypt_floating: bool,
    /// Insert decoy functions.
    pub decoy_functions: bool,
    /// Insert anti-debugging detections.
    pub detect_debugger: bool,
    /// Insert fake dot-source comment markers.
    pub fake_dot_source_markers: bool,
    /// Insert opaque predicate branches.
    pub opaque_branches: bool,
    /// Insert scriptblock decoys.
    pub scriptblock_decoys: bool,
    /// Insert here-string padding.
    pub literal_padding: bool,
    /// Use indirect command invocation.
    pub reflect_invoke_commands: bool,
    /// Store string fragments in char-code array vaults.
    pub string_char_array_vault: bool,
    /// Wrap code in try/finally blocks with dead noise.
    pub try_finally_noise: bool,
    /// Apply redundant xor / affine integer masks.
    pub affine_integer_mask: bool,
    /// Insert dead event/timer stubs.
    pub event_stub: bool,
    /// Strip comments from the output source.
    pub remove_comments: bool,
}

impl PowerShellProObfuscator {
    /// Default PowerShell Pro Obfuscator WebApi endpoint.
    pub const API_URL: &'static str = "https://www.pelock.com/api/powershell-pro-obfuscator/v1";

    /// Success.
    pub const ERROR_SUCCESS: i64 = 0;

    /// Invalid size for source code (it's 1000 bytes max. for demo version).
    pub const ERROR_INPUT_SIZE: i64 = 1;

    /// Input source is empty.
    pub const ERROR_INPUT: i64 = 2;

    /// PowerShell source code parsing error.
    pub const ERROR_PARSING: i64 = 3;

    /// PowerShell parsed code obfuscation error.
    pub const ERROR_OBFUSCATION: i64 = 4;

    /// An error occurred while generating output code.
    pub const ERROR_OUTPUT: i64 = 5;

    /// Initialize PowerShell Pro Obfuscator client.
    ///
    /// `api_key` — activation key for the service (it can be empty for demo mode).
    pub fn new(api_key: Option<String>) -> Self {
        Self {
            api_key,
            client: reqwest::Client::new(),
            enable_compression: false,
            self_defending: true,
            protection_linker: true,
            rename_variables: true,
            rename_parameters: true,
            rename_functions: true,
            shuffle_functions: true,
            control_flow_flatten: true,
            state_machine: true,
            vm_strategy: true,
            encrypt_integers: true,
            split_strings: true,
            encrypt_strings: true,
            integers_to_arrays: true,
            floats_to_arrays: true,
            insert_dead_code: true,
            complexify_booleans: true,
            integers_to_floating: true,
            encrypt_floating: true,
            decoy_functions: true,
            detect_debugger: true,
            fake_dot_source_markers: true,
            opaque_branches: true,
            scriptblock_decoys: true,
            literal_padding: true,
            reflect_invoke_commands: true,
            string_char_array_vault: true,
            try_finally_noise: true,
            affine_integer_mask: true,
            event_stub: true,
            remove_comments: true,
        }
    }

    /// Login to the service and get the information about the current license limits.
    ///
    /// `return_as_object` — return result as an object or JSON encoded string.
    pub async fn login(&self, return_as_object: bool) -> Option<PowerShellProObfuscatorResponse> {
        let mut params = HashMap::new();
        params.insert("command".to_string(), "login".to_string());
        self.post_request(params, return_as_object).await
    }

    /// Obfuscate PowerShell script source code file using provided parameters.
    ///
    /// `return_as_object` — return result as an object or JSON encoded string.
    pub async fn obfuscate_script_file(
        &self,
        script_file_path: &std::path::Path,
        return_as_object: bool,
    ) -> Option<PowerShellProObfuscatorResponse> {
        let source = tokio::fs::read_to_string(script_file_path).await.ok()?;
        if source.is_empty() {
            return None;
        }
        self.obfuscate_script_source(&source, return_as_object).await
    }

    /// Obfuscate PowerShell script source code (string) using provided parameters.
    ///
    /// `return_as_object` — return result as an object or JSON encoded string.
    pub async fn obfuscate_script_source(
        &self,
        script_source: &str,
        return_as_object: bool,
    ) -> Option<PowerShellProObfuscatorResponse> {
        let mut params = HashMap::new();
        params.insert("command".to_string(), "obfuscate".to_string());
        params.insert("source".to_string(), script_source.to_string());
        self.post_request(params, return_as_object).await
    }

    /// Send a POST request to the server.
    async fn post_request(
        &self,
        mut params: HashMap<String, String>,
        return_as_object: bool,
    ) -> Option<PowerShellProObfuscatorResponse> {
        //
        // add activation key to the parameters array
        //
        if let Some(ref key) = self.api_key {
            if !key.is_empty() {
                params.insert("key".to_string(), key.clone());
            }
        }

        //
        // obfuscation strategies
        //
        if self.self_defending {
            params.insert("self_defending".to_string(), "1".to_string());
        }
        if self.protection_linker {
            params.insert("protection_linker".to_string(), "1".to_string());
        }
        if self.rename_variables {
            params.insert("rename_variables".to_string(), "1".to_string());
        }
        if self.rename_parameters {
            params.insert("rename_parameters".to_string(), "1".to_string());
        }
        if self.rename_functions {
            params.insert("rename_functions".to_string(), "1".to_string());
        }
        if self.shuffle_functions {
            params.insert("shuffle_functions".to_string(), "1".to_string());
        }
        if self.control_flow_flatten {
            params.insert("control_flow_flatten".to_string(), "1".to_string());
        }
        if self.state_machine {
            params.insert("state_machine".to_string(), "1".to_string());
        }
        if self.vm_strategy {
            params.insert("vm_strategy".to_string(), "1".to_string());
        }
        if self.encrypt_integers {
            params.insert("encrypt_integers".to_string(), "1".to_string());
        }
        if self.split_strings {
            params.insert("split_strings".to_string(), "1".to_string());
        }
        if self.encrypt_strings {
            params.insert("encrypt_strings".to_string(), "1".to_string());
        }
        if self.integers_to_arrays {
            params.insert("integers_to_arrays".to_string(), "1".to_string());
        }
        if self.floats_to_arrays {
            params.insert("floats_to_arrays".to_string(), "1".to_string());
        }
        if self.insert_dead_code {
            params.insert("insert_dead_code".to_string(), "1".to_string());
        }
        if self.complexify_booleans {
            params.insert("complexify_booleans".to_string(), "1".to_string());
        }
        if self.integers_to_floating {
            params.insert("integers_to_floating".to_string(), "1".to_string());
        }
        if self.encrypt_floating {
            params.insert("encrypt_floating".to_string(), "1".to_string());
        }
        if self.decoy_functions {
            params.insert("decoy_functions".to_string(), "1".to_string());
        }
        if self.detect_debugger {
            params.insert("detect_debugger".to_string(), "1".to_string());
        }
        if self.fake_dot_source_markers {
            params.insert("fake_dot_source_markers".to_string(), "1".to_string());
        }
        if self.opaque_branches {
            params.insert("opaque_branches".to_string(), "1".to_string());
        }
        if self.scriptblock_decoys {
            params.insert("scriptblock_decoys".to_string(), "1".to_string());
        }
        if self.literal_padding {
            params.insert("literal_padding".to_string(), "1".to_string());
        }
        if self.reflect_invoke_commands {
            params.insert("reflect_invoke_commands".to_string(), "1".to_string());
        }
        if self.string_char_array_vault {
            params.insert("string_char_array_vault".to_string(), "1".to_string());
        }
        if self.try_finally_noise {
            params.insert("try_finally_noise".to_string(), "1".to_string());
        }
        if self.affine_integer_mask {
            params.insert("affine_integer_mask".to_string(), "1".to_string());
        }
        if self.event_stub {
            params.insert("event_stub".to_string(), "1".to_string());
        }
        if self.remove_comments {
            params.insert("remove_comments".to_string(), "1".to_string());
        }

        //
        // check if compression is enabled
        //
        if self.enable_compression {
            if let Some(source) = params.get("source").cloned() {
                let mut enc = ZlibEncoder::new(Vec::new(), Compression::best());
                enc.write_all(source.as_bytes()).ok()?;
                let compressed = enc.finish().ok()?;
                params.insert("source".to_string(), B64_ENGINE.encode(compressed));
                params.insert("compression".to_string(), "1".to_string());
            }
        }

        let mut form = reqwest::multipart::Form::new();
        for (k, v) in params {
            form = form.text(k, v);
        }

        let response_text = self
            .client
            .post(Self::API_URL)
            .header("User-Agent", "PELock PowerShell Pro Obfuscator")
            .multipart(form)
            .send()
            .await
            .ok()?
            .text()
            .await
            .ok()?;

        //
        // check the result
        //
        if response_text.is_empty() {
            return None;
        }

        let mut result: PowerShellProObfuscatorResult =
            serde_json::from_str(&response_text).ok()?;

        //
        // depack output code back into the string
        //
        let mut depacked = false;

        if self.enable_compression
            && result.error == Self::ERROR_SUCCESS
            && result.output.as_ref().is_some_and(|s| !s.is_empty())
        {
            let b64 = result.output.as_ref()?;
            let buf = B64_ENGINE.decode(b64.as_bytes()).ok()?;
            let mut decoder = ZlibDecoder::new(&buf[..]);
            let mut out = String::new();
            decoder.read_to_string(&mut out).ok()?;
            result.output = Some(out);
            depacked = true;
        }

        if return_as_object {
            return Some(PowerShellProObfuscatorResponse::Object(result));
        }

        //
        // if output was depacked - pack it again to JSON format
        //
        if depacked {
            let s = serde_json::to_string(&result).ok()?;
            return Some(PowerShellProObfuscatorResponse::Json(s));
        }

        //
        // return original JSON response code
        //
        Some(PowerShellProObfuscatorResponse::Json(response_text))
    }
}