python-obfuscator 1.0.0

Python Obfuscator Web API interface can help you obfuscate and protect Python .py source code against analysis, reverse engineering and technology theft. Python Obfuscator provides advanced Python 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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/******************************************************************************
 * Python 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 [`PythonObfuscator::ERROR_SUCCESS`] and related constants).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PythonObfuscatorResult {
    /// Error code (see `ERROR_*` constants on [`PythonObfuscator`]).
    pub error: i64,
    /// Obfuscated source when error is [`PythonObfuscator::ERROR_SUCCESS`].
    #[serde(default)]
    pub output: Option<String>,
    /// 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).
    #[serde(default)]
    pub demo: Option<bool>,
    /// License end date (Y-m-d), empty if none.
    #[serde(default, rename = "license_expiration")]
    pub license_expiration: Option<String>,
    /// Total obfuscations for this activation code.
    #[serde(default, rename = "usages_total")]
    pub usages_total: Option<i64>,
    /// 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 PythonObfuscatorResponse {
    /// Structured result (after optional output decompression).
    Object(PythonObfuscatorResult),
    /// JSON encoded string (original body, or re-encoded after decompression).
    Json(String),
}

/// Public virtualization mode posted as `code_virtualization`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CodeVirtualization {
    #[serde(rename = "vm")]
    Vm,
    #[serde(rename = "fsa")]
    Fsa,
    #[serde(rename = "flat")]
    Flat,
}

impl CodeVirtualization {
    /// Wire value for the Web API (`vm`, `fsa`, or `flat`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Vm => "vm",
            Self::Fsa => "fsa",
            Self::Flat => "flat",
        }
    }
}

/// Identifier alphabet posted as `rename_style`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RenameStyle {
    #[serde(rename = "il")]
    Il,
    #[serde(rename = "o0")]
    O0,
    #[serde(rename = "confusable")]
    Confusable,
    #[serde(rename = "hex")]
    Hex,
    #[serde(rename = "homoglyph")]
    Homoglyph,
    #[serde(rename = "mangled")]
    Mangled,
}

impl RenameStyle {
    /// Wire value for the Web API.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Il => "il",
            Self::O0 => "o0",
            Self::Confusable => "confusable",
            Self::Hex => "hex",
            Self::Homoglyph => "homoglyph",
            Self::Mangled => "mangled",
        }
    }
}

/// Python Obfuscator WebApi client.
#[derive(Debug, Clone)]
pub struct PythonObfuscator {
    api_key: Option<String>,
    client: reqwest::Client,
    /// Should the source code be compressed.
    pub enable_compression: bool,
    /// Fixed random seed for reproducible obfuscation output (optional).
    pub seed: Option<i64>,
    /// Randomization density / intensity (0-100).
    pub randomization_density: Option<i64>,
    /// Identifier renaming style (il, o0, confusable, hex, homoglyph, mangled).
    pub rename_style: Option<RenameStyle>,
    /// Public virtualization mode (vm, fsa, or flat). Set to `None` to skip virtualization.
    pub code_virtualization: Option<CodeVirtualization>,
    /// 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,
    /// Rename function call references consistently with renamed functions.
    pub rename_function_calls: bool,
    /// Shuffle function order in the output source.
    pub shuffle_functions: bool,
    /// Fold/resolve constant expressions at obfuscation time.
    pub resolve_constants: bool,
    /// Split strings into concatenated chunks.
    pub split_strings: bool,
    /// Apply light transformations/mutations to string literals.
    pub modify_strings: bool,
    /// Encrypt strings using randomly generated polymorphic encryption algorithms.
    pub encrypt_strings: bool,
    /// Store string fragments in char-code array vaults.
    pub string_char_array_vault: bool,
    /// Encrypt integers.
    pub encrypt_integers: bool,
    /// Encrypt floating point numbers.
    pub encrypt_floating: bool,
    /// Replace binary operators with mixed boolean-arithmetic (MBA) equivalents.
    pub mba_binops: bool,
    /// Represent integers via floating-point math.
    pub integers_to_floating: bool,
    /// Move integers to arrays.
    pub integers_to_arrays: bool,
    /// Move floats to arrays.
    pub floats_to_arrays: bool,
    /// Apply redundant xor / affine integer masks.
    pub affine_integer_mask: bool,
    /// Encrypt integer array literals.
    pub array_int_crypt: bool,
    /// Encrypt character array literals.
    pub array_char_crypt: bool,
    /// Encrypt floating-point array literals.
    pub array_double_crypt: bool,
    /// Encrypt string array literals.
    pub array_string_crypt: bool,
    /// Insert a shared bucket of random noise values used by other strategies.
    pub insert_random_value_bucket: bool,
    /// Populate the random value bucket with decoy integers.
    pub random_bucket_integers: bool,
    /// Populate the random value bucket with decoy arrays.
    pub random_bucket_arrays: bool,
    /// Populate the random value bucket with decoy functions.
    pub random_bucket_functions: bool,
    /// Populate the random value bucket with decoy characters.
    pub random_bucket_characters: bool,
    /// Populate the random value bucket with anti-regex decoy noise.
    pub random_bucket_anti_regex: bool,
    /// Populate the random value bucket with autostart decoy stubs.
    pub random_bucket_autostart: bool,
    /// Rewrite selected statements using ternary operators.
    pub insert_ternary_operators: bool,
    /// Replace boolean conditions with equivalent complex expressions.
    pub complexify_booleans: bool,
    /// Insert opaque predicate branches.
    pub opaque_branches: bool,
    /// Insert opaque mixer chains into control flow.
    pub opaque_mixer_chain: bool,
    /// Insert dead code.
    pub insert_dead_code: bool,
    /// Wrap code in try/finally blocks with dead noise.
    pub try_finally_noise: bool,
    /// Insert decoy functions.
    pub decoy_functions: bool,
    /// Insert decoy lambda expressions.
    pub lambda_decoys: bool,
    /// Insert literal padding noise.
    pub literal_padding: bool,
    /// Insert fake import statement markers.
    pub fake_import_markers: bool,
    /// Use dynamic getattr()-based indirect calls.
    pub dynamic_getattr_calls: bool,
    /// Rewrite absolute imports into __import__ / getattr.
    pub obfuscate_imports: bool,
    /// Insert dead callback/event registration stubs.
    pub callback_registration_stubs: bool,
    /// Insert anti-debugging detections.
    pub detect_debugger: bool,
    /// Insert virtual machine (anti-VM) detections.
    pub anti_vm: bool,
    /// Insert anti-sandbox detections.
    pub anti_sandbox: bool,
    /// Insert anti-emulators (CPU) detections.
    pub anti_emulator: bool,
    /// Strip comments from the output source.
    pub remove_comments: bool,
}

impl PythonObfuscator {
    /// Default Python Obfuscator WebApi endpoint.
    pub const API_URL: &'static str = "https://www.pelock.com/api/python-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;

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

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

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

    /// Initialize Python Obfuscator client.
    ///
    /// `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).
    pub fn new(api_key: Option<String>) -> Self {
        Self {
            api_key,
            client: reqwest::Client::new(),
            enable_compression: false,
            seed: None,
            randomization_density: None,
            rename_style: None,
            code_virtualization: Some(CodeVirtualization::Vm),
            self_defending: false,
            protection_linker: false,
            rename_variables: true,
            rename_parameters: true,
            rename_functions: true,
            rename_function_calls: true,
            shuffle_functions: true,
            resolve_constants: true,
            split_strings: true,
            modify_strings: true,
            encrypt_strings: true,
            string_char_array_vault: true,
            encrypt_integers: true,
            encrypt_floating: true,
            mba_binops: true,
            integers_to_floating: true,
            integers_to_arrays: true,
            floats_to_arrays: true,
            affine_integer_mask: true,
            array_int_crypt: true,
            array_char_crypt: true,
            array_double_crypt: true,
            array_string_crypt: true,
            insert_random_value_bucket: true,
            random_bucket_integers: true,
            random_bucket_arrays: true,
            random_bucket_functions: true,
            random_bucket_characters: true,
            random_bucket_anti_regex: true,
            random_bucket_autostart: true,
            insert_ternary_operators: true,
            complexify_booleans: true,
            opaque_branches: true,
            opaque_mixer_chain: true,
            insert_dead_code: true,
            try_finally_noise: true,
            decoy_functions: true,
            lambda_decoys: true,
            literal_padding: true,
            fake_import_markers: true,
            dynamic_getattr_calls: true,
            obfuscate_imports: true,
            callback_registration_stubs: true,
            detect_debugger: false,
            anti_vm: false,
            anti_sandbox: false,
            anti_emulator: false,
            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<PythonObfuscatorResponse> {
        let mut params = HashMap::new();
        params.insert("command".to_string(), "login".to_string());
        self.post_request(params, return_as_object).await
    }

    /// Obfuscate Python 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<PythonObfuscatorResponse> {
        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 Python 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<PythonObfuscatorResponse> {
        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<PythonObfuscatorResponse> {
        //
        // 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());
            }
        }

        //
        // global tuning options
        //
        if let Some(seed) = self.seed {
            params.insert("seed".to_string(), seed.to_string());
        }
        if let Some(density) = self.randomization_density {
            params.insert("randomization_density".to_string(), density.to_string());
        }
        if let Some(style) = self.rename_style {
            params.insert("rename_style".to_string(), style.as_str().to_string());
        }
        if let Some(mode) = self.code_virtualization {
            params.insert("code_virtualization".to_string(), mode.as_str().to_string());
        }

        //
        // 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.rename_function_calls {
            params.insert("rename_function_calls".to_string(), "1".to_string());
        }
        if self.shuffle_functions {
            params.insert("shuffle_functions".to_string(), "1".to_string());
        }
        if self.resolve_constants {
            params.insert("resolve_constants".to_string(), "1".to_string());
        }
        if self.split_strings {
            params.insert("split_strings".to_string(), "1".to_string());
        }
        if self.modify_strings {
            params.insert("modify_strings".to_string(), "1".to_string());
        }
        if self.encrypt_strings {
            params.insert("encrypt_strings".to_string(), "1".to_string());
        }
        if self.string_char_array_vault {
            params.insert("string_char_array_vault".to_string(), "1".to_string());
        }
        if self.encrypt_integers {
            params.insert("encrypt_integers".to_string(), "1".to_string());
        }
        if self.encrypt_floating {
            params.insert("encrypt_floating".to_string(), "1".to_string());
        }
        if self.mba_binops {
            params.insert("mba_binops".to_string(), "1".to_string());
        }
        if self.integers_to_floating {
            params.insert("integers_to_floating".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.affine_integer_mask {
            params.insert("affine_integer_mask".to_string(), "1".to_string());
        }
        if self.array_int_crypt {
            params.insert("array_int_crypt".to_string(), "1".to_string());
        }
        if self.array_char_crypt {
            params.insert("array_char_crypt".to_string(), "1".to_string());
        }
        if self.array_double_crypt {
            params.insert("array_double_crypt".to_string(), "1".to_string());
        }
        if self.array_string_crypt {
            params.insert("array_string_crypt".to_string(), "1".to_string());
        }
        if self.insert_random_value_bucket {
            params.insert("insert_random_value_bucket".to_string(), "1".to_string());
        }
        if self.random_bucket_integers {
            params.insert("random_bucket_integers".to_string(), "1".to_string());
        }
        if self.random_bucket_arrays {
            params.insert("random_bucket_arrays".to_string(), "1".to_string());
        }
        if self.random_bucket_functions {
            params.insert("random_bucket_functions".to_string(), "1".to_string());
        }
        if self.random_bucket_characters {
            params.insert("random_bucket_characters".to_string(), "1".to_string());
        }
        if self.random_bucket_anti_regex {
            params.insert("random_bucket_anti_regex".to_string(), "1".to_string());
        }
        if self.random_bucket_autostart {
            params.insert("random_bucket_autostart".to_string(), "1".to_string());
        }
        if self.insert_ternary_operators {
            params.insert("insert_ternary_operators".to_string(), "1".to_string());
        }
        if self.complexify_booleans {
            params.insert("complexify_booleans".to_string(), "1".to_string());
        }
        if self.opaque_branches {
            params.insert("opaque_branches".to_string(), "1".to_string());
        }
        if self.opaque_mixer_chain {
            params.insert("opaque_mixer_chain".to_string(), "1".to_string());
        }
        if self.insert_dead_code {
            params.insert("insert_dead_code".to_string(), "1".to_string());
        }
        if self.try_finally_noise {
            params.insert("try_finally_noise".to_string(), "1".to_string());
        }
        if self.decoy_functions {
            params.insert("decoy_functions".to_string(), "1".to_string());
        }
        if self.lambda_decoys {
            params.insert("lambda_decoys".to_string(), "1".to_string());
        }
        if self.literal_padding {
            params.insert("literal_padding".to_string(), "1".to_string());
        }
        if self.fake_import_markers {
            params.insert("fake_import_markers".to_string(), "1".to_string());
        }
        if self.dynamic_getattr_calls {
            params.insert("dynamic_getattr_calls".to_string(), "1".to_string());
        }
        if self.obfuscate_imports {
            params.insert("obfuscate_imports".to_string(), "1".to_string());
        }
        if self.callback_registration_stubs {
            params.insert("callback_registration_stubs".to_string(), "1".to_string());
        }
        if self.detect_debugger {
            params.insert("detect_debugger".to_string(), "1".to_string());
        }
        if self.anti_vm {
            params.insert("anti_vm".to_string(), "1".to_string());
        }
        if self.anti_sandbox {
            params.insert("anti_sandbox".to_string(), "1".to_string());
        }
        if self.anti_emulator {
            params.insert("anti_emulator".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 Python Obfuscator")
            .multipart(form)
            .send()
            .await
            .ok()?
            .text()
            .await
            .ok()?;

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

        let mut result: PythonObfuscatorResult =
            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(PythonObfuscatorResponse::Object(result));
        }

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

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