Skip to main content

python_obfuscator/
lib.rs

1/******************************************************************************
2 * Python 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 [`PythonObfuscator::ERROR_SUCCESS`] and related constants).
21#[derive(Debug, Clone, Deserialize, Serialize)]
22pub struct PythonObfuscatorResult {
23    /// Error code (see `ERROR_*` constants on [`PythonObfuscator`]).
24    pub error: i64,
25    /// Obfuscated source when error is [`PythonObfuscator::ERROR_SUCCESS`].
26    #[serde(default)]
27    pub output: Option<String>,
28    /// Demo mode when key is invalid or empty. Demo ignores strategy flags and always applies integers_to_arrays, mba_binops, and encrypt_strings (no virtualization; 1000 character limit).
29    #[serde(default)]
30    pub demo: Option<bool>,
31    /// License end date (Y-m-d), empty if none.
32    #[serde(default, rename = "license_expiration")]
33    pub license_expiration: Option<String>,
34    /// Total obfuscations for this activation code.
35    #[serde(default, rename = "usages_total")]
36    pub usages_total: Option<i64>,
37    /// Max. source size (bytes), e.g. demo limit.
38    #[serde(default, rename = "string_limit")]
39    pub string_limit: Option<i64>,
40}
41
42/// Parsed API response: either a structured object or the raw JSON string (when `return_as_object` is `false`).
43#[derive(Debug, Clone)]
44pub enum PythonObfuscatorResponse {
45    /// Structured result (after optional output decompression).
46    Object(PythonObfuscatorResult),
47    /// JSON encoded string (original body, or re-encoded after decompression).
48    Json(String),
49}
50
51/// Public virtualization mode posted as `code_virtualization`.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53pub enum CodeVirtualization {
54    #[serde(rename = "vm")]
55    Vm,
56    #[serde(rename = "fsa")]
57    Fsa,
58    #[serde(rename = "flat")]
59    Flat,
60}
61
62impl CodeVirtualization {
63    /// Wire value for the Web API (`vm`, `fsa`, or `flat`).
64    pub fn as_str(self) -> &'static str {
65        match self {
66            Self::Vm => "vm",
67            Self::Fsa => "fsa",
68            Self::Flat => "flat",
69        }
70    }
71}
72
73/// Identifier alphabet posted as `rename_style`.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
75pub enum RenameStyle {
76    #[serde(rename = "il")]
77    Il,
78    #[serde(rename = "o0")]
79    O0,
80    #[serde(rename = "confusable")]
81    Confusable,
82    #[serde(rename = "hex")]
83    Hex,
84    #[serde(rename = "homoglyph")]
85    Homoglyph,
86    #[serde(rename = "mangled")]
87    Mangled,
88}
89
90impl RenameStyle {
91    /// Wire value for the Web API.
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Self::Il => "il",
95            Self::O0 => "o0",
96            Self::Confusable => "confusable",
97            Self::Hex => "hex",
98            Self::Homoglyph => "homoglyph",
99            Self::Mangled => "mangled",
100        }
101    }
102}
103
104/// Python Obfuscator WebApi client.
105#[derive(Debug, Clone)]
106pub struct PythonObfuscator {
107    api_key: Option<String>,
108    client: reqwest::Client,
109    /// Should the source code be compressed.
110    pub enable_compression: bool,
111    /// Fixed random seed for reproducible obfuscation output (optional).
112    pub seed: Option<i64>,
113    /// Randomization density / intensity (0-100).
114    pub randomization_density: Option<i64>,
115    /// Identifier renaming style (il, o0, confusable, hex, homoglyph, mangled).
116    pub rename_style: Option<RenameStyle>,
117    /// Public virtualization mode (vm, fsa, or flat). Set to `None` to skip virtualization.
118    pub code_virtualization: Option<CodeVirtualization>,
119    /// Protection against tampering with protected code (integrity verification).
120    pub self_defending: bool,
121    /// Protection linker (decoy call graph).
122    pub protection_linker: bool,
123    /// Rename variable names to random string values.
124    pub rename_variables: bool,
125    /// Rename parameter names to random string values.
126    pub rename_parameters: bool,
127    /// Rename function names to random string values.
128    pub rename_functions: bool,
129    /// Rename function call references consistently with renamed functions.
130    pub rename_function_calls: bool,
131    /// Shuffle function order in the output source.
132    pub shuffle_functions: bool,
133    /// Fold/resolve constant expressions at obfuscation time.
134    pub resolve_constants: bool,
135    /// Split strings into concatenated chunks.
136    pub split_strings: bool,
137    /// Apply light transformations/mutations to string literals.
138    pub modify_strings: bool,
139    /// Encrypt strings using randomly generated polymorphic encryption algorithms.
140    pub encrypt_strings: bool,
141    /// Store string fragments in char-code array vaults.
142    pub string_char_array_vault: bool,
143    /// Encrypt integers.
144    pub encrypt_integers: bool,
145    /// Encrypt floating point numbers.
146    pub encrypt_floating: bool,
147    /// Replace binary operators with mixed boolean-arithmetic (MBA) equivalents.
148    pub mba_binops: bool,
149    /// Represent integers via floating-point math.
150    pub integers_to_floating: bool,
151    /// Move integers to arrays.
152    pub integers_to_arrays: bool,
153    /// Move floats to arrays.
154    pub floats_to_arrays: bool,
155    /// Apply redundant xor / affine integer masks.
156    pub affine_integer_mask: bool,
157    /// Encrypt integer array literals.
158    pub array_int_crypt: bool,
159    /// Encrypt character array literals.
160    pub array_char_crypt: bool,
161    /// Encrypt floating-point array literals.
162    pub array_double_crypt: bool,
163    /// Encrypt string array literals.
164    pub array_string_crypt: bool,
165    /// Insert a shared bucket of random noise values used by other strategies.
166    pub insert_random_value_bucket: bool,
167    /// Populate the random value bucket with decoy integers.
168    pub random_bucket_integers: bool,
169    /// Populate the random value bucket with decoy arrays.
170    pub random_bucket_arrays: bool,
171    /// Populate the random value bucket with decoy functions.
172    pub random_bucket_functions: bool,
173    /// Populate the random value bucket with decoy characters.
174    pub random_bucket_characters: bool,
175    /// Populate the random value bucket with anti-regex decoy noise.
176    pub random_bucket_anti_regex: bool,
177    /// Populate the random value bucket with autostart decoy stubs.
178    pub random_bucket_autostart: bool,
179    /// Rewrite selected statements using ternary operators.
180    pub insert_ternary_operators: bool,
181    /// Replace boolean conditions with equivalent complex expressions.
182    pub complexify_booleans: bool,
183    /// Insert opaque predicate branches.
184    pub opaque_branches: bool,
185    /// Insert opaque mixer chains into control flow.
186    pub opaque_mixer_chain: bool,
187    /// Insert dead code.
188    pub insert_dead_code: bool,
189    /// Wrap code in try/finally blocks with dead noise.
190    pub try_finally_noise: bool,
191    /// Insert decoy functions.
192    pub decoy_functions: bool,
193    /// Insert decoy lambda expressions.
194    pub lambda_decoys: bool,
195    /// Insert literal padding noise.
196    pub literal_padding: bool,
197    /// Insert fake import statement markers.
198    pub fake_import_markers: bool,
199    /// Use dynamic getattr()-based indirect calls.
200    pub dynamic_getattr_calls: bool,
201    /// Rewrite absolute imports into __import__ / getattr.
202    pub obfuscate_imports: bool,
203    /// Insert dead callback/event registration stubs.
204    pub callback_registration_stubs: bool,
205    /// Insert anti-debugging detections.
206    pub detect_debugger: bool,
207    /// Insert virtual machine (anti-VM) detections.
208    pub anti_vm: bool,
209    /// Insert anti-sandbox detections.
210    pub anti_sandbox: bool,
211    /// Insert anti-emulators (CPU) detections.
212    pub anti_emulator: bool,
213    /// Strip comments from the output source.
214    pub remove_comments: bool,
215}
216
217impl PythonObfuscator {
218    /// Default Python Obfuscator WebApi endpoint.
219    pub const API_URL: &'static str = "https://www.pelock.com/api/python-obfuscator/v1";
220
221    /// Success.
222    pub const ERROR_SUCCESS: i64 = 0;
223
224    /// Invalid size for source code (it's 1000 bytes max. for demo version).
225    pub const ERROR_INPUT_SIZE: i64 = 1;
226
227    /// Input source is empty.
228    pub const ERROR_INPUT: i64 = 2;
229
230    /// Python source code parsing error.
231    pub const ERROR_PARSING: i64 = 3;
232
233    /// Python parsed code obfuscation error.
234    pub const ERROR_OBFUSCATION: i64 = 4;
235
236    /// An error occurred while generating output code.
237    pub const ERROR_OUTPUT: i64 = 5;
238
239    /// Initialize Python Obfuscator client.
240    ///
241    /// `api_key` — activation key. Empty or invalid keys run demo mode, which ignores strategy flags and always applies integers_to_arrays, mba_binops, and encrypt_strings (no virtualization; 1000 character limit).
242    pub fn new(api_key: Option<String>) -> Self {
243        Self {
244            api_key,
245            client: reqwest::Client::new(),
246            enable_compression: false,
247            seed: None,
248            randomization_density: None,
249            rename_style: None,
250            code_virtualization: Some(CodeVirtualization::Vm),
251            self_defending: false,
252            protection_linker: false,
253            rename_variables: true,
254            rename_parameters: true,
255            rename_functions: true,
256            rename_function_calls: true,
257            shuffle_functions: true,
258            resolve_constants: true,
259            split_strings: true,
260            modify_strings: true,
261            encrypt_strings: true,
262            string_char_array_vault: true,
263            encrypt_integers: true,
264            encrypt_floating: true,
265            mba_binops: true,
266            integers_to_floating: true,
267            integers_to_arrays: true,
268            floats_to_arrays: true,
269            affine_integer_mask: true,
270            array_int_crypt: true,
271            array_char_crypt: true,
272            array_double_crypt: true,
273            array_string_crypt: true,
274            insert_random_value_bucket: true,
275            random_bucket_integers: true,
276            random_bucket_arrays: true,
277            random_bucket_functions: true,
278            random_bucket_characters: true,
279            random_bucket_anti_regex: true,
280            random_bucket_autostart: true,
281            insert_ternary_operators: true,
282            complexify_booleans: true,
283            opaque_branches: true,
284            opaque_mixer_chain: true,
285            insert_dead_code: true,
286            try_finally_noise: true,
287            decoy_functions: true,
288            lambda_decoys: true,
289            literal_padding: true,
290            fake_import_markers: true,
291            dynamic_getattr_calls: true,
292            obfuscate_imports: true,
293            callback_registration_stubs: true,
294            detect_debugger: false,
295            anti_vm: false,
296            anti_sandbox: false,
297            anti_emulator: false,
298            remove_comments: true,
299        }
300    }
301
302    /// Login to the service and get the information about the current license limits.
303    ///
304    /// `return_as_object` — return result as an object or JSON encoded string.
305    pub async fn login(&self, return_as_object: bool) -> Option<PythonObfuscatorResponse> {
306        let mut params = HashMap::new();
307        params.insert("command".to_string(), "login".to_string());
308        self.post_request(params, return_as_object).await
309    }
310
311    /// Obfuscate Python script source code file using provided parameters.
312    ///
313    /// `return_as_object` — return result as an object or JSON encoded string.
314    pub async fn obfuscate_script_file(
315        &self,
316        script_file_path: &std::path::Path,
317        return_as_object: bool,
318    ) -> Option<PythonObfuscatorResponse> {
319        let source = tokio::fs::read_to_string(script_file_path).await.ok()?;
320        if source.is_empty() {
321            return None;
322        }
323        self.obfuscate_script_source(&source, return_as_object).await
324    }
325
326    /// Obfuscate Python script source code (string) using provided parameters.
327    ///
328    /// `return_as_object` — return result as an object or JSON encoded string.
329    pub async fn obfuscate_script_source(
330        &self,
331        script_source: &str,
332        return_as_object: bool,
333    ) -> Option<PythonObfuscatorResponse> {
334        let mut params = HashMap::new();
335        params.insert("command".to_string(), "obfuscate".to_string());
336        params.insert("source".to_string(), script_source.to_string());
337        self.post_request(params, return_as_object).await
338    }
339
340    /// Send a POST request to the server.
341    async fn post_request(
342        &self,
343        mut params: HashMap<String, String>,
344        return_as_object: bool,
345    ) -> Option<PythonObfuscatorResponse> {
346        //
347        // add activation key to the parameters array
348        //
349        if let Some(ref key) = self.api_key {
350            if !key.is_empty() {
351                params.insert("key".to_string(), key.clone());
352            }
353        }
354
355        //
356        // global tuning options
357        //
358        if let Some(seed) = self.seed {
359            params.insert("seed".to_string(), seed.to_string());
360        }
361        if let Some(density) = self.randomization_density {
362            params.insert("randomization_density".to_string(), density.to_string());
363        }
364        if let Some(style) = self.rename_style {
365            params.insert("rename_style".to_string(), style.as_str().to_string());
366        }
367        if let Some(mode) = self.code_virtualization {
368            params.insert("code_virtualization".to_string(), mode.as_str().to_string());
369        }
370
371        //
372        // obfuscation strategies
373        //
374        if self.self_defending {
375            params.insert("self_defending".to_string(), "1".to_string());
376        }
377        if self.protection_linker {
378            params.insert("protection_linker".to_string(), "1".to_string());
379        }
380        if self.rename_variables {
381            params.insert("rename_variables".to_string(), "1".to_string());
382        }
383        if self.rename_parameters {
384            params.insert("rename_parameters".to_string(), "1".to_string());
385        }
386        if self.rename_functions {
387            params.insert("rename_functions".to_string(), "1".to_string());
388        }
389        if self.rename_function_calls {
390            params.insert("rename_function_calls".to_string(), "1".to_string());
391        }
392        if self.shuffle_functions {
393            params.insert("shuffle_functions".to_string(), "1".to_string());
394        }
395        if self.resolve_constants {
396            params.insert("resolve_constants".to_string(), "1".to_string());
397        }
398        if self.split_strings {
399            params.insert("split_strings".to_string(), "1".to_string());
400        }
401        if self.modify_strings {
402            params.insert("modify_strings".to_string(), "1".to_string());
403        }
404        if self.encrypt_strings {
405            params.insert("encrypt_strings".to_string(), "1".to_string());
406        }
407        if self.string_char_array_vault {
408            params.insert("string_char_array_vault".to_string(), "1".to_string());
409        }
410        if self.encrypt_integers {
411            params.insert("encrypt_integers".to_string(), "1".to_string());
412        }
413        if self.encrypt_floating {
414            params.insert("encrypt_floating".to_string(), "1".to_string());
415        }
416        if self.mba_binops {
417            params.insert("mba_binops".to_string(), "1".to_string());
418        }
419        if self.integers_to_floating {
420            params.insert("integers_to_floating".to_string(), "1".to_string());
421        }
422        if self.integers_to_arrays {
423            params.insert("integers_to_arrays".to_string(), "1".to_string());
424        }
425        if self.floats_to_arrays {
426            params.insert("floats_to_arrays".to_string(), "1".to_string());
427        }
428        if self.affine_integer_mask {
429            params.insert("affine_integer_mask".to_string(), "1".to_string());
430        }
431        if self.array_int_crypt {
432            params.insert("array_int_crypt".to_string(), "1".to_string());
433        }
434        if self.array_char_crypt {
435            params.insert("array_char_crypt".to_string(), "1".to_string());
436        }
437        if self.array_double_crypt {
438            params.insert("array_double_crypt".to_string(), "1".to_string());
439        }
440        if self.array_string_crypt {
441            params.insert("array_string_crypt".to_string(), "1".to_string());
442        }
443        if self.insert_random_value_bucket {
444            params.insert("insert_random_value_bucket".to_string(), "1".to_string());
445        }
446        if self.random_bucket_integers {
447            params.insert("random_bucket_integers".to_string(), "1".to_string());
448        }
449        if self.random_bucket_arrays {
450            params.insert("random_bucket_arrays".to_string(), "1".to_string());
451        }
452        if self.random_bucket_functions {
453            params.insert("random_bucket_functions".to_string(), "1".to_string());
454        }
455        if self.random_bucket_characters {
456            params.insert("random_bucket_characters".to_string(), "1".to_string());
457        }
458        if self.random_bucket_anti_regex {
459            params.insert("random_bucket_anti_regex".to_string(), "1".to_string());
460        }
461        if self.random_bucket_autostart {
462            params.insert("random_bucket_autostart".to_string(), "1".to_string());
463        }
464        if self.insert_ternary_operators {
465            params.insert("insert_ternary_operators".to_string(), "1".to_string());
466        }
467        if self.complexify_booleans {
468            params.insert("complexify_booleans".to_string(), "1".to_string());
469        }
470        if self.opaque_branches {
471            params.insert("opaque_branches".to_string(), "1".to_string());
472        }
473        if self.opaque_mixer_chain {
474            params.insert("opaque_mixer_chain".to_string(), "1".to_string());
475        }
476        if self.insert_dead_code {
477            params.insert("insert_dead_code".to_string(), "1".to_string());
478        }
479        if self.try_finally_noise {
480            params.insert("try_finally_noise".to_string(), "1".to_string());
481        }
482        if self.decoy_functions {
483            params.insert("decoy_functions".to_string(), "1".to_string());
484        }
485        if self.lambda_decoys {
486            params.insert("lambda_decoys".to_string(), "1".to_string());
487        }
488        if self.literal_padding {
489            params.insert("literal_padding".to_string(), "1".to_string());
490        }
491        if self.fake_import_markers {
492            params.insert("fake_import_markers".to_string(), "1".to_string());
493        }
494        if self.dynamic_getattr_calls {
495            params.insert("dynamic_getattr_calls".to_string(), "1".to_string());
496        }
497        if self.obfuscate_imports {
498            params.insert("obfuscate_imports".to_string(), "1".to_string());
499        }
500        if self.callback_registration_stubs {
501            params.insert("callback_registration_stubs".to_string(), "1".to_string());
502        }
503        if self.detect_debugger {
504            params.insert("detect_debugger".to_string(), "1".to_string());
505        }
506        if self.anti_vm {
507            params.insert("anti_vm".to_string(), "1".to_string());
508        }
509        if self.anti_sandbox {
510            params.insert("anti_sandbox".to_string(), "1".to_string());
511        }
512        if self.anti_emulator {
513            params.insert("anti_emulator".to_string(), "1".to_string());
514        }
515        if self.remove_comments {
516            params.insert("remove_comments".to_string(), "1".to_string());
517        }
518
519        //
520        // check if compression is enabled
521        //
522        if self.enable_compression {
523            if let Some(source) = params.get("source").cloned() {
524                let mut enc = ZlibEncoder::new(Vec::new(), Compression::best());
525                enc.write_all(source.as_bytes()).ok()?;
526                let compressed = enc.finish().ok()?;
527                params.insert("source".to_string(), B64_ENGINE.encode(compressed));
528                params.insert("compression".to_string(), "1".to_string());
529            }
530        }
531
532        let mut form = reqwest::multipart::Form::new();
533        for (k, v) in params {
534            form = form.text(k, v);
535        }
536
537        let response_text = self
538            .client
539            .post(Self::API_URL)
540            .header("User-Agent", "PELock Python Obfuscator")
541            .multipart(form)
542            .send()
543            .await
544            .ok()?
545            .text()
546            .await
547            .ok()?;
548
549        //
550        // check the result
551        //
552        if response_text.is_empty() {
553            return None;
554        }
555
556        let mut result: PythonObfuscatorResult =
557            serde_json::from_str(&response_text).ok()?;
558
559        //
560        // depack output code back into the string
561        //
562        let mut depacked = false;
563
564        if self.enable_compression
565            && result.error == Self::ERROR_SUCCESS
566            && result.output.as_ref().is_some_and(|s| !s.is_empty())
567        {
568            let b64 = result.output.as_ref()?;
569            let buf = B64_ENGINE.decode(b64.as_bytes()).ok()?;
570            let mut decoder = ZlibDecoder::new(&buf[..]);
571            let mut out = String::new();
572            decoder.read_to_string(&mut out).ok()?;
573            result.output = Some(out);
574            depacked = true;
575        }
576
577        if return_as_object {
578            return Some(PythonObfuscatorResponse::Object(result));
579        }
580
581        //
582        // if output was depacked - pack it again to JSON format
583        //
584        if depacked {
585            let s = serde_json::to_string(&result).ok()?;
586            return Some(PythonObfuscatorResponse::Json(s));
587        }
588
589        //
590        // return original JSON response code
591        //
592        Some(PythonObfuscatorResponse::Json(response_text))
593    }
594}