pynamerx 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pynamerx-0.1.0/.github/workflows/publish.yml +33 -0
- pynamerx-0.1.0/.gitignore +20 -0
- pynamerx-0.1.0/LICENSE +21 -0
- pynamerx-0.1.0/PKG-INFO +178 -0
- pynamerx-0.1.0/README.md +157 -0
- pynamerx-0.1.0/examples/advanced_source.py +83 -0
- pynamerx-0.1.0/examples/demo.py +61 -0
- pynamerx-0.1.0/examples/obfuscate.py +78 -0
- pynamerx-0.1.0/examples/sample.py +39 -0
- pynamerx-0.1.0/pyproject.toml +42 -0
- pynamerx-0.1.0/src/pynamer/__init__.py +35 -0
- pynamerx-0.1.0/src/pynamer/__main__.py +127 -0
- pynamerx-0.1.0/src/pynamer/api.py +205 -0
- pynamerx-0.1.0/src/pynamer/attributes.py +170 -0
- pynamerx-0.1.0/src/pynamer/config.py +88 -0
- pynamerx-0.1.0/src/pynamer/errors.py +24 -0
- pynamerx-0.1.0/src/pynamer/mapfile.py +76 -0
- pynamerx-0.1.0/src/pynamer/minify.py +47 -0
- pynamerx-0.1.0/src/pynamer/names.py +79 -0
- pynamerx-0.1.0/src/pynamer/renamer.py +453 -0
- pynamerx-0.1.0/src/pynamer/symbols.py +542 -0
- pynamerx-0.1.0/src/pynamer/transforms.py +78 -0
- pynamerx-0.1.0/src/pynamer/utils.py +71 -0
- pynamerx-0.1.0/tests/conftest.py +40 -0
- pynamerx-0.1.0/tests/test_api.py +79 -0
- pynamerx-0.1.0/tests/test_behavior.py +308 -0
- pynamerx-0.1.0/tests/test_cli.py +44 -0
- pynamerx-0.1.0/tests/test_config.py +102 -0
- pynamerx-0.1.0/tests/test_mapfile.py +50 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
workflow_dispatch:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- uses: actions/setup-python@v5
|
|
14
|
+
with:
|
|
15
|
+
python-version: "3.x"
|
|
16
|
+
- run: python -m pip install --upgrade build
|
|
17
|
+
- run: python -m build
|
|
18
|
+
- uses: actions/upload-artifact@v4
|
|
19
|
+
with:
|
|
20
|
+
name: dist
|
|
21
|
+
path: dist/
|
|
22
|
+
|
|
23
|
+
publish:
|
|
24
|
+
needs: build
|
|
25
|
+
runs-on: ubuntu-latest
|
|
26
|
+
permissions:
|
|
27
|
+
id-token: write
|
|
28
|
+
steps:
|
|
29
|
+
- uses: actions/download-artifact@v4
|
|
30
|
+
with:
|
|
31
|
+
name: dist
|
|
32
|
+
path: dist/
|
|
33
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
pynamerx-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PyNamer maintainers
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pynamerx-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pynamerx
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A powerful, scope-aware Python source renamer/obfuscator that handles complex scenarios.
|
|
5
|
+
Project-URL: Homepage, https://github.com/pooraddyy/PyNamer
|
|
6
|
+
Project-URL: Repository, https://github.com/pooraddyy/PyNamer
|
|
7
|
+
Project-URL: Issues, https://github.com/pooraddyy/PyNamer/issues
|
|
8
|
+
Author: pooraddyy
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ast,minifier,obfuscation,remapper,renamer,symbol-table
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest>=7.4; extra == 'test'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# PyNamer
|
|
23
|
+
|
|
24
|
+
> A scope-aware Python **source renamer / obfuscator** that survives the hard
|
|
25
|
+
> cases: closures, `global`/`nonlocal`, keyword arguments, inheritance,
|
|
26
|
+
> comprehensions, walrus, `match`, `__slots__` and attributes.
|
|
27
|
+
|
|
28
|
+
PyNamer builds an **explicit scope tree** (much like CPython's own `symtable`),
|
|
29
|
+
performs a dedicated **attribute data-flow analysis**, and rewrites the AST in a
|
|
30
|
+
single, re-entrant pass.
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from pynamer import rename
|
|
34
|
+
|
|
35
|
+
obfuscated = rename(open("secret.py").read())
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Why it is more powerful
|
|
39
|
+
|
|
40
|
+
| Concern | Typical renamers | PyNamer |
|
|
41
|
+
| --- | --- | --- |
|
|
42
|
+
| Re-entrancy | module-level globals | full scope tree, no shared state |
|
|
43
|
+
| Attributes | rename everything / nothing | data-flow: only *locally defined* attributes, never externally observed ones |
|
|
44
|
+
| Keyword arguments | untouched / naive | remapped against the **resolved callee**, MRO-aware, incl. inherited `__init__` |
|
|
45
|
+
| Inheritance | blind | MRO walking for constructors & method kwargs |
|
|
46
|
+
| Comprehensions | leaky | correct Python 3 scoping (first iterable in the enclosing scope) |
|
|
47
|
+
| `getattr(obj, "x")` | broken | constant attribute strings remapped too |
|
|
48
|
+
| Names | readable `_0x1` | deterministic or hashed/compacted, collision-free |
|
|
49
|
+
| Minifier | monkey-patches the unparser | auditable token-aware whitespace pass |
|
|
50
|
+
| Cross-module | none | `RenameMap` gives package-wide, stable names |
|
|
51
|
+
| Safety | none | optional `compile()` validation, preservation lists |
|
|
52
|
+
|
|
53
|
+
## Install
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install -e . # from a checkout
|
|
57
|
+
# or
|
|
58
|
+
pip install -e ".[test]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Requires Python 3.10+.
|
|
62
|
+
|
|
63
|
+
## CLI
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pynamer module.py -o module.obf.py --prefix _0x --strategy base62
|
|
67
|
+
pynamer module.py --builtins --hide-init --strip-docstrings --stats
|
|
68
|
+
cat module.py | pynamer - --strategy hash --seed 7
|
|
69
|
+
python -m pynamer module.py --map-out map.json # reuse later with --map-in
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Library API
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from pynamer import process, rename, rename_ast, RenameConfig, NameStrategy, RenameMap
|
|
76
|
+
|
|
77
|
+
# 1. simplest form -> string in, string out
|
|
78
|
+
out = rename(source)
|
|
79
|
+
|
|
80
|
+
# 2. full result object
|
|
81
|
+
result = process(source, strategy="hash", seed=1, builtins=True)
|
|
82
|
+
print(result.stats.as_dict()) # {"symbols": ..., "attributes": ...}
|
|
83
|
+
print(result.mapping.symbols) # {"my_func": "_0x3", ...}
|
|
84
|
+
result.mapping.save("map.json")
|
|
85
|
+
|
|
86
|
+
# 3. AST in, AST out
|
|
87
|
+
new_tree = rename_ast(result.tree)
|
|
88
|
+
|
|
89
|
+
# 4. explicit config object
|
|
90
|
+
cfg = RenameConfig(strategy=NameStrategy.BASE62, prefix="_", minify=True)
|
|
91
|
+
out = rename(source, config=cfg)
|
|
92
|
+
|
|
93
|
+
# 5. package-wide stable renaming
|
|
94
|
+
shared = RenameMap.load("map.json")
|
|
95
|
+
for path in ("a.py", "b.py"):
|
|
96
|
+
process(open(path).read(), map=shared)
|
|
97
|
+
shared.save("map.json")
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Configuration
|
|
101
|
+
|
|
102
|
+
Every option is a field on [`RenameConfig`](src/pynamer/config.py) and can be
|
|
103
|
+
passed as a keyword argument to `process`/`rename`:
|
|
104
|
+
|
|
105
|
+
| Option | Default | Meaning |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| `strategy` | `"sequential"` | `sequential` / `hash` / `random` / `base62` / `words` |
|
|
108
|
+
| `seed` | `0` | seed for deterministic strategies |
|
|
109
|
+
| `prefix` | `"_0x"` | prefix for generated identifiers |
|
|
110
|
+
| `minify` | `True` | single-space indentation, no blank lines |
|
|
111
|
+
| `strip_docstrings` | `False` | drop module/class/function docstrings |
|
|
112
|
+
| `builtins` | `False` | alias builtins (`print`, `len`, …) at the top of the module |
|
|
113
|
+
| `hide_init` | `False` | obscure explicit constructors behind a forwarding method |
|
|
114
|
+
| `track_instances` | `False` | also rename local `Foo()`-instance variables |
|
|
115
|
+
| `rename_attributes` | `True` | rename locally defined attributes |
|
|
116
|
+
| `rename_kwargs` | `True` | remap keyword arguments of resolvable calls |
|
|
117
|
+
| `preserve` | `()` | names to never rename |
|
|
118
|
+
| `preserve_attributes` | `()` | attributes to never rename |
|
|
119
|
+
| `preserve_public` | `False` | keep public (non-underscore) module names |
|
|
120
|
+
| `validate` | `True` | re-`compile()` the result, raising on breakage |
|
|
121
|
+
| `map` | `None` | a `RenameMap` for cross-module stability |
|
|
122
|
+
|
|
123
|
+
## What is deliberately *not* renamed
|
|
124
|
+
|
|
125
|
+
* `__dunder__` names and the `super` builtin (zero-arg `super()` relies on the
|
|
126
|
+
literal name for the `__class__` cell).
|
|
127
|
+
* `visit_*` methods by default (they form the `ast.NodeVisitor` protocol).
|
|
128
|
+
* `from __future__ import ...` feature names (they are compiler flags).
|
|
129
|
+
* Attributes that also appear on objects PyNamer cannot reason about, and any
|
|
130
|
+
attribute reached through `super()` unless it is defined on a *local* base.
|
|
131
|
+
* Names listed in `preserve` / `preserve_attributes`.
|
|
132
|
+
* Parameter names that are passed as a keyword at a call site whose callee
|
|
133
|
+
cannot be resolved statically (for example `receiver.method(x=1)` on an
|
|
134
|
+
unknown object, or any `**mapping` call) - renaming them would silently break
|
|
135
|
+
the call, so they keep their spelling.
|
|
136
|
+
|
|
137
|
+
## Known limitations
|
|
138
|
+
|
|
139
|
+
Renaming is a semantics-preserving source transformation *up to* reflection:
|
|
140
|
+
|
|
141
|
+
* A renamed class/function reports its new `__name__` / `__qualname__`,
|
|
142
|
+
`__doc__` disappears when `strip_docstrings=True`, and an `Enum` member's
|
|
143
|
+
`.name` reflects the new spelling. Avoid depending on those strings, or list
|
|
144
|
+
the symbol in `preserve` / `preserve_attributes`.
|
|
145
|
+
* Dynamic name lookups via `globals()`, `eval`, `locals()` or non-constant
|
|
146
|
+
`getattr(obj, some_variable)` cannot be tracked. Constant
|
|
147
|
+
`getattr`/`setattr`/`hasattr`/`delattr` **are** handled.
|
|
148
|
+
* Attributes of classes whose bases live outside the processed source are left
|
|
149
|
+
untouched (safe by default).
|
|
150
|
+
|
|
151
|
+
## Examples
|
|
152
|
+
|
|
153
|
+
Runnable examples live in [`examples/`](examples):
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
python examples/demo.py # end-to-end demonstration
|
|
157
|
+
python examples/obfuscate.py examples/advanced_source.py # obfuscate & verify a file
|
|
158
|
+
python examples/obfuscate.py examples/advanced_source.py -o out.py --builtins
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
* `examples/sample.py` - a small `Money` program used by the demo.
|
|
162
|
+
* `examples/advanced_source.py` - a deliberately gnarly module (closures,
|
|
163
|
+
`global`/`nonlocal`, kwargs across inheritance, `super()`, `__slots__`,
|
|
164
|
+
`match`, walrus comprehensions, constant `getattr`).
|
|
165
|
+
* `examples/obfuscate.py` - obfuscates a file with the library API and asserts
|
|
166
|
+
the obfuscated module still produces identical output.
|
|
167
|
+
|
|
168
|
+
## Testing
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
pip install -e ".[test]"
|
|
172
|
+
pytest # behaviour-preservation & unit tests
|
|
173
|
+
python examples/demo.py # end-to-end demonstration
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## License
|
|
177
|
+
|
|
178
|
+
MIT - see [LICENSE](LICENSE).
|
pynamerx-0.1.0/README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# PyNamer
|
|
2
|
+
|
|
3
|
+
> A scope-aware Python **source renamer / obfuscator** that survives the hard
|
|
4
|
+
> cases: closures, `global`/`nonlocal`, keyword arguments, inheritance,
|
|
5
|
+
> comprehensions, walrus, `match`, `__slots__` and attributes.
|
|
6
|
+
|
|
7
|
+
PyNamer builds an **explicit scope tree** (much like CPython's own `symtable`),
|
|
8
|
+
performs a dedicated **attribute data-flow analysis**, and rewrites the AST in a
|
|
9
|
+
single, re-entrant pass.
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from pynamer import rename
|
|
13
|
+
|
|
14
|
+
obfuscated = rename(open("secret.py").read())
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Why it is more powerful
|
|
18
|
+
|
|
19
|
+
| Concern | Typical renamers | PyNamer |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| Re-entrancy | module-level globals | full scope tree, no shared state |
|
|
22
|
+
| Attributes | rename everything / nothing | data-flow: only *locally defined* attributes, never externally observed ones |
|
|
23
|
+
| Keyword arguments | untouched / naive | remapped against the **resolved callee**, MRO-aware, incl. inherited `__init__` |
|
|
24
|
+
| Inheritance | blind | MRO walking for constructors & method kwargs |
|
|
25
|
+
| Comprehensions | leaky | correct Python 3 scoping (first iterable in the enclosing scope) |
|
|
26
|
+
| `getattr(obj, "x")` | broken | constant attribute strings remapped too |
|
|
27
|
+
| Names | readable `_0x1` | deterministic or hashed/compacted, collision-free |
|
|
28
|
+
| Minifier | monkey-patches the unparser | auditable token-aware whitespace pass |
|
|
29
|
+
| Cross-module | none | `RenameMap` gives package-wide, stable names |
|
|
30
|
+
| Safety | none | optional `compile()` validation, preservation lists |
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install -e . # from a checkout
|
|
36
|
+
# or
|
|
37
|
+
pip install -e ".[test]"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Requires Python 3.10+.
|
|
41
|
+
|
|
42
|
+
## CLI
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pynamer module.py -o module.obf.py --prefix _0x --strategy base62
|
|
46
|
+
pynamer module.py --builtins --hide-init --strip-docstrings --stats
|
|
47
|
+
cat module.py | pynamer - --strategy hash --seed 7
|
|
48
|
+
python -m pynamer module.py --map-out map.json # reuse later with --map-in
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Library API
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from pynamer import process, rename, rename_ast, RenameConfig, NameStrategy, RenameMap
|
|
55
|
+
|
|
56
|
+
# 1. simplest form -> string in, string out
|
|
57
|
+
out = rename(source)
|
|
58
|
+
|
|
59
|
+
# 2. full result object
|
|
60
|
+
result = process(source, strategy="hash", seed=1, builtins=True)
|
|
61
|
+
print(result.stats.as_dict()) # {"symbols": ..., "attributes": ...}
|
|
62
|
+
print(result.mapping.symbols) # {"my_func": "_0x3", ...}
|
|
63
|
+
result.mapping.save("map.json")
|
|
64
|
+
|
|
65
|
+
# 3. AST in, AST out
|
|
66
|
+
new_tree = rename_ast(result.tree)
|
|
67
|
+
|
|
68
|
+
# 4. explicit config object
|
|
69
|
+
cfg = RenameConfig(strategy=NameStrategy.BASE62, prefix="_", minify=True)
|
|
70
|
+
out = rename(source, config=cfg)
|
|
71
|
+
|
|
72
|
+
# 5. package-wide stable renaming
|
|
73
|
+
shared = RenameMap.load("map.json")
|
|
74
|
+
for path in ("a.py", "b.py"):
|
|
75
|
+
process(open(path).read(), map=shared)
|
|
76
|
+
shared.save("map.json")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Configuration
|
|
80
|
+
|
|
81
|
+
Every option is a field on [`RenameConfig`](src/pynamer/config.py) and can be
|
|
82
|
+
passed as a keyword argument to `process`/`rename`:
|
|
83
|
+
|
|
84
|
+
| Option | Default | Meaning |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `strategy` | `"sequential"` | `sequential` / `hash` / `random` / `base62` / `words` |
|
|
87
|
+
| `seed` | `0` | seed for deterministic strategies |
|
|
88
|
+
| `prefix` | `"_0x"` | prefix for generated identifiers |
|
|
89
|
+
| `minify` | `True` | single-space indentation, no blank lines |
|
|
90
|
+
| `strip_docstrings` | `False` | drop module/class/function docstrings |
|
|
91
|
+
| `builtins` | `False` | alias builtins (`print`, `len`, …) at the top of the module |
|
|
92
|
+
| `hide_init` | `False` | obscure explicit constructors behind a forwarding method |
|
|
93
|
+
| `track_instances` | `False` | also rename local `Foo()`-instance variables |
|
|
94
|
+
| `rename_attributes` | `True` | rename locally defined attributes |
|
|
95
|
+
| `rename_kwargs` | `True` | remap keyword arguments of resolvable calls |
|
|
96
|
+
| `preserve` | `()` | names to never rename |
|
|
97
|
+
| `preserve_attributes` | `()` | attributes to never rename |
|
|
98
|
+
| `preserve_public` | `False` | keep public (non-underscore) module names |
|
|
99
|
+
| `validate` | `True` | re-`compile()` the result, raising on breakage |
|
|
100
|
+
| `map` | `None` | a `RenameMap` for cross-module stability |
|
|
101
|
+
|
|
102
|
+
## What is deliberately *not* renamed
|
|
103
|
+
|
|
104
|
+
* `__dunder__` names and the `super` builtin (zero-arg `super()` relies on the
|
|
105
|
+
literal name for the `__class__` cell).
|
|
106
|
+
* `visit_*` methods by default (they form the `ast.NodeVisitor` protocol).
|
|
107
|
+
* `from __future__ import ...` feature names (they are compiler flags).
|
|
108
|
+
* Attributes that also appear on objects PyNamer cannot reason about, and any
|
|
109
|
+
attribute reached through `super()` unless it is defined on a *local* base.
|
|
110
|
+
* Names listed in `preserve` / `preserve_attributes`.
|
|
111
|
+
* Parameter names that are passed as a keyword at a call site whose callee
|
|
112
|
+
cannot be resolved statically (for example `receiver.method(x=1)` on an
|
|
113
|
+
unknown object, or any `**mapping` call) - renaming them would silently break
|
|
114
|
+
the call, so they keep their spelling.
|
|
115
|
+
|
|
116
|
+
## Known limitations
|
|
117
|
+
|
|
118
|
+
Renaming is a semantics-preserving source transformation *up to* reflection:
|
|
119
|
+
|
|
120
|
+
* A renamed class/function reports its new `__name__` / `__qualname__`,
|
|
121
|
+
`__doc__` disappears when `strip_docstrings=True`, and an `Enum` member's
|
|
122
|
+
`.name` reflects the new spelling. Avoid depending on those strings, or list
|
|
123
|
+
the symbol in `preserve` / `preserve_attributes`.
|
|
124
|
+
* Dynamic name lookups via `globals()`, `eval`, `locals()` or non-constant
|
|
125
|
+
`getattr(obj, some_variable)` cannot be tracked. Constant
|
|
126
|
+
`getattr`/`setattr`/`hasattr`/`delattr` **are** handled.
|
|
127
|
+
* Attributes of classes whose bases live outside the processed source are left
|
|
128
|
+
untouched (safe by default).
|
|
129
|
+
|
|
130
|
+
## Examples
|
|
131
|
+
|
|
132
|
+
Runnable examples live in [`examples/`](examples):
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
python examples/demo.py # end-to-end demonstration
|
|
136
|
+
python examples/obfuscate.py examples/advanced_source.py # obfuscate & verify a file
|
|
137
|
+
python examples/obfuscate.py examples/advanced_source.py -o out.py --builtins
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
* `examples/sample.py` - a small `Money` program used by the demo.
|
|
141
|
+
* `examples/advanced_source.py` - a deliberately gnarly module (closures,
|
|
142
|
+
`global`/`nonlocal`, kwargs across inheritance, `super()`, `__slots__`,
|
|
143
|
+
`match`, walrus comprehensions, constant `getattr`).
|
|
144
|
+
* `examples/obfuscate.py` - obfuscates a file with the library API and asserts
|
|
145
|
+
the obfuscated module still produces identical output.
|
|
146
|
+
|
|
147
|
+
## Testing
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
pip install -e ".[test]"
|
|
151
|
+
pytest # behaviour-preservation & unit tests
|
|
152
|
+
python examples/demo.py # end-to-end demonstration
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## License
|
|
156
|
+
|
|
157
|
+
MIT - see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
|
|
5
|
+
CATALOG = {"widget": 9.99, "gadget": 19.5}
|
|
6
|
+
VISITS = 0
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make_counter(start=0):
|
|
10
|
+
total = start
|
|
11
|
+
|
|
12
|
+
def bump(step=1):
|
|
13
|
+
nonlocal total
|
|
14
|
+
total += step
|
|
15
|
+
return total
|
|
16
|
+
|
|
17
|
+
return bump
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@functools.lru_cache(maxsize=None)
|
|
21
|
+
def price_of(item, *, tax=0.0):
|
|
22
|
+
global VISITS
|
|
23
|
+
VISITS += 1
|
|
24
|
+
base = CATALOG[item]
|
|
25
|
+
return round(base * (1 + tax), 2)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Node:
|
|
29
|
+
__slots__ = ("value", "children")
|
|
30
|
+
|
|
31
|
+
def __init__(self, value, children=None):
|
|
32
|
+
self.value = value
|
|
33
|
+
self.children = children or []
|
|
34
|
+
|
|
35
|
+
def weighted(self, *, scale=1.0):
|
|
36
|
+
return self.value * scale + sum(
|
|
37
|
+
child.weighted(scale=scale) for child in self.children
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Discounted(Node):
|
|
42
|
+
def weighted(self, *, scale=1.0, discount=0.0):
|
|
43
|
+
total = super().weighted(scale=scale)
|
|
44
|
+
return round(total * (1 - discount), 2)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def classify(value):
|
|
48
|
+
match value:
|
|
49
|
+
case 0:
|
|
50
|
+
return "zero"
|
|
51
|
+
case int() if value < 0:
|
|
52
|
+
return "negative"
|
|
53
|
+
case [first, *rest]:
|
|
54
|
+
return f"list starting {first} (+{len(rest)})"
|
|
55
|
+
case {"kind": kind, **extra}:
|
|
56
|
+
return f"{kind}:{len(extra)}"
|
|
57
|
+
case _:
|
|
58
|
+
return "other"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def running_max(numbers):
|
|
62
|
+
best = 0
|
|
63
|
+
return [best := max(best, n) for n in numbers]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def main():
|
|
67
|
+
counter = make_counter(10)
|
|
68
|
+
print("counter:", counter(), counter(5), counter())
|
|
69
|
+
|
|
70
|
+
tree = Discounted(5, [Node(2), Node(3, [Node(1)])])
|
|
71
|
+
print("price:", price_of("widget", tax=0.1), "visits:", VISITS)
|
|
72
|
+
print("tree:", tree.weighted(scale=2.0, discount=0.25))
|
|
73
|
+
|
|
74
|
+
samples = [0, -3, [1, 2, 3], {"kind": "box", "w": 1, "h": 2}, 3.14]
|
|
75
|
+
print("classify:", ", ".join(classify(s) for s in samples))
|
|
76
|
+
print("running_max:", running_max([3, 1, 4, 1, 5]))
|
|
77
|
+
|
|
78
|
+
node = Node(7)
|
|
79
|
+
print("getattr:", getattr(node, "value"))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
main()
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import io
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
|
9
|
+
|
|
10
|
+
from pynamer import process
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def behaviour(source: str, filename: str) -> str:
|
|
14
|
+
namespace: dict = {"__name__": "__main__"}
|
|
15
|
+
buffer = io.StringIO()
|
|
16
|
+
with contextlib.redirect_stdout(buffer):
|
|
17
|
+
exec(compile(source, filename, "exec"), namespace)
|
|
18
|
+
return buffer.getvalue()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main() -> None:
|
|
22
|
+
here = os.path.dirname(__file__)
|
|
23
|
+
path = os.path.join(here, "sample.py")
|
|
24
|
+
original = open(path).read()
|
|
25
|
+
|
|
26
|
+
print("=" * 72)
|
|
27
|
+
print("PyNamer demo")
|
|
28
|
+
print("=" * 72)
|
|
29
|
+
|
|
30
|
+
for label, config in {
|
|
31
|
+
"sequential + attributes + minify": {},
|
|
32
|
+
"hashed names, no minify": {"strategy": "hash", "seed": 7, "minify": False},
|
|
33
|
+
"builtins + hide_init + strip_docstrings": {
|
|
34
|
+
"strategy": "base62",
|
|
35
|
+
"prefix": "_",
|
|
36
|
+
"builtins": True,
|
|
37
|
+
"hide_init": True,
|
|
38
|
+
"strip_docstrings": True,
|
|
39
|
+
},
|
|
40
|
+
}.items():
|
|
41
|
+
result = process(original, filename=path, config=None, **config)
|
|
42
|
+
print(f"\n### {label}")
|
|
43
|
+
print(
|
|
44
|
+
f" symbols={result.stats.symbols} "
|
|
45
|
+
f"attributes={result.stats.attributes} "
|
|
46
|
+
f"builtins={result.stats.builtins} "
|
|
47
|
+
f"size {result.stats.input_size} -> {result.stats.output_size}"
|
|
48
|
+
)
|
|
49
|
+
assert behaviour(original, path) == behaviour(result.source, path), (
|
|
50
|
+
f"behaviour changed for {label!r}"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
print("\n" + "-" * 72)
|
|
54
|
+
print("Obfuscated output (first configuration):")
|
|
55
|
+
print("-" * 72)
|
|
56
|
+
print(process(original, filename=path).source)
|
|
57
|
+
print("Behaviour is identical to the original for every configuration.")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
main()
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import contextlib
|
|
5
|
+
import io
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
|
10
|
+
|
|
11
|
+
from pynamer import process
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run_source(source: str, filename: str) -> str:
|
|
15
|
+
namespace: dict = {"__name__": "__main__"}
|
|
16
|
+
buffer = io.StringIO()
|
|
17
|
+
with contextlib.redirect_stdout(buffer):
|
|
18
|
+
exec(compile(source, filename, "exec"), namespace)
|
|
19
|
+
return buffer.getvalue()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse_args(argv=None):
|
|
23
|
+
parser = argparse.ArgumentParser(
|
|
24
|
+
description="Obfuscate a Python file with PyNamer and verify it still runs."
|
|
25
|
+
)
|
|
26
|
+
parser.add_argument("source", help="path to the Python file to obfuscate")
|
|
27
|
+
parser.add_argument("-o", "--output", help="write the result here instead of stdout")
|
|
28
|
+
parser.add_argument("--strategy", default="sequential")
|
|
29
|
+
parser.add_argument("--seed", type=int, default=0)
|
|
30
|
+
parser.add_argument("--prefix", default="_0x")
|
|
31
|
+
parser.add_argument("--no-minify", action="store_true")
|
|
32
|
+
parser.add_argument("--builtins", action="store_true")
|
|
33
|
+
parser.add_argument("--hide-init", action="store_true")
|
|
34
|
+
parser.add_argument("--strip-docstrings", action="store_true")
|
|
35
|
+
return parser.parse_args(argv)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main(argv=None) -> int:
|
|
39
|
+
args = parse_args(argv)
|
|
40
|
+
original = open(args.source).read()
|
|
41
|
+
|
|
42
|
+
result = process(
|
|
43
|
+
original,
|
|
44
|
+
filename=args.source,
|
|
45
|
+
config=None,
|
|
46
|
+
strategy=args.strategy,
|
|
47
|
+
seed=args.seed,
|
|
48
|
+
prefix=args.prefix,
|
|
49
|
+
minify=not args.no_minify,
|
|
50
|
+
builtins=args.builtins,
|
|
51
|
+
hide_init=args.hide_init,
|
|
52
|
+
strip_docstrings=args.strip_docstrings,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
before = run_source(original, args.source)
|
|
56
|
+
after = run_source(result.source, args.source)
|
|
57
|
+
status = "identical" if before == after else "DIFFERENT"
|
|
58
|
+
|
|
59
|
+
print(
|
|
60
|
+
f"symbols={result.stats.symbols} attributes={result.stats.attributes} "
|
|
61
|
+
f"builtins={result.stats.builtins} "
|
|
62
|
+
f"size {result.stats.input_size} -> {result.stats.output_size} "
|
|
63
|
+
f"behaviour={status}",
|
|
64
|
+
file=sys.stderr,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
if args.output:
|
|
68
|
+
with open(args.output, "w") as fh:
|
|
69
|
+
fh.write(result.source)
|
|
70
|
+
print(f"wrote {args.output}", file=sys.stderr)
|
|
71
|
+
else:
|
|
72
|
+
sys.stdout.write(result.source)
|
|
73
|
+
|
|
74
|
+
return 0 if before == after else 1
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
if __name__ == "__main__":
|
|
78
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
RATES = {"usd": 1.0, "eur": 0.92, "inr": 83.1}
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Money:
|
|
7
|
+
|
|
8
|
+
def __init__(self, amount, currency="usd"):
|
|
9
|
+
self.amount = amount
|
|
10
|
+
self.currency = currency
|
|
11
|
+
|
|
12
|
+
def convert(self, target):
|
|
13
|
+
base = self.amount * RATES[self.currency]
|
|
14
|
+
return Money(base / RATES[target], currency=target)
|
|
15
|
+
|
|
16
|
+
def __repr__(self):
|
|
17
|
+
return f"{self.amount:.2f} {self.currency.upper()}"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def total(prices, *, discount=0.0):
|
|
21
|
+
running = 0.0
|
|
22
|
+
for price in prices:
|
|
23
|
+
running += price.amount
|
|
24
|
+
return running * (1 - discount)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def describe(wallet):
|
|
28
|
+
cheapest = min(wallet, key=lambda money: money.amount)
|
|
29
|
+
return f"{len(wallet)} items, cheapest {cheapest!r}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main():
|
|
33
|
+
wallet = [Money(10), Money(20).convert("eur"), Money(5, "inr")]
|
|
34
|
+
print(describe(wallet))
|
|
35
|
+
print(total(wallet, discount=0.1))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
main()
|