├── .cvsignore ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README ├── TODO ├── pyobfuscate ├── pyobfuscate-install ├── pyobfuscate.cmd ├── pyobfuscate.py ├── setup.cfg ├── setup.py └── test ├── generated ├── .gitempty └── package │ └── .gitempty ├── global_lib.py ├── run_tests ├── test_args.py ├── test_classes.py ├── test_default_encodings.py ├── test_fstring.py ├── test_globals.py ├── test_lambda.py ├── test_latin9_declarations.py ├── test_literals.py ├── test_locals.py ├── test_nonlocals.py ├── test_pyobfuscate.py ├── test_utf8_declarations.py └── testfiles ├── .cvsignore ├── allpublic.py ├── allpublic_hidden.py ├── bug1583.py ├── bug1673.py ├── commblanks.py ├── defafteruse.py ├── dyn_all.py ├── global.py ├── import.py ├── importall_star.py ├── importpackage.py ├── importpackage_as.py ├── keywordclass.py ├── keywordclassuser.py ├── keywordfunc.py ├── lambda_global.py ├── package ├── .cvsignore ├── __init__.py └── tobeimported.py ├── power.py ├── tobeimported.py ├── tobeimported_everything.py └── tobeimported_noall.py /.cvsignore: -------------------------------------------------------------------------------- 1 | MANIFEST 2 | build 3 | dist 4 | pyobfuscate.spec 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include pyobfuscate MANIFEST.in pyobfuscate.spec LICENSE Makefile README TODO 2 | include pyobfuscate.cmd pyobfuscate.py 3 | 4 | global-exclude *~ *.pyo *.pyc .cvsignore 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | 3 | .PHONY: dist default all install rpm 4 | 5 | default: 6 | 7 | 8 | install: 9 | ./setup.py install 10 | 11 | rpm: 12 | ./setup.py bdist_rpm 13 | 14 | dist: 15 | # We distribute a .spec file, so that it's possible to run "rpm -ta pyobfuscate.tgz" 16 | ./setup.py bdist_rpm --spec-only 17 | mv dist/pyobfuscate.spec . 18 | ./setup.py sdist --formats=gztar,zip 19 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | 2 | pyobfuscate - Python source code obfuscator 3 | =========================================== 4 | 5 | pyobfuscate is a source code obfuscator: It makes Python source code 6 | hard to read for humans, while still being executable for the Python 7 | interpreter. 8 | 9 | 10 | Why obfuscate? 11 | -------------- 12 | 13 | Obfuscation makes little sense for Open Source 14 | (http://www.opensource.org/) programs, but vendors developing 15 | commercial applications are usually not happy with shipping the 16 | original source code to customers. 17 | 18 | Several obfuscators for other languages, like Java, already 19 | exists. With Python, the problem is even more severe than with Java, 20 | because Python bytecode is not compatible between different Python 21 | versions. Also, bytecode is very easy to "decompile" to source code by 22 | using "decompyle": http://www.crazy-compilers.com/decompyle/. 23 | 24 | If shipping original source code is the only option for distributing 25 | Python applications, then many vendors might choose another 26 | programming language instead. 27 | 28 | 29 | What does pyobfuscate do? 30 | ------------------------- 31 | 32 | pyobfuscate transforms the source code in several ways. Some of these 33 | transformations are reversible (can be "un-obfuscated"); some are 34 | not. Here's a list of what pyobfuscate currently does: 35 | 36 | * Removes comments and docstrings (not reversible) 37 | 38 | * Changes indentation (reversible) 39 | 40 | * Adds whitespace between tokens (somewhat reversible) 41 | 42 | * Renames functions, classes and variables (not reversible) 43 | 44 | * Inserts bogus lines instead of blank lines. 45 | 46 | 47 | Limitations 48 | ----------- 49 | 50 | pyobfuscate operates on one single source file at a time. It does not 51 | obfuscate the interface between several files. 52 | 53 | pyobfuscate cannot obfuscate methods, class variables or other 54 | attributes, currently. See the TODO for more information. 55 | 56 | 57 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | 2 | * Write testcases! 3 | 4 | 5 | * The documentation for the --seed argument says default is to use 6 | system time, but in reality, a fixed number is used. 7 | 8 | 9 | * Obfuscate strings, by using \x sequences. 10 | 11 | 12 | * Obfuscate attributes and methods. The fundamental problem is that 13 | when referencing attributes/methods (with obj.attr or obj.meth), we 14 | do not know the type of obj. The Bicycle Repair Man project has some 15 | type detection code, which might be useful. 16 | 17 | 18 | * Replace all "import foo" with "import foo as somethingobfuscated". 19 | 20 | 21 | * Do not put noop-lines before from __future__ imports. 22 | 23 | 24 | * Make noop-lines even more unreadable by introducing variables in the 25 | "if" expression, and possible let multiple adjacent noop-lines form 26 | a single if-statement. 27 | -------------------------------------------------------------------------------- /pyobfuscate: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*-mode: python; coding: utf-8 -*- 3 | # 4 | # pyobfuscate - Python source code obfuscator 5 | # 6 | # Copyright 2004-2007 Peter Astrand for Cendio AB 7 | # Copyright 2020-2021 Pierre Ossman for Cendio AB 8 | # 9 | # This program is free software; you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation; version 2 of the License. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program; if not, write to the Free Software 20 | # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 21 | 22 | import io 23 | import sys 24 | import token 25 | import keyword 26 | import tokenize 27 | import ast 28 | import random 29 | import symtable 30 | import io 31 | import getopt 32 | import string 33 | 34 | # Python 3.9+ is needed for ast to fully replace parser, so ignore these 35 | # deprecation warnings for now 36 | 37 | import warnings 38 | with warnings.catch_warnings(): 39 | warnings.filterwarnings("ignore", category=DeprecationWarning) 40 | import symbol 41 | import parser 42 | 43 | TOKENBLANKS=1 44 | 45 | def get_source_encoding(source): 46 | ''' Use tokenize to get the files encoding declaration ''' 47 | f = io.BytesIO(source) 48 | tok = tokenize.tokenize(f.readline) 49 | t_type, t_string, t_srow_scol, t_erow_ecol, t_line = next(tok) 50 | 51 | assert t_type == tokenize.ENCODING 52 | return t_string 53 | 54 | 55 | class FStringReplacer: 56 | "Convert f-string statements" 57 | def __init__(self, source): 58 | osf = io.BytesIO(source) 59 | result = [] 60 | last_was_fstring = False 61 | for tok in tokenize.tokenize(osf.readline): 62 | if tok.type == tokenize.STRING and tok.string.startswith("f"): 63 | if last_was_fstring: 64 | new_string = "+" 65 | else: 66 | new_string = "" 67 | last_was_fstring = True 68 | formatter = string.Formatter() 69 | fcount = 0 70 | expressions = [] 71 | for literal_text, field_name, format_spec, conversion in formatter.parse(tok.string[1:]): 72 | new_string += literal_text.replace("{", "{{").replace("}", "}}") 73 | if field_name is not None: 74 | expressions.append(field_name) 75 | new_string += '{' + f"{fcount}" 76 | fcount += 1 77 | if conversion is not None: 78 | new_string += "!" + conversion 79 | if format_spec: 80 | new_string += ":" + format_spec 81 | new_string += '}' 82 | 83 | expressions = ",".join(expressions) 84 | new_string += f".format({expressions})" 85 | result.append((tok.type, new_string, tok.start, tok.end, tok.line)) 86 | elif tok.type == tokenize.NL: 87 | result.append(tok) 88 | else: 89 | last_was_fstring = False 90 | result.append(tok) 91 | self.source = tokenize.untokenize(result) 92 | 93 | 94 | class NameTranslator: 95 | def __init__(self): 96 | self.realnames = {} 97 | self.bogusnames = [] 98 | 99 | 100 | def get_name(self, name): 101 | """Get a translation for a real name""" 102 | if name not in self.realnames: 103 | self.realnames[name] = self.gen_unique_name() 104 | return self.realnames[name] 105 | 106 | 107 | def get_bogus_name(self,): 108 | """Get a random bogus name""" 109 | if len(self.bogusnames) < 20: 110 | newname = self.gen_unique_name() 111 | self.bogusnames.append(newname) 112 | return newname 113 | else: 114 | return random.choice(self.bogusnames) 115 | 116 | 117 | def gen_unique_name(self): 118 | """Generate a name that hasn't been used before; 119 | not as a real name, not as a bogus name""" 120 | existing_names = list(self.realnames.values()) + self.bogusnames 121 | name = "" 122 | while True: 123 | name += self.gen_name() 124 | if name not in existing_names: 125 | break 126 | return name 127 | 128 | 129 | def gen_name(): 130 | if random.choice((True, False)): 131 | # Type ilII1ili1Ilil1il1Ilili1 132 | chars = ("i", "I", "1") 133 | else: 134 | # Type oooOo0oOo00oOO0o0O0 135 | chars = ("o", "O", "0") 136 | 137 | # Name must'nt begin with a number 138 | result = random.choice(chars[:2]) 139 | for x in range(random.randint(1, 12)): 140 | result += random.choice(chars) 141 | return result 142 | gen_name = staticmethod(gen_name) 143 | 144 | 145 | 146 | class LambdaSymTable: 147 | def __init__(self, symtabs, argnames): 148 | # Well, lambdas have no name, so they are safe to obfuscate... 149 | self.symtabs = symtabs 150 | self.mysymbs = {} 151 | for argname in argnames: 152 | self.mysymbs[argname] = symtable.Symbol(argname, symtable.DEF_PARAM) 153 | 154 | 155 | def lookup(self, name): 156 | lsymb = self.mysymbs.get(name) 157 | if lsymb: 158 | return lsymb 159 | else: 160 | # If the symbol is not found in the current sumboltable, 161 | # then look in the toplevel symtable. Perhaps we should 162 | # even look in all symtabs. 163 | try: 164 | return self.symtabs[-1].lookup(name) 165 | except KeyError: 166 | return self.symtabs[0].lookup(name) 167 | 168 | 169 | def get_type(self): 170 | return self.symtabs[-1].get_type() 171 | 172 | 173 | def is_lambda_arg(self, id): 174 | return id in self.mysymbs 175 | 176 | 177 | class CSTWalker: 178 | def __init__(self, source, pubapi): 179 | encoding = get_source_encoding(source) 180 | # Our public API (__all__) 181 | self.pubapi = pubapi 182 | # Names of imported modules 183 | self.modnames = [] 184 | self.symtab = symtable.symtable(source.decode(encoding), "-", "exec") 185 | cst = parser.suite(source.decode(encoding)) 186 | elements = parser.st2tuple(cst, line_info=1) 187 | self.names = {} 188 | self.walk(elements, [self.symtab]) 189 | 190 | 191 | 192 | def getNames(self): 193 | return self.names 194 | 195 | 196 | def addToNames(self, line, name, doreplace): 197 | namedict = self.names.get(line, {}) 198 | if not namedict: 199 | self.names[line] = namedict 200 | 201 | occurancelist = namedict.get(name, []) 202 | if not occurancelist: 203 | namedict[name] = occurancelist 204 | 205 | occurancelist.append(doreplace) 206 | 207 | 208 | def res_name(self, name): 209 | if name.startswith("__") and name.endswith("__"): 210 | return 1 211 | if name in self.modnames: 212 | return 1 213 | if hasattr(__builtins__, name): 214 | return 1 215 | return 0 216 | 217 | 218 | def walk(self, elements, symtabs): 219 | # We are not interested in terminal tokens 220 | if not isinstance(elements, tuple): 221 | return 222 | if token.ISTERMINAL(elements[0]): 223 | return 224 | 225 | production = elements[0] 226 | if production == symbol.funcdef: 227 | self.handle_funcdef(elements, symtabs) 228 | elif production == symbol.typedargslist: 229 | self.handle_typedargslist(elements, symtabs) 230 | elif production == symbol.varargslist: 231 | self.handle_varargslist(elements, symtabs) 232 | elif production == symbol.import_as_name: 233 | self.handle_import_as_name(elements, symtabs) 234 | elif production == symbol.dotted_as_name: 235 | self.handle_dotted_as_name(elements, symtabs) 236 | elif production == symbol.dotted_name: 237 | self.handle_dotted_name(elements, symtabs) 238 | elif production == symbol.global_stmt: 239 | self.handle_global_stmt(elements, symtabs) 240 | elif production == symbol.nonlocal_stmt: 241 | self.handle_nonlocal_stmt(elements, symtabs) 242 | elif production == symbol.atom: 243 | self.handle_atom(elements, symtabs) 244 | elif production == symbol.trailer: 245 | self.handle_trailer(elements, symtabs) 246 | elif production == symbol.classdef: 247 | self.handle_classdef(elements, symtabs) 248 | elif production == symbol.argument: 249 | self.handle_argument(elements, symtabs) 250 | elif production == symbol.lambdef: 251 | self.handle_lambdef(elements, symtabs) 252 | elif production == symbol.except_clause: 253 | self.handle_except_clause(elements, symtabs) 254 | else: 255 | for node in elements: 256 | self.walk(node, symtabs) 257 | 258 | 259 | def mangle_name(self, symtabs, name): 260 | if self.res_name(name): 261 | return name 262 | 263 | if not name.startswith("__"): 264 | return name 265 | 266 | for i in range(len(symtabs)): 267 | tab = symtabs[-1 - i] 268 | tabtype = tab.get_type() 269 | if tabtype == "class": 270 | classname = tab.get_name().lstrip("_") 271 | return "_" + classname + name 272 | 273 | return name 274 | 275 | def should_obfuscate(self, id, symtabs): 276 | # This is the primary location of the magic in pyobfuscate, 277 | # where we try to figure out if a given symbol should be 278 | # obfuscated or left alone. 279 | 280 | tab = symtabs[-1] 281 | 282 | # Don't touch reserved names 283 | if self.res_name(id): 284 | return False 285 | 286 | # Need to get the internal symbol name before we can look it 287 | # up (needed for private class/object members) 288 | orig_id = id 289 | id = self.mangle_name(symtabs, id) 290 | try: 291 | s = tab.lookup(id) 292 | except Exception: 293 | return False 294 | 295 | # XXX: Debug code 296 | # Add the symbols you want to examine to this list 297 | debug_symbols = [] 298 | if id in debug_symbols: 299 | print("%s:" % id, file=sys.stderr) 300 | print(" Imported:", s.is_imported(), file=sys.stderr) 301 | print(" Parameter:", s.is_parameter(), file=sys.stderr) 302 | print(" Global:", s.is_global(), file=sys.stderr) 303 | print(" Nonlocal:", s.is_nonlocal(), file=sys.stderr) 304 | print(" Local:", s.is_local(), file=sys.stderr) 305 | 306 | # Explicit imports are a clear no 307 | if s.is_imported(): 308 | return False 309 | 310 | # Don't obfuscate arguments as the caller might be external 311 | # and referencing them by name 312 | if s.is_parameter(): 313 | # But we assume that lambda arguments are never referenced 314 | # by name. FIXME? 315 | if isinstance(tab, LambdaSymTable): 316 | if tab.is_lambda_arg(id): 317 | return True 318 | 319 | return False 320 | 321 | # Lambda scopes have some kind of pseudo-inheritance from 322 | # the surounding scope. As lambdas can only declare arguments 323 | # (which we just handled), we should start digging upwards for 324 | # all other symbols. 325 | if isinstance(tab, LambdaSymTable): 326 | while True: 327 | symtabs = symtabs[:-1] 328 | if symtabs == []: 329 | raise RuntimeError("Lambda symbol '%s' is not present on any scope" % id) 330 | 331 | if id in symtabs[-1].get_identifiers(): 332 | return self.should_obfuscate(orig_id, symtabs) 333 | 334 | # Global objects require special consideration. Need to figure 335 | # out where the symbol originated... 336 | if s.is_global(): 337 | topsymtab = symtabs[0] 338 | 339 | # A global that's not in the global symbol table is a symbol 340 | # that Python has no idea where it comes from (it is only 341 | # "read" in every context in the module). That means either 342 | # buggy code, or that it got dragged in via "import *". Assume 343 | # the latter and don't obfuscate it. 344 | if id not in topsymtab.get_identifiers(): 345 | return False 346 | 347 | topsym = topsymtab.lookup(id) 348 | 349 | # XXX: See above: 350 | if id in debug_symbols: 351 | print(" Imported (G):", topsym.is_imported(), file=sys.stderr) 352 | print(" Parameter (G):", topsym.is_parameter(), file=sys.stderr) 353 | print(" Global (G):", topsym.is_global(), file=sys.stderr) 354 | print(" Local (G):", topsym.is_local(), file=sys.stderr) 355 | 356 | # Explicit imports are a clear no 357 | if topsym.is_imported(): 358 | return False 359 | 360 | # "Local" really means "written to", or "declared". So a 361 | # global that is not "local" in the global symbol table is 362 | # something that was created in another scope. This can happen 363 | # in two cases: 364 | # 365 | # a) Imported via * 366 | # 367 | # b) Created via "global foo" inside a function 368 | # 369 | # We want to obfuscate b), but not a). But we cannot tell which 370 | # is which, so just leave both alone. 371 | if not topsym.is_local(): 372 | # Symbol.is_local is currently broken upstream: 373 | # https://bugs.python.org/issue41840 374 | from _symtable import DEF_BOUND 375 | if not (topsym._Symbol__flags & DEF_BOUND): 376 | return False 377 | 378 | # This is something we declared, so obfuscate unless it is 379 | # part of the module API. 380 | return id not in self.pubapi 381 | 382 | # If it's not global, nor local, then it must come from a 383 | # containing scope (e.g. function inside another function). 384 | if not s.is_local(): 385 | # Any more scopes to try? 386 | if len(symtabs) <= 2: 387 | raise RuntimeError("Symbol '%s' is not present on any scope" % id) 388 | return self.should_obfuscate(orig_id, symtabs[:-1]) 389 | 390 | # Local symbols are handled differently depending on what 391 | # our current scope is. 392 | tabtype = tab.get_type() 393 | if tabtype == "module": 394 | # Toplevel. Check with pubapi. 395 | return id not in self.pubapi 396 | elif tabtype == "function": 397 | # Function/method. Always OK. 398 | return True 399 | elif tabtype == "class": 400 | # This is a class method/variable (or, perhaps, a class in a class) 401 | # FIXME: We cannot obfuscate methods right now, 402 | # because we cannot handle calls like obj.meth(), 403 | # since we do not know the type of obj. 404 | return False 405 | else: 406 | raise RuntimeError("Unknown scope '%s' for symbol '%s'" % (tabtype, id)) 407 | 408 | def handle_funcdef(self, elements, symtabs): 409 | # funcdef: 'def' NAME parameters ':' suite 410 | # elements is something like: 411 | # (259, (1, 'def', 6), (1, 'f', 6), (260, ... 412 | name = elements[2] 413 | assert name[0] == token.NAME 414 | id = name[1] 415 | line = name[2] 416 | obfuscate = self.should_obfuscate(id, symtabs) 417 | 418 | self.addToNames(line, id, obfuscate) 419 | 420 | tab = symtabs[-1] 421 | 422 | orig_id = id 423 | id = self.mangle_name(symtabs, id) 424 | 425 | functabs = tab.lookup(id).get_namespaces() 426 | 427 | # Mangled names mess up the association with the symbol table, so 428 | # we need to find it manually 429 | if len(functabs) == 0: 430 | functabs = [] 431 | for child in tab.get_children(): 432 | if child.get_name() == orig_id: 433 | functabs.append(child) 434 | 435 | for node in elements: 436 | self.walk(node, symtabs + functabs) 437 | 438 | def handle_typedargslist(self, elements, symtabs): 439 | # typedargslist: (tfpdef ['=' test] (',' [TYPE_COMMENT] tfpdef ['=' test])* ... 440 | 441 | # FIXME: should handle type comments? 442 | 443 | self.handle_varargslist(elements, symtabs) 444 | 445 | def handle_varargslist(self, elements, symtabs): 446 | # varargslist: vfpdef ['=' test ](',' vfpdef ['=' test])* ... 447 | # elements is something like: 448 | # (261, (262, (1, 'XXX', 37)), (12, ',', 37), (262, (1, 'bar', 38)), (22, '=', 38), (292, (293, (294, 449 | # The purpose of this method is to find vararg and kwarg names 450 | # (which are not vfpdefs). 451 | tab = symtabs[-1] 452 | 453 | for tok in elements: 454 | if not isinstance(tok, tuple): 455 | continue 456 | 457 | toktype = tok[0] 458 | if toktype == symbol.test: 459 | # This is a "= test" expression 460 | for node in tok: 461 | # The [:-1] is because we actually are not in the 462 | # functions scope yet. 463 | self.walk(node, symtabs[:-1]) 464 | elif toktype == symbol.tfpdef: 465 | self.handle_tfpdef(tok, symtabs) 466 | elif toktype == symbol.vfpdef: 467 | self.handle_vfpdef(tok, symtabs) 468 | else: 469 | assert(toktype in [token.STAR, token.DOUBLESTAR, 470 | token.COMMA, token.EQUAL]) 471 | 472 | def handle_tfpdef(self, elements, symtabs): 473 | # tfpdef: NAME [':' test] 474 | 475 | # Just ignore the type part 476 | self.handle_vfpdef(elements, symtabs) 477 | 478 | def handle_vfpdef(self, elements, symtabs): 479 | # vfpdef: NAME 480 | # elements is something like: 481 | # (262, (1, 'self', 13)) 482 | name = elements[1] 483 | assert name[0] == token.NAME 484 | id = name[1] 485 | line = name[2] 486 | obfuscate = self.should_obfuscate(id, symtabs) 487 | self.addToNames(line, id, obfuscate) 488 | 489 | 490 | def handle_import_as_name(self, elements, symtabs): 491 | # import_as_name: NAME [NAME NAME] 492 | # elements is something like: 493 | # (279, (1, 'format_tb', 11)) 494 | # or 495 | # (279, (1, 'format_tb', 11), (1, 'as', 11), (1, 'ftb', 11)) 496 | name1 = elements[1] 497 | assert name1[0] == token.NAME 498 | id1 = name1[1] 499 | line1 = name1[2] 500 | self.addToNames(line1, id1, 0) 501 | 502 | if len(elements) > 2: 503 | assert len(elements) == 4 504 | 505 | name2 = elements[2] 506 | assert name2[0] == token.NAME 507 | id2 = name2[1] 508 | assert id2 == "as" 509 | line2 = name2[2] 510 | self.addToNames(line2, id2, 0) 511 | 512 | name3 = elements[3] 513 | assert name3[0] == token.NAME 514 | id3 = name3[1] 515 | line3 = name3[2] 516 | # FIXME: Later, obfuscate if scope/pubabi etc OK 517 | self.addToNames(line3, id3, 0) 518 | self.modnames.append(id3) 519 | 520 | for node in elements: 521 | self.walk(node, symtabs) 522 | 523 | 524 | def handle_dotted_as_name(self, elements, symtabs): 525 | # dotted_as_name: dotted_name [NAME NAME] 526 | # elements is something like: 527 | # (280, (281, (1, 'os', 2))) 528 | # or 529 | # (280, (281, (1, 'traceback', 11)), (1, 'as', 11), (1, 'tb', 11)) 530 | # handle_dotted_name takes care of dotted_name 531 | dotted_name = elements[1] 532 | 533 | modname = dotted_name[1] 534 | assert modname[0] == token.NAME 535 | mod_id = modname[1] 536 | mod_line = modname[2] 537 | self.addToNames(mod_line, mod_id, 0) 538 | self.modnames.append(mod_id) 539 | 540 | if len(elements) > 2: 541 | # import foo as bar ... 542 | assert len(elements) == 4 543 | 544 | asname = elements[2] 545 | assert asname[0] == token.NAME 546 | asid = asname[1] 547 | assert asid == "as" 548 | asline = asname[2] 549 | self.addToNames(asline, asid, 0) 550 | 551 | name = elements[3] 552 | assert name[0] == token.NAME 553 | id = name[1] 554 | line = name[2] 555 | # FIXME: Later, obfuscate if scope/pubabi etc OK 556 | self.addToNames(line, id, 0) 557 | self.modnames.append(id) 558 | 559 | for node in elements: 560 | self.walk(node, symtabs) 561 | 562 | 563 | def handle_dotted_name(self, elements, symtabs): 564 | # dotted_name: NAME ('.' NAME)* 565 | # elements is something like: 566 | # (281, (1, 'os', 2)) 567 | # or 568 | # (281, (1, 'compiler', 11), (23, '.', 11), (1, 'ast', 11)) 569 | # or 570 | # (281, (1, 'bike', 11), (23, '.', 11), (1, 'bikefacade', 11), (23, '.', 11), (1, 'visitor', 11)) 571 | name = elements[1] 572 | assert name[0] == token.NAME 573 | id = name[1] 574 | line = name[2] 575 | obfuscate = self.should_obfuscate(id, symtabs) 576 | self.addToNames(line, id, obfuscate) 577 | 578 | # Sequence length should be even 579 | assert (len(elements) % 2 == 0) 580 | for x in range(2, len(elements), 2): 581 | dot = elements[x] 582 | name = elements[x+1] 583 | 584 | assert dot[0] == token.DOT 585 | assert name[0] == token.NAME 586 | id = name[1] 587 | line = name[2] 588 | self.addToNames(line, id, 0) 589 | for node in elements: 590 | self.walk(node, symtabs) 591 | 592 | 593 | def handle_global_stmt(self, elements, symtabs): 594 | # global_stmt: 'global' NAME (',' NAME)* 595 | # elements is something like: 596 | # (282, (1, 'global', 41), (1, 'foo', 41)) 597 | # or 598 | # (282, (1, 'global', 32), (1, 'aaaa', 32), (12, ',', 32), (1, 'bbbb', 32)) 599 | gname = elements[1] 600 | assert gname[0] == token.NAME 601 | gid = gname[1] 602 | assert gid == "global" 603 | 604 | name1 = elements[2] 605 | assert name1[0] == token.NAME 606 | id1 = name1[1] 607 | line1 = name1[2] 608 | obfuscate = self.should_obfuscate(id1, symtabs) 609 | self.addToNames(line1, id1, obfuscate) 610 | 611 | # Sequence length should be odd 612 | assert (len(elements) % 2) 613 | for x in range(3, len(elements), 2): 614 | comma = elements[x] 615 | name = elements[x+1] 616 | assert comma[0] == token.COMMA 617 | assert name[0] == token.NAME 618 | id = name[1] 619 | line = name[2] 620 | obfuscate = id not in self.pubapi 621 | self.addToNames(line, id, obfuscate) 622 | for node in elements: 623 | self.walk(node, symtabs) 624 | 625 | 626 | def handle_nonlocal_stmt(self, elements, symtabs): 627 | # nonlocal_stmt: 'nonlocal' NAME (',' NAME)* 628 | # elements is something like: 629 | # (293, (1, 'nonlocal', 41), (1, 'foo', 41)) 630 | # or 631 | # (293, (1, 'nonlocal', 32), (1, 'aaaa', 32), (12, ',', 32), (1, 'bbbb', 32)) 632 | nlname = elements[1] 633 | assert nlname[0] == token.NAME 634 | nlid = nlname[1] 635 | assert nlid == "nonlocal" 636 | 637 | name1 = elements[2] 638 | assert name1[0] == token.NAME 639 | id1 = name1[1] 640 | line1 = name1[2] 641 | obfuscate = self.should_obfuscate(id1, symtabs) 642 | self.addToNames(line1, id1, obfuscate) 643 | 644 | # Sequence length should be odd 645 | assert (len(elements) % 2) 646 | for x in range(3, len(elements), 2): 647 | comma = elements[x] 648 | name = elements[x+1] 649 | assert comma[0] == token.COMMA 650 | assert name[0] == token.NAME 651 | id = name[1] 652 | line = name[2] 653 | obfuscate = id not in self.pubapi 654 | self.addToNames(line, id, obfuscate) 655 | for node in elements: 656 | self.walk(node, symtabs) 657 | 658 | 659 | def handle_atom(self, elements, symtabs): 660 | # atom: ... | NAME | ... 661 | # elements is something like: 662 | # (305, (1, 'os', 15)) 663 | name = elements[1] 664 | if name[0] == token.NAME: 665 | id = name[1] 666 | line = name[2] 667 | obfuscate = self.should_obfuscate(id, symtabs) 668 | 669 | self.addToNames(line, id, obfuscate) 670 | 671 | for node in elements: 672 | self.walk(node, symtabs) 673 | 674 | 675 | def handle_trailer(self, elements, symtabs): 676 | # trailer: ... | '.' NAME 677 | # elements is something like: 678 | # (308, (23, '.', 33), (1, 'poll', 33)) 679 | trailer = elements[1] 680 | if trailer[0] == token.DOT: 681 | name = elements[2] 682 | assert name[0] == token.NAME 683 | id = name[1] 684 | line = name[2] 685 | # Cannot obfuscate these as we have no idea what the base 686 | # object is. 687 | self.addToNames(line, id, 0) 688 | for node in elements: 689 | self.walk(node, symtabs) 690 | 691 | 692 | def handle_classdef(self, elements, symtabs): 693 | # classdef: 'class' NAME ['(' arglist ')'] ':' suite 694 | # elements is something like: 695 | # (316, (1, 'class', 48), (1, 'SuperMyClass', 48), (11, ':', 48), 696 | name = elements[2] 697 | assert name[0] == token.NAME 698 | id = name[1] 699 | line = name[2] 700 | obfuscate = self.should_obfuscate(id, symtabs) 701 | 702 | self.addToNames(line, id, obfuscate) 703 | 704 | aftername = elements[3] 705 | aftername2 = elements[4] 706 | # Should be either a colon or left paren 707 | assert aftername[0] in (token.COLON, token.LPAR) 708 | if aftername[0] == token.LPAR and aftername2[0] != token.RPAR: 709 | # This class is inherited 710 | arglist = elements[4] 711 | assert arglist[0] == symbol.arglist 712 | # Parsing of arglist should be done in the original scope 713 | for node in arglist: 714 | self.walk(node, symtabs) 715 | elements = elements[5:] 716 | 717 | tab = symtabs[-1] 718 | classtab = tab.lookup(id).get_namespace() 719 | 720 | for node in elements: 721 | self.walk(node, symtabs + [classtab]) 722 | 723 | 724 | def handle_argument(self, elements, symtabs): 725 | # argument: [test '='] test # Really [keyword '='] test 726 | # elements is like: 727 | # (318, (292, (293, (294, (295, (297, (298, (299, (300, (301, 728 | # (302, (303, (304, (305, (3, '"SC_OPEN_MAX"', 15 729 | 730 | # Keyword argument? 731 | if len(elements) >= 4: 732 | # keyword=test 733 | 734 | # Because test is used we need do dig down until we find 735 | # the final NAME 736 | keyword = elements[1] 737 | while len(keyword) == 2: 738 | keyword = keyword[1] 739 | 740 | assert keyword[0] == token.NAME 741 | keyword_id = keyword[1] 742 | keyword_line = keyword[2] 743 | 744 | # Argument names have to be in the clear as we cannot track all 745 | # callers. See should_obfuscate(). 746 | self.addToNames(keyword_line, keyword_id, False) 747 | 748 | # Let the obfuscator continue handling the value 749 | elements = elements[3] 750 | 751 | for node in elements: 752 | self.walk(node, symtabs) 753 | 754 | 755 | def handle_lambdef(self, elements, symtabs): 756 | # lambdef: 'lambda' [varargslist] ':' test 757 | # elements is like: 758 | # (307, (1, 'lambda', 588), (261, (262, (1, 'e', 588))), (11, ':', 588) 759 | # or 760 | # (307, (1, 'lambda', 40), (11, ':', 40), (292 ... 761 | if elements[2][0] == token.COLON: 762 | # There are no lambda arguments. Simple! 763 | # We still need to create a LambdaSymTable though since we 764 | # rely on some magic lookup that it does. 765 | test = elements[3] 766 | lambdatab = LambdaSymTable(symtabs, []) 767 | for node in test: 768 | self.walk(node, symtabs + [lambdatab]) 769 | else: 770 | # The more common case: You have a varargslist. 771 | varargslist = elements[2] 772 | 773 | # Part 1: Deal with varargslist. Fetch the names of the 774 | # arguments. Construct a LambdaSymTable. 775 | arguments = self.get_varargs_names(varargslist) 776 | for line, name in arguments: 777 | self.addToNames(line, name, 1) 778 | 779 | argnames = [e[1] for e in arguments] 780 | lambdatab = LambdaSymTable(symtabs, argnames) 781 | 782 | # Part 2: Parse the 'test' part, using the LambdaSymTable. 783 | test = elements[4] 784 | for node in test: 785 | self.walk(node, symtabs + [lambdatab]) 786 | 787 | def handle_except_clause(self, elements, symtabs): 788 | # except_clause: 'except' [test ['as' NAME]] 789 | 790 | # Has "as" part? 791 | if len(elements) == 5: 792 | name = elements[4] 793 | assert name[0] == token.NAME 794 | id = name[1] 795 | line = name[2] 796 | 797 | obfuscate = self.should_obfuscate(id, symtabs) 798 | self.addToNames(line, id, obfuscate) 799 | 800 | for node in elements: 801 | self.walk(node, symtabs) 802 | 803 | @staticmethod 804 | def get_varargs_names(elements): 805 | """Extract all argument names and lines from varargslist""" 806 | result = [] 807 | 808 | for tok in elements: 809 | if not isinstance(tok, tuple): 810 | continue 811 | 812 | toktype = tok[0] 813 | if toktype == symbol.vfpdef: 814 | name = tok[1] 815 | assert name[0] == token.NAME 816 | id = name[1] 817 | line = name[2] 818 | result.append((line, id)) 819 | else: 820 | assert(toktype in [symbol.test, 821 | token.STAR, token.DOUBLESTAR, 822 | token.COMMA, token.EQUAL]) 823 | 824 | return result 825 | 826 | 827 | class PubApiExtractor(ast.NodeVisitor): 828 | def __init__(self, source): 829 | root = ast.parse(source) 830 | self.pubapi = None 831 | self.matches = 0 832 | self.visit(root) 833 | if self.pubapi == None: 834 | # Didn't find __all__. 835 | if conf.allpublic: 836 | encoding = get_source_encoding(source) 837 | symtab = symtable.symtable(source.decode(encoding), "-", "exec") 838 | self.pubapi = [s for s in symtab.get_identifiers() if s[0] != "_"] 839 | else: 840 | self.pubapi = [] 841 | 842 | if self.matches > 1: 843 | print("Warning: Found multiple __all__ definitions", file=sys.stderr) 844 | print("Using last definition", file=sys.stderr) 845 | 846 | 847 | def visit_Assign(self, node): 848 | for assnode in node.targets: 849 | if not isinstance(assnode, ast.Name): 850 | continue 851 | 852 | if assnode.id == "__all__": 853 | self.matches += 1 854 | self.pubapi = [] 855 | # Verify that the expression is a list 856 | constant = isinstance(node.value, ast.List) 857 | if constant: 858 | # Verify that each element in list is a constant 859 | # string node 860 | for node in node.value.elts: 861 | if (isinstance(node, ast.Constant) and 862 | isinstance(node.value, str)): 863 | self.pubapi.append(node.value) 864 | elif isinstance(node, ast.Str): 865 | self.pubapi.append(node.s) 866 | else: 867 | constant = False 868 | break 869 | 870 | if not constant: 871 | print("Error: __all__ is not a list of constants.", file=sys.stderr) 872 | sys.exit(1) 873 | 874 | 875 | 876 | class ColumnExtractor: 877 | def __init__(self, source, names): 878 | 879 | self.indent = 0 880 | self.first_on_line = 1 881 | # How many times have we seen this symbol on this line before? 882 | self.symboltimes = {} 883 | self.names = names 884 | # Dictionary indexed on (row, column), containing name 885 | self.result = {} 886 | # To detect line num changes; backslash constructs doesn't 887 | # generate any token 888 | self.this_lineno = 1 889 | f = io.BytesIO(source) 890 | self.parse(f) 891 | 892 | 893 | def parse(self, f): 894 | for tok in tokenize.tokenize(f.readline): 895 | t_type, t_string, t_srow_scol, t_erow_ecol, t_line = tok 896 | 897 | if t_type == tokenize.ENCODING: 898 | continue 899 | 900 | assert self.this_lineno <= t_srow_scol[0] 901 | if self.this_lineno < t_srow_scol[0]: 902 | # Gosh, line has skipped. This must be due to an 903 | # ending backslash. 904 | self.this_lineno = t_srow_scol[0] 905 | self.symboltimes = {} 906 | 907 | if t_type in [tokenize.NL, tokenize.NEWLINE]: 908 | self.this_lineno += 1 909 | self.symboltimes = {} 910 | elif t_type == tokenize.NAME: 911 | # Make life easier on us by ignoring keywords 912 | if keyword.iskeyword(t_string): 913 | continue 914 | 915 | srow = t_srow_scol[0] 916 | scol = t_srow_scol[1] 917 | 918 | namedict = self.names.get(srow) 919 | if not namedict: 920 | raise RuntimeError("Overlooked symbol '%s' on line %d column %d" % (t_string, srow, scol)) 921 | 922 | occurancelist = namedict.get(t_string) 923 | if not occurancelist: 924 | raise RuntimeError("Overlooked symbol '%s' on line %d column %d" % (t_string, srow, scol)) 925 | 926 | seen_times = self.saw_symbol(t_string) 927 | if seen_times > len(occurancelist): 928 | raise RuntimeError("Overlooked symbol '%s' on line %d column %d" % (t_string, srow, scol)) 929 | 930 | if occurancelist[seen_times]: 931 | # This occurance should be obfuscated. 932 | assert self.result.get((srow, scol)) == None 933 | self.result[(srow, scol)] = t_string 934 | 935 | 936 | def saw_symbol(self, name): 937 | """Update self.symboltimes, when we have seen a symbol 938 | Return the current seen_times for this symbol""" 939 | seen_times = self.symboltimes.get(name, -1) 940 | seen_times += 1 941 | self.symboltimes[name] = seen_times 942 | return seen_times 943 | 944 | 945 | 946 | class TokenPrinter: 947 | AFTERCOMMENT = 0 948 | INSIDECOMMENT = 1 949 | BEFORECOMMENT = 2 950 | 951 | def __init__(self, source, names): 952 | self.indent = 0 953 | self.first_on_line = 1 954 | self.symboltimes = {} 955 | self.names = names 956 | self.nametranslator = NameTranslator() 957 | self.encoding = None 958 | # Pending, obfuscated noop lines. We cannot add the noop lines 959 | # until we know what comes after. 960 | self.pending = [] 961 | self.pending_indent = 0 962 | # To detect line num changes; backslash constructs doesn't 963 | # generate any token 964 | self.this_lineno = 1 965 | self.pending_newlines = 0 966 | # Skip next token? 967 | self.skip_token = 0 968 | # Keep track of constructions that can span multiple lines 969 | self.paren_count = 0 970 | self.curly_count = 0 971 | self.square_count = 0 972 | # Comment state. One of AFTERCOMMENT, INSIDECOMMENT, BEFORECOMMENT 973 | if conf.firstcomment: 974 | self.commentstate = TokenPrinter.AFTERCOMMENT 975 | else: 976 | self.commentstate = TokenPrinter.BEFORECOMMENT 977 | f = io.BytesIO(source) 978 | self.play(f) 979 | 980 | 981 | def play(self, f): 982 | for tok in tokenize.tokenize(f.readline): 983 | t_type, t_string, t_srow_scol, t_erow_ecol, t_line = tok 984 | 985 | #print >>sys.stderr, "TTTT", tokenize.tok_name[t_type], repr(t_string), self.this_lineno, t_srow_scol[0] 986 | 987 | if t_type == tokenize.ENCODING: 988 | assert self.encoding == None 989 | self.encoding = t_string 990 | continue 991 | 992 | if t_type == tokenize.OP: 993 | if t_string == "(": 994 | self.paren_count += 1 995 | elif t_string == ")": 996 | self.paren_count -= 1 997 | elif t_string == "{": 998 | self.curly_count += 1 999 | elif t_string == "}": 1000 | self.curly_count -= 1 1001 | elif t_string == "[": 1002 | self.square_count += 1 1003 | elif t_string == "]": 1004 | self.square_count -= 1 1005 | 1006 | assert self.paren_count >= 0 1007 | assert self.curly_count >= 0 1008 | assert self.square_count >= 0 1009 | 1010 | if self.skip_token: 1011 | self.skip_token = 0 1012 | continue 1013 | 1014 | # Make sure we keep line numbers 1015 | # line numbers may not decrease 1016 | assert self.this_lineno <= t_srow_scol[0] 1017 | if self.this_lineno < t_srow_scol[0]: 1018 | # Gosh, line has skipped. This must be due to an 1019 | # ending backslash. 1020 | self.pending_newlines += t_srow_scol[0] - self.this_lineno 1021 | self.this_lineno = t_srow_scol[0] 1022 | 1023 | if t_type in [tokenize.NL, tokenize.NEWLINE]: 1024 | for x in range(self.pending_newlines): 1025 | if conf.blanks != conf.KEEP_BLANKS: 1026 | self.pending.append(self.gen_noop_line() + "\n") 1027 | self.pending_indent = self.indent 1028 | else: 1029 | sys.stdout.buffer.write(b"\n") 1030 | self.pending_newlines = 0 1031 | 1032 | if t_type == tokenize.NL: 1033 | if self.first_on_line and conf.blanks != conf.KEEP_BLANKS: 1034 | self.pending.append(self.gen_noop_line() + "\n") 1035 | self.pending_indent = self.indent 1036 | else: 1037 | sys.stdout.buffer.write(b"\n") 1038 | self.this_lineno += 1 1039 | if self.commentstate == TokenPrinter.INSIDECOMMENT: 1040 | self.commentstate = TokenPrinter.AFTERCOMMENT 1041 | 1042 | elif t_type == tokenize.NEWLINE: 1043 | self.first_on_line = 1 1044 | self.this_lineno += 1 1045 | sys.stdout.buffer.write(b"\n") 1046 | if self.commentstate == TokenPrinter.INSIDECOMMENT: 1047 | self.commentstate = TokenPrinter.AFTERCOMMENT 1048 | 1049 | elif t_type == tokenize.INDENT: 1050 | self.indent += conf.indent 1051 | elif t_type == tokenize.DEDENT: 1052 | self.indent -= conf.indent 1053 | elif t_type == tokenize.COMMENT: 1054 | if self.commentstate == TokenPrinter.BEFORECOMMENT: 1055 | self.commentstate = TokenPrinter.INSIDECOMMENT 1056 | 1057 | if self.first_on_line: 1058 | if self.commentstate in [TokenPrinter.BEFORECOMMENT, TokenPrinter.INSIDECOMMENT]: 1059 | # Output comment 1060 | t_string += "\n" 1061 | self.line_append(t_string) 1062 | elif conf.blanks != conf.KEEP_BLANKS: 1063 | self.pending.append(self.gen_noop_line() + "\n") 1064 | self.pending_indent = self.indent 1065 | else: 1066 | sys.stdout.buffer.write(b"\n") 1067 | 1068 | self.this_lineno += 1 1069 | else: 1070 | sys.stdout.buffer.write(b"\n") 1071 | self.this_lineno += 1 1072 | 1073 | # tokenizer does not generate a NEWLINE after comment 1074 | self.first_on_line = 1 1075 | # tokinizer generates NL after each COMMENT 1076 | self.skip_token = 1 1077 | elif t_type == tokenize.STRING: 1078 | if self.first_on_line: 1079 | # Skip over docstrings, unless this looks like a Swagger interface 1080 | # FIXME: This simple approach fails with: 1081 | # "foo"; print 3 1082 | if self.paren_count > 0 or \ 1083 | self.curly_count > 0 or \ 1084 | self.square_count > 0 or \ 1085 | ("---" in t_string and "description:" in t_string): 1086 | self.line_append(t_string) 1087 | self.this_lineno += t_string.count("\n") 1088 | else: 1089 | self.skip_token = 1 1090 | else: 1091 | self.line_append(t_string) 1092 | self.this_lineno += t_string.count("\n") 1093 | elif t_type == tokenize.NAME: 1094 | (srow, scol) = t_srow_scol 1095 | if self.names.get(t_srow_scol): 1096 | t_string = self.nametranslator.get_name(t_string) 1097 | 1098 | self.line_append(t_string) 1099 | else: 1100 | self.line_append(t_string) 1101 | 1102 | 1103 | def line_append(self, s): 1104 | assert self.encoding != None 1105 | if self.pending: 1106 | indent = max(self.indent, self.pending_indent) 1107 | self.pending = [row.encode(self.encoding) for row in self.pending] 1108 | self.pending = [b" "*indent + row for row in self.pending] 1109 | if conf.blanks == conf.OBFUSCATE_BLANKS: 1110 | sys.stdout.buffer.write(b''.join(self.pending)) 1111 | self.pending = [] 1112 | 1113 | if self.first_on_line: 1114 | sys.stdout.buffer.write(b" "*self.indent) 1115 | else: 1116 | sys.stdout.buffer.write(b" "*TOKENBLANKS) 1117 | 1118 | sys.stdout.buffer.write(s.encode(self.encoding)) 1119 | self.first_on_line = 0 1120 | 1121 | 1122 | def gen_noop_line(self): 1123 | if self.paren_count > 0 or \ 1124 | self.curly_count > 0 or \ 1125 | self.square_count > 0: 1126 | result = "# " 1127 | else: 1128 | testint = random.randint(1, 100) 1129 | result = "if %d - %d: " % (testint, testint) 1130 | num_words = random.randint(1, 6) 1131 | for x in range(num_words - 1): 1132 | op = random.choice((".", "/", "+", "-", "%", "*")) 1133 | result += self.nametranslator.get_bogus_name() + " %s " % op 1134 | result += self.nametranslator.get_bogus_name() 1135 | return result 1136 | 1137 | 1138 | def usage(): 1139 | print(""" 1140 | Usage: 1141 | 1142 | pyobfuscate [options] 1143 | 1144 | Options: 1145 | 1146 | -h, --help Print this help. 1147 | -i, --indent Indentation to use. Default is 1. 1148 | -s, --seed Seed to use for name randomization. Default is 1149 | system time. 1150 | -r, --removeblanks Remove blank lines, instead of obfuscate 1151 | -k, --keepblanks Keep blank lines, instead of obfuscate 1152 | -f, --firstcomment Remove first block of comments as well 1153 | -a, --allpublic When __all__ is missing, assume everything is public. 1154 | The default is to assume nothing is public. 1155 | -v, --verbose Verbose mode. 1156 | """, file=sys.stderr) 1157 | 1158 | 1159 | class Configuration: 1160 | KEEP_BLANKS = 0 1161 | OBFUSCATE_BLANKS = 1 1162 | REMOVE_BLANKS = 2 1163 | 1164 | def __init__(self): 1165 | try: 1166 | opts, args = getopt.getopt(sys.argv[1:], "hi:s:rkfav", 1167 | ["help", "indent=", "seed=", "removeblanks", 1168 | "keepblanks", "firstcomment", "allpublic", 1169 | "verbose"]) 1170 | if len(args) != 1: 1171 | raise getopt.GetoptError("A filename is required", "") 1172 | except getopt.GetoptError as e: 1173 | print("Error:", e, file=sys.stderr) 1174 | usage() 1175 | sys.exit(2) 1176 | 1177 | self.file = args[0] 1178 | self.indent = 1 1179 | self.seed = 42 1180 | self.blanks = self.OBFUSCATE_BLANKS 1181 | self.firstcomment = False 1182 | self.allpublic = False 1183 | self.verbose = False 1184 | 1185 | for o, a in opts: 1186 | if o in ("-h", "--help"): 1187 | usage() 1188 | sys.exit() 1189 | if o in ("-i", "--indent"): 1190 | self.indent = int(a) 1191 | if o in ("-s", "--seed"): 1192 | self.seed = a 1193 | if o in ("-r", "--removeblanks"): 1194 | self.blanks = self.REMOVE_BLANKS 1195 | if o in ("-k", "--keepblanks"): 1196 | self.blanks = self.KEEP_BLANKS 1197 | if o in ("-f", "--firstcomment"): 1198 | self.firstcomment = True 1199 | if o in ("-a", "--allpublic"): 1200 | self.allpublic = True 1201 | if o == ("-v", "--verbose"): 1202 | self.verbose = True 1203 | 1204 | 1205 | 1206 | def main(): 1207 | global conf 1208 | conf = Configuration() 1209 | random.seed(conf.seed) 1210 | source = open(conf.file, mode='rb').read() 1211 | 1212 | # Step 0: Convert f-strings to "".format() 1213 | fsr = FStringReplacer(source) 1214 | source = fsr.source 1215 | 1216 | # Step 1: Extract __all__ from source. 1217 | pae = PubApiExtractor(source) 1218 | 1219 | 1220 | # Step 2: Walk the CST tree. The result of this step is a 1221 | # dictionary indexed on line numbers, which contains dictionaries 1222 | # indexed on symbols, which contains a list of the occurances of 1223 | # this symbol on this line. A 1 in this list means that the 1224 | # occurance should be obfuscated; 0 means not. Example: {64: 1225 | # {'foo': [0, 1], 'run': [0]} 1226 | cw = CSTWalker(source, pae.pubapi) 1227 | 1228 | 1229 | # Step 3: We need those column numbers! Use the tokenize module to 1230 | # step through the source code to gather this information. The 1231 | # result of this step is a dictionary indexed on tuples (row, 1232 | # column), which contains the symbol names. Example: {(55, 6): 1233 | # 'MyClass'} Only symbols that should be replaced are returned. 1234 | # (This step could perhaps be merged with step 4, but there are 1235 | # two reasons for not doing so: 1) Make each step less 1236 | # complicated. 2) If we want to use BRM some day, then we'll need 1237 | # the column numbers.) 1238 | ce = ColumnExtractor(source, cw.names) 1239 | 1240 | 1241 | # Step 4: Play the tokenizer game! Step through the source 1242 | # code. Obfuscate those symbols gathered earlier. Change 1243 | # indentation, blank lines etc. 1244 | TokenPrinter(source, ce.result) 1245 | 1246 | # Step 5: Output a marker that makes it possible to recognize 1247 | # obfuscated files 1248 | print("# dd678faae9ac167bc83abf78e5cb2f3f0688d3a3") 1249 | 1250 | if __name__ == "__main__": 1251 | main() 1252 | 1253 | -------------------------------------------------------------------------------- /pyobfuscate-install: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # pyobfuscate - Python source code obfuscator 3 | # 4 | # Copyright 2004-2007 Peter Astrand for Cendio AB 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; version 2 of the License. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program; if not, write to the Free Software 17 | # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 18 | 19 | 20 | import os, sys 21 | 22 | def get_origin_dir(): 23 | startdir = os.getcwd() 24 | os.chdir(os.path.dirname(sys.argv[0])) 25 | origin = os.getcwd() 26 | os.chdir(startdir) 27 | return origin 28 | 29 | 30 | def usage(): 31 | print(""" 32 | Install and obfuscate a Python file in one step. 33 | 34 | Usage: 35 | pyobfuscate-install [-m ] [pyobfuscate-args] 36 | 37 | """, file=sys.stderr) 38 | sys.exit(1) 39 | 40 | 41 | def main(): 42 | if len(sys.argv) < 2: 43 | usage() 44 | 45 | origin = get_origin_dir() 46 | mode = 0o755 47 | rest = [] 48 | next_is_mode = False 49 | for arg in sys.argv[1:]: 50 | if next_is_mode: 51 | mode = int(arg, 8) 52 | next_is_mode = False 53 | elif arg == "-m": 54 | next_is_mode = True 55 | else: 56 | rest.append(arg) 57 | 58 | source = rest[-2] 59 | dest = rest[-1] 60 | rest = rest[:-2] 61 | 62 | if os.path.isdir(dest): 63 | dest = os.path.join(dest, os.path.basename(source)) 64 | 65 | cmd = [os.path.join(origin, "pyobfuscate")] 66 | cmd.extend(rest) 67 | cmd.extend([source, ">", dest]) 68 | cmd = " ".join(cmd) 69 | print("Calling", cmd, file=sys.stderr) 70 | retcode = os.system(cmd) 71 | os.chmod(dest, mode) 72 | if retcode > 254: 73 | retcode = 254 74 | sys.exit(retcode) 75 | 76 | 77 | if __name__ == "__main__": 78 | main() 79 | 80 | -------------------------------------------------------------------------------- /pyobfuscate.cmd: -------------------------------------------------------------------------------- 1 | @echo off 2 | rem 3 | rem Windows wrapper for Python scripts. Allows you to invoke a Python 4 | rem script as "myscript" instead of "myscript.py". 5 | rem Author: Peter Astrand 6 | rem 7 | %~dpn0.py %* 8 | -------------------------------------------------------------------------------- /pyobfuscate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Execute the file with the same name as myself minus the extension. 4 | # Author: Peter Astrand 5 | # 6 | import os, sys 7 | root, ext = os.path.splitext(sys.argv[0]) 8 | exec(compile(open(root, "rb").read(), root, 'exec')) 9 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | 2 | [bdist_rpm] 3 | doc_files = README TODO 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | DESCRIPTION = """\ 4 | Python source code obfuscator 5 | """ 6 | 7 | from distutils.core import setup 8 | 9 | setup (name = "pyobfuscate", 10 | version = "0.3", 11 | license = "GPL", 12 | description = "pyobfuscate", 13 | long_description = DESCRIPTION, 14 | author = "Peter Astrand", 15 | author_email = "astrand@cendio.se", 16 | url = "http://www.lysator.liu.se/~astrand/projects/pyobfuscate/", 17 | scripts = [ 'pyobfuscate', 'pyobfuscate-install' ] 18 | ) 19 | -------------------------------------------------------------------------------- /test/generated/.gitempty: -------------------------------------------------------------------------------- 1 | Stupid git. 2 | -------------------------------------------------------------------------------- /test/generated/package/.gitempty: -------------------------------------------------------------------------------- 1 | Stupid git. 2 | -------------------------------------------------------------------------------- /test/global_lib.py: -------------------------------------------------------------------------------- 1 | # Library for the globals test 2 | 3 | external_global_top = "a" 4 | external_global_ro = "b" 5 | external_global_rw = "c" 6 | 7 | -------------------------------------------------------------------------------- /test/run_tests: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd `dirname "$0"` 4 | 5 | # Obfuscate the obfuscator as a torture test 6 | 7 | ../pyobfuscate ../pyobfuscate > pyobfuscate 8 | chmod u+x pyobfuscate 9 | 10 | for fn in test_*.py; do 11 | echo 12 | echo "@@ $fn @@" 13 | echo 14 | # Piping source code with a different encoding compared to the 15 | # terminal doesn't work with older versions of Python. We can 16 | # bypass this if we first write to a file. 17 | ./pyobfuscate $fn > tmp_testfile 18 | python3 tmp_testfile 19 | rm tmp_testfile 20 | done 21 | -------------------------------------------------------------------------------- /test/test_args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | def function_none(): 6 | pass 7 | 8 | def function_args(a, b, c): 9 | assert a == 1 10 | assert b == 2 11 | assert c == 3 12 | assert "a" in locals() 13 | assert "b" in locals() 14 | assert "c" in locals() 15 | 16 | def function_default(expected, arg=12): 17 | assert expected == arg 18 | assert "expected" in locals() 19 | assert "arg" in locals() 20 | 21 | def function_posargs(*args): 22 | # FIXME: args could be obfuscated in theory, but the obfuscator is 23 | # currently unable. 24 | #assert "args" not in locals() 25 | pass 26 | 27 | def function_kwargs(**kwargs): 28 | # FIXME: Dito 29 | #assert "kwargs" not in locals() 30 | pass 31 | 32 | class FunctionArgumentTest(unittest.TestCase): 33 | def test_none(self): 34 | function_none() 35 | 36 | def test_pos(self): 37 | function_args(1, 2, 3) 38 | 39 | def test_named(self): 40 | function_args(c=3, b=2, a=1) 41 | 42 | def test_default(self): 43 | function_default(12) 44 | 45 | def test_default_pos(self): 46 | function_default(13, 13) 47 | 48 | def test_default_named(self): 49 | function_default(13, arg=13) 50 | 51 | def test_posargs(self): 52 | function_posargs() 53 | function_posargs(1, 2, 3) 54 | 55 | def test_kwargs(self): 56 | function_kwargs() 57 | function_kwargs(a=1, b=2, c=3) 58 | 59 | class Dummy: 60 | def method_none(self): 61 | pass 62 | 63 | def method_args(self, a, b, c): 64 | assert a == 1 65 | assert b == 2 66 | assert c == 3 67 | assert "a" in locals() 68 | assert "b" in locals() 69 | assert "c" in locals() 70 | 71 | def method_default(self, expected, arg=12): 72 | assert expected == arg 73 | assert "expected" in locals() 74 | assert "arg" in locals() 75 | 76 | class MethodArgumentTest(unittest.TestCase): 77 | def test_none(self): 78 | obj = Dummy() 79 | obj.method_none() 80 | 81 | def test_pos(self): 82 | obj = Dummy() 83 | obj.method_args(1, 2, 3) 84 | 85 | def test_named(self): 86 | obj = Dummy() 87 | obj.method_args(c=3, b=2, a=1) 88 | 89 | def test_default(self): 90 | obj = Dummy() 91 | obj.method_default(12) 92 | 93 | def test_default_pos(self): 94 | obj = Dummy() 95 | obj.method_default(13, 13) 96 | 97 | def test_default_named(self): 98 | obj = Dummy() 99 | obj.method_default(13, arg=13) 100 | 101 | if "__main__" == __name__: 102 | unittest.main() 103 | -------------------------------------------------------------------------------- /test/test_classes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | __all__ = ["GlobalClass"] 6 | 7 | class LocalClass: 8 | def method_a(): 9 | pass 10 | 11 | class GlobalClass: 12 | def method_b(): 13 | pass 14 | 15 | class OuterNestedClass: 16 | class InnerNestedClass: 17 | pass 18 | 19 | def nested_function(test): 20 | class InnerNestedClass: 21 | pass 22 | test.assertFalse("InnerNestedClass" in locals()) 23 | 24 | # This crashed the obfuscator at one point 25 | class EmptyAncestors(): 26 | pass 27 | 28 | class LocalAncestor(LocalClass): 29 | pass 30 | 31 | class GlocalAncestor(GlobalClass): 32 | pass 33 | 34 | class MixedAncestors(LocalClass, GlobalClass): 35 | pass 36 | 37 | class PrivateMethods: 38 | def __hidden_method(self, a, b): 39 | c = a + b 40 | return c 41 | 42 | def public_method(self, a, b): 43 | return self.__hidden_method(a, b) 44 | 45 | class ClassTest(unittest.TestCase): 46 | def test_local(self): 47 | self.assertFalse("LocalClass" in globals()) 48 | 49 | def test_local_method(self): 50 | obj = LocalClass() 51 | # Method names should not be obfuscated as we don't 52 | # know what the object is until runtime 53 | self.assertTrue(hasattr(obj, "method_a")) 54 | 55 | def test_global(self): 56 | self.assertTrue("GlobalClass" in globals()) 57 | 58 | def test_global_method(self): 59 | obj = GlobalClass() 60 | # See test_local_method() 61 | self.assertTrue(hasattr(obj, "method_b")) 62 | 63 | def test_nested_class(self): 64 | self.assertFalse("OuterNestedClass" in globals()) 65 | self.assertTrue(hasattr(OuterNestedClass, "InnerNestedClass")) 66 | 67 | def test_nested_function(self): 68 | nested_function(self) 69 | 70 | def test_local_ancestor(self): 71 | self.assertFalse("LocalClass" in globals()) 72 | self.assertFalse("LocalAncestor" in globals()) 73 | self.assertTrue(issubclass(LocalAncestor, LocalClass)) 74 | 75 | def test_global_ancestor(self): 76 | self.assertTrue("GlobalClass" in globals()) 77 | self.assertFalse("GlocalAncestor" in globals()) 78 | self.assertTrue(issubclass(GlocalAncestor, GlobalClass)) 79 | 80 | def test_mixed_ancestors(self): 81 | self.assertFalse("LocalClass" in globals()) 82 | self.assertTrue("GlobalClass" in globals()) 83 | self.assertFalse("MixedAncestors" in globals()) 84 | self.assertTrue(issubclass(MixedAncestors, LocalClass)) 85 | self.assertTrue(issubclass(MixedAncestors, GlobalClass)) 86 | 87 | def test_private_method(self): 88 | self.assertFalse("PrivateMethods" in globals()) 89 | obj = PrivateMethods() 90 | self.assertEqual(obj.public_method(4, 5), 9) 91 | 92 | if "__main__" == __name__: 93 | unittest.main() 94 | -------------------------------------------------------------------------------- /test/test_default_encodings.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # No encoding given here, will use Python 3 default (utf-8) 3 | import unittest 4 | 5 | class SourceCodeDefaultEncodingTest(unittest.TestCase): 6 | def test_default_encoding(self): 7 | symbol = "€" 8 | codepoint = "\u20ac" 9 | self.assertEqual(symbol, codepoint) 10 | 11 | if "__main__" == __name__: 12 | unittest.main() -------------------------------------------------------------------------------- /test/test_fstring.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | import unittest 5 | 6 | globalval = 999 7 | 8 | class C: 9 | foo = 42 10 | pass 11 | c = C() 12 | 13 | multiline = f""" 14 | param1={globalval} 15 | param2={c.foo} 16 | """ 17 | 18 | class FStringTest(unittest.TestCase): 19 | def test_strings(self): 20 | value = 17 21 | self.assertEqual(f"{value*value}", "289") 22 | self.assertEqual(f"{value!s}", "17") 23 | self.assertEqual(f"{value:4}", " 17") 24 | self.assertEqual(f"{globalval}dollars", "999dollars") 25 | self.assertTrue(f"{sys.version}".startswith("3.")) 26 | self.assertEqual(multiline, """ 27 | param1=999 28 | param2=42 29 | """) 30 | 31 | self.assertEqual(f"a {value} " 32 | f"b {globalval} ", "a 17 b 999 ") 33 | self.assertEqual(f"{{ {value} }}", "{ 17 }") 34 | 35 | 36 | if "__main__" == __name__: 37 | unittest.main() 38 | -------------------------------------------------------------------------------- /test/test_globals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | # Locally defined global variable should be obfuscated 6 | local_global = 1 7 | 8 | # Check that referenced are properly followed 9 | local_reffed_global = 2 10 | 11 | def check_func_ref(self): 12 | var = local_reffed_global 13 | self.assertFalse("var" in locals()) 14 | self.assertEqual(var, 2) 15 | 16 | def check_func_write(val): 17 | global local_reffed_global 18 | local_reffed_global = val 19 | 20 | # Locally defined globals can be missing on the module scope 21 | # Unfortunately we don't know if this variable is only declared here, 22 | # or if it also comes via a * import. The obfuscator assumes the worst 23 | # and lets it remain in the clear. 24 | def check_func_define(self): 25 | global hidden_local_global 26 | hidden_local_global = 3 27 | self.assertFalse("hidden_local_global" in locals()) 28 | self.assertTrue("hidden_local_global" in globals()) 29 | 30 | # Multiple global references at once 31 | local_global_a = 4 32 | local_global_b = 5 33 | 34 | def check_func_multi_write(a, b): 35 | global local_global_a, local_global_b 36 | local_global_a = a 37 | local_global_b = b 38 | 39 | class LocalGlobalTest(unittest.TestCase): 40 | def test_simple(self): 41 | self.assertFalse("local_global" in globals()) 42 | 43 | def test_reffed(self): 44 | self.assertFalse("local_reffed_global" in globals()) 45 | 46 | def test_func_ref(self): 47 | check_func_ref(self) 48 | 49 | def check_method_ref(self): 50 | var = local_reffed_global 51 | self.assertFalse("var" in locals()) 52 | self.assertEqual(var, 2) 53 | 54 | def test_method_ref(self): 55 | self.check_method_ref() 56 | 57 | def test_func_write(self): 58 | check_func_write('x') 59 | self.assertEqual(local_reffed_global, 'x') 60 | check_func_write(2) 61 | self.assertEqual(local_reffed_global, 2) 62 | 63 | def check_method_write(self, val): 64 | global local_reffed_global 65 | local_reffed_global = val 66 | 67 | def test_method_write(self): 68 | self.check_method_write('x') 69 | self.assertEqual(local_reffed_global, 'x') 70 | self.check_method_write(2) 71 | self.assertEqual(local_reffed_global, 2) 72 | 73 | def test_func_define(self): 74 | check_func_define(self) 75 | self.assertEqual(hidden_local_global, 3) 76 | 77 | def test_multi(self): 78 | self.assertFalse("local_global_a" in globals()) 79 | self.assertFalse("local_global_b" in globals()) 80 | 81 | def test_func_multi_write(self): 82 | check_func_multi_write('y', 'z') 83 | self.assertEqual(local_global_a, 'y') 84 | self.assertEqual(local_global_b, 'z') 85 | check_func_multi_write(4, 5) 86 | self.assertEqual(local_global_a, 4) 87 | self.assertEqual(local_global_b, 5) 88 | 89 | def check_method_multi_write(self, a, b): 90 | global local_global_a, local_global_b 91 | local_global_a = a 92 | local_global_b = b 93 | 94 | def test_method_multi_write(self): 95 | self.check_method_multi_write('y', 'z') 96 | self.assertEqual(local_global_a, 'y') 97 | self.assertEqual(local_global_b, 'z') 98 | self.check_method_multi_write(4, 5) 99 | self.assertEqual(local_global_a, 4) 100 | self.assertEqual(local_global_b, 5) 101 | 102 | # Check that external references do not get obfuscated 103 | from global_lib import * 104 | 105 | # Local copies should still get obfuscated though 106 | local_copy = external_global_top 107 | 108 | def check_func_external_ref(self): 109 | var = external_global_ro 110 | self.assertFalse("var" in locals()) 111 | self.assertEqual(var, "b") 112 | 113 | def check_func_external_write(val): 114 | global external_global_rw 115 | external_global_rw = val 116 | 117 | class ExternalGlobalTest(unittest.TestCase): 118 | def test_name(self): 119 | self.assertTrue("external_global_top" in globals()) 120 | self.assertTrue("external_global_ro" in globals()) 121 | self.assertTrue("external_global_rw" in globals()) 122 | 123 | def test_copy(self): 124 | self.assertFalse("local_copy" in globals()) 125 | 126 | def test_func_ref(self): 127 | check_func_external_ref(self) 128 | 129 | def check_method_ref(self): 130 | var = external_global_ro 131 | self.assertFalse("var" in locals()) 132 | self.assertEqual(var, "b") 133 | 134 | def test_method_ref(self): 135 | self.check_method_ref() 136 | 137 | def test_func_write(self): 138 | check_func_external_write('x') 139 | self.assertEqual(external_global_rw, 'x') 140 | check_func_external_write("c") 141 | self.assertEqual(external_global_rw, "c") 142 | 143 | def check_method_write(self, val): 144 | global external_global_rw 145 | external_global_rw = val 146 | 147 | def test_method_write(self): 148 | self.check_method_write('x') 149 | self.assertEqual(external_global_rw, 'x') 150 | self.check_method_write("c") 151 | self.assertEqual(external_global_rw, "c") 152 | 153 | if "__main__" == __name__: 154 | unittest.main() 155 | -------------------------------------------------------------------------------- /test/test_lambda.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | __all__ = ["public_global"] 6 | 7 | private_global = 1 8 | public_global = 2 9 | 10 | def arg_func(arg): 11 | f = lambda : arg 12 | return f() 13 | 14 | class LambdaTest(unittest.TestCase): 15 | def test_simple(self): 16 | f = lambda: True 17 | self.assertTrue(f()) 18 | 19 | def test_arg(self): 20 | f = lambda b: b 21 | self.assertTrue(f(True)) 22 | 23 | def test_local(self): 24 | var = 3 25 | f = lambda : var 26 | self.assertTrue(f() == 3) 27 | 28 | def test_local_arg(self): 29 | self.assertTrue(arg_func(4) == 4) 30 | 31 | def test_private_global(self): 32 | self.assertFalse("private_global" in globals()) 33 | f = lambda : private_global 34 | self.assertTrue(f() == 1) 35 | 36 | def test_public_global(self): 37 | self.assertTrue("public_global" in globals()) 38 | f = lambda : public_global 39 | self.assertTrue(f() == 2) 40 | 41 | if "__main__" == __name__: 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /test/test_latin9_declarations.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/astrand/pyobfuscate/34f5f6505c338ec34cd8653579235545c5c1c9ac/test/test_latin9_declarations.py -------------------------------------------------------------------------------- /test/test_literals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | # Check that multi line literals don't get destroyed. 6 | # 7 | # Bug 1: Line starting with a string was assumed to be a doc string 8 | # 9 | dictionary = { 10 | 'key1': (12, 'foobar', None, 11 | "another string", 44, 12 | "foo", 13 | None), 14 | 'key2': (12, 'foobar', None, 15 | "another string", 44, 16 | "foo", 17 | None) 18 | } 19 | 20 | class LiteralTest(unittest.TestCase): 21 | def test_dictionary(self): 22 | self.assertTrue("key1" in list(dictionary.keys())) 23 | self.assertTrue("key2" in list(dictionary.keys())) 24 | self.assertEqual(dictionary["key1"][5], "foo") 25 | self.assertEqual(dictionary["key2"][5], "foo") 26 | 27 | if "__main__" == __name__: 28 | unittest.main() 29 | -------------------------------------------------------------------------------- /test/test_locals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | __all__ = ["public_variable"] 6 | 7 | def function_write(test): 8 | just_write = 1 9 | test.assertFalse("just_write" in locals()) 10 | 11 | def function_read_write(test): 12 | read_write = 2 13 | if read_write: 14 | pass 15 | test.assertFalse("read_write" in locals()) 16 | 17 | def function_public(test): 18 | # A different variable mentioned in __all__ shouldn't 19 | # prevent obfuscation 20 | public_variable = 3 21 | test.assertFalse("public_variable" in locals()) 22 | 23 | def function_nested(test): 24 | # Nested function definitions makes the scope handling really 25 | # confusing 26 | def nested(test): 27 | test.assertTrue(var == 12) 28 | var = 12 29 | test.assertFalse("var" in locals()) 30 | test.assertFalse("nested" in locals()) 31 | nested(test) 32 | 33 | def function_double_nested(test): 34 | def nested_a(test): 35 | def nested_b(test): 36 | test.assertTrue(var == 666) 37 | test.assertFalse("nested_b" in locals()) 38 | var = 666 39 | test.assertFalse("var" in locals()) 40 | test.assertFalse("nested_a" in locals()) 41 | nested_a(test) 42 | 43 | class FunctionTest(unittest.TestCase): 44 | def test_just_write(self): 45 | function_write(self) 46 | 47 | def test_read_write(self): 48 | function_read_write(self) 49 | 50 | def test_public(self): 51 | function_public(self) 52 | 53 | def test_nested(self): 54 | function_nested(self) 55 | 56 | def test_double_nested(self): 57 | function_double_nested(self) 58 | 59 | class Dummy: 60 | def method_write(self, test): 61 | just_write = 1 62 | test.assertFalse("just_write" in locals()) 63 | 64 | def method_read_write(self, test): 65 | read_write = 2 66 | if read_write: 67 | pass 68 | test.assertFalse("read_write" in locals()) 69 | 70 | def method_public(self, test): 71 | # A different variable mentioned in __all__ shouldn't 72 | # prevent obfuscation 73 | public_variable = 3 74 | test.assertFalse("public_variable" in locals()) 75 | 76 | class MethodTest(unittest.TestCase): 77 | def test_just_write(self): 78 | obj = Dummy() 79 | obj.method_write(self) 80 | 81 | def test_read_write(self): 82 | obj = Dummy() 83 | obj.method_read_write(self) 84 | 85 | def test_public(self): 86 | obj = Dummy() 87 | obj.method_public(self) 88 | 89 | if "__main__" == __name__: 90 | unittest.main() 91 | -------------------------------------------------------------------------------- /test/test_nonlocals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | 5 | # Note: read-only non-local bindings are tested in test_locals.py 6 | 7 | def check_func(self): 8 | def nested(self, val): 9 | nonlocal var 10 | var = val 11 | var = 1 12 | self.assertFalse("var" in locals()) 13 | self.assertFalse("nested" in locals()) 14 | nested(self, 'x') 15 | self.assertEqual(var, 'x') 16 | nested(self, 2) 17 | self.assertEqual(var, 2) 18 | 19 | def check_func_double(self): 20 | def nested_a(self, val): 21 | var2 = 2 22 | def nested_b(self, val1, val2): 23 | nonlocal var1 24 | nonlocal var2 25 | var1 = val1 26 | var2 = val2 27 | self.assertFalse("var2" in locals()) 28 | self.assertFalse("nested_b" in locals()) 29 | nested_b(self, 'x', 'y') 30 | self.assertEqual(var1, 'x') 31 | self.assertEqual(var2, 'y') 32 | nested_b(self, 3, 4) 33 | self.assertEqual(var1, 3) 34 | self.assertEqual(var2, 4) 35 | nested_b(self, val, val) 36 | var1 = 1 37 | self.assertFalse("var1" in locals()) 38 | self.assertFalse("nested_a" in locals()) 39 | nested_a(self, 'z') 40 | self.assertEqual(var1, 'z') 41 | nested_a(self, 5) 42 | self.assertEqual(var1, 5) 43 | 44 | def check_func_multi(self): 45 | def nested(self, val1, val2): 46 | nonlocal var1, var2 47 | var1 = val1 48 | var2 = val2 49 | var1 = 1 50 | var2 = 2 51 | self.assertFalse("var1" in locals()) 52 | self.assertFalse("var2" in locals()) 53 | self.assertFalse("nested" in locals()) 54 | nested(self, 'x', 'y') 55 | self.assertEqual(var1, 'x') 56 | self.assertEqual(var2, 'y') 57 | nested(self, 3, 4) 58 | self.assertEqual(var1, 3) 59 | self.assertEqual(var2, 4) 60 | 61 | class NonlocalTest(unittest.TestCase): 62 | def test_func(self): 63 | check_func(self) 64 | 65 | def test_method(self): 66 | def nested(self, val): 67 | nonlocal var 68 | var = val 69 | var = 1 70 | self.assertFalse("var" in locals()) 71 | self.assertFalse("nested" in locals()) 72 | nested(self, 'x') 73 | self.assertEqual(var, 'x') 74 | nested(self, 2) 75 | self.assertEqual(var, 2) 76 | 77 | def test_func_double(self): 78 | check_func_double(self) 79 | 80 | def test_method_double(self): 81 | def nested_a(self, val): 82 | var2 = 2 83 | def nested_b(self, val1, val2): 84 | nonlocal var1 85 | nonlocal var2 86 | var1 = val1 87 | var2 = val2 88 | self.assertFalse("var2" in locals()) 89 | self.assertFalse("nested_b" in locals()) 90 | nested_b(self, 'x', 'y') 91 | self.assertEqual(var1, 'x') 92 | self.assertEqual(var2, 'y') 93 | nested_b(self, 3, 4) 94 | self.assertEqual(var1, 3) 95 | self.assertEqual(var2, 4) 96 | nested_b(self, val, val) 97 | var1 = 1 98 | self.assertFalse("var1" in locals()) 99 | self.assertFalse("nested_a" in locals()) 100 | nested_a(self, 'z') 101 | self.assertEqual(var1, 'z') 102 | nested_a(self, 5) 103 | self.assertEqual(var1, 5) 104 | 105 | def test_func_multi(self): 106 | check_func_multi(self) 107 | 108 | def test_method_multi(self): 109 | def nested(self, val1, val2): 110 | nonlocal var1, var2 111 | var1 = val1 112 | var2 = val2 113 | var1 = 1 114 | var2 = 2 115 | self.assertFalse("var1" in locals()) 116 | self.assertFalse("var2" in locals()) 117 | self.assertFalse("nested" in locals()) 118 | nested(self, 'x', 'y') 119 | self.assertEqual(var1, 'x') 120 | self.assertEqual(var2, 'y') 121 | nested(self, 3, 4) 122 | self.assertEqual(var1, 3) 123 | self.assertEqual(var2, 4) 124 | 125 | if "__main__" == __name__: 126 | unittest.main() 127 | -------------------------------------------------------------------------------- /test/test_pyobfuscate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import unittest 4 | import sys 5 | sys.path = ["/opt/thinlinc/modules"] + sys.path 6 | import subprocess 7 | import re 8 | import os 9 | import tempfile 10 | 11 | class ObfuscateTest(unittest.TestCase): 12 | def mkstemp(self): 13 | """wrapper for mkstemp, calling mktemp if mkstemp is not available""" 14 | if hasattr(tempfile, "mkstemp"): 15 | return tempfile.mkstemp() 16 | else: 17 | fname = tempfile.mktemp() 18 | return os.open(fname, os.O_RDWR|os.O_CREAT), fname 19 | 20 | def run_pyobfuscate(self, testfile, args=[]): 21 | cmdline = ["../pyobfuscate"] + args + [testfile] 22 | p = subprocess.Popen(cmdline, 23 | stdout=subprocess.PIPE, 24 | stderr=subprocess.PIPE) 25 | (stdout, stderr) = p.communicate() 26 | assert b'' == stderr, "pyobfuscate wrote to stderr: %s" % stderr 27 | return stdout.decode() 28 | 29 | def obfuscate_and_write(self, testfile, outfile, args=[]): 30 | with open(outfile, 'w') as f: 31 | f.write(self.run_pyobfuscate(testfile, args)) 32 | 33 | def run_src(self, src): 34 | f, fname = self.mkstemp() 35 | os.write(f, src.encode()) 36 | os.close(f) 37 | retcode = subprocess.call([sys.executable, fname]) 38 | os.remove(fname) 39 | return retcode 40 | 41 | def obfuscate_and_run_file(self, testfile, args=[]): 42 | output = self.run_pyobfuscate(testfile, args) 43 | return self.run_src(output) 44 | 45 | def obfuscate_and_run_src(self, src, args=[]): 46 | f, fname = self.mkstemp() 47 | os.write(f, src) 48 | os.close(f) 49 | retcode = self.obfuscate_and_run_file(fname, args) 50 | os.remove(fname) 51 | return retcode 52 | 53 | def test_DontKeepblanks(self): 54 | """Don't keep blanks unless told so""" 55 | output = self.run_pyobfuscate("testfiles/commblanks.py") 56 | assert None == re.search(output, "^$"), "Blank lines in output" 57 | lines = output.split("\n") 58 | assert "#" == lines[0][0], "First line is not a comment" 59 | assert 42 == self.run_src(output) 60 | 61 | def test_Keepblanks(self): 62 | """Keep blanks when told so""" 63 | output = self.run_pyobfuscate("testfiles/commblanks.py", 64 | args=["--keepblanks"]) 65 | lines = output.split("\n") 66 | assert '' == lines[5], "Blank lines removed" 67 | assert 42 == self.run_src(output) 68 | 69 | def test_lambdaGlobal(self): 70 | """Support lambda constructs referencing global functions. 71 | Test inspired by log message for revision 1.15""" 72 | assert 42 == self.obfuscate_and_run_file("testfiles/lambda_global.py"), "Incorrect value returned after obfuscation" 73 | 74 | def test_power(self): 75 | """Handle power operator correctly. Bug 1411""" 76 | assert 4 == self.obfuscate_and_run_file("testfiles/power.py"), "Incorrect value returned after obfuscation" 77 | 78 | def test_keywordfunc(self): 79 | """Handle keyword functions correctly. 80 | Test inspired by revision 1.8 and revision 1.9""" 81 | assert 42 == self.obfuscate_and_run_file("testfiles/keywordfunc.py"), "Incorrect value returned after obfuscation" 82 | 83 | def test_importlist(self): 84 | """Handle from import """ 85 | self.obfuscate_and_write("testfiles/tobeimported.py", 86 | "generated/tobeimported.py") 87 | self.obfuscate_and_write("testfiles/import.py", 88 | "generated/import.py") 89 | assert 42 == subprocess.call([sys.executable, "generated/import.py"]), "Incorrect value returned after obfuscation" 90 | 91 | def test_import_package(self): 92 | """Handle from x.y import z""" 93 | self.obfuscate_and_write("testfiles/package/tobeimported.py", 94 | "generated/package/tobeimported.py") 95 | self.obfuscate_and_write("testfiles/package/__init__.py", 96 | "generated/package/__init__.py") 97 | 98 | self.obfuscate_and_write("testfiles/importpackage.py", 99 | "generated/importpackage.py") 100 | assert 42 == subprocess.call([sys.executable, 101 | "generated/importpackage.py"], 102 | env={"PYTHONPATH":"generated"}), "Incorrect value returned after obfuscation" 103 | 104 | def test_import_package_as(self): 105 | """Handle from x.y import z as a""" 106 | self.obfuscate_and_write("testfiles/package/tobeimported.py", 107 | "generated/package/tobeimported.py") 108 | self.obfuscate_and_write("testfiles/package/__init__.py", 109 | "generated/package/__init__.py") 110 | 111 | self.obfuscate_and_write("testfiles/importpackage_as.py", 112 | "generated/importpackage_as.py") 113 | assert 42 == subprocess.call([sys.executable, 114 | "generated/importpackage_as.py"], 115 | env={"PYTHONPATH":"generated"}), "Incorrect value returned after obfuscation" 116 | 117 | def test_import_everything(self): 118 | self.obfuscate_and_write("testfiles/tobeimported_everything.py", 119 | "generated/tobeimported_everything.py") 120 | self.obfuscate_and_write("testfiles/importall_star.py", 121 | "generated/importall_star.py") 122 | assert 42 == subprocess.call([sys.executable, "generated/importall_star.py"]), "Incorrect value returned after obfuscation" 123 | 124 | def test_import_dyn_all(self): 125 | """Verify that trying to import from a file with dynamic __all__ fails""" 126 | cmdline = ["../pyobfuscate", "testfiles/dyn_all.py"] 127 | p = subprocess.Popen(cmdline, 128 | stdout=subprocess.PIPE, 129 | stderr=subprocess.PIPE) 130 | (stdout, stderr) = p.communicate() 131 | assert -1 != stderr.find(b"__all__ is not a list of constants"), "pyobufscate didn't bail out with an error on file with dynamic __all__" 132 | 133 | def test_import_with_keywords(self): 134 | """Verify that an imported class, defined in __all__, does not get obfuscated keyword arguments""" 135 | self.obfuscate_and_write("testfiles/keywordclass.py", 136 | "generated/keywordclass.py") 137 | self.obfuscate_and_write("testfiles/keywordclassuser.py", 138 | "generated/keywordclassuser.py") 139 | assert 42 == subprocess.call([sys.executable, "generated/keywordclassuser.py"]), "Incorrect value returned after obfuscation" 140 | 141 | def test_global_stmt(self): 142 | """Verify use of 'global' keyword""" 143 | assert 42 == self.obfuscate_and_run_file("testfiles/global.py"), "Incorrect value returned after obfuscation" 144 | 145 | def test_definition_after_use(self): 146 | """Verify that a function defined after it's used works as expected""" 147 | output = self.run_pyobfuscate("testfiles/defafteruse.py") 148 | assert 42 == self.run_src(output), "Incorrect value returned after obfuscation" 149 | 150 | def test_bug1583(self): 151 | """Verify that bug 1583 is not present (lambda obfuscation problems)""" 152 | output = self.run_pyobfuscate("testfiles/bug1583.py") 153 | assert 42 == self.run_src(output), "Incorrect value returned after obfuscation" 154 | 155 | def test_bug1673(self): 156 | """Verify that bug 1673 is not present (global variable handling)""" 157 | output = self.run_pyobfuscate("testfiles/bug1673.py") 158 | assert 49 == self.run_src(output), "Incorrect value returned after obfuscation" 159 | 160 | def test_allpublic(self): 161 | """ Verify that we respect the --allpublic flag but still keep 162 | functions starting with '_' hidden """ 163 | self.obfuscate_and_write("testfiles/tobeimported_noall.py", 164 | "generated/tobeimported_noall.py", 165 | args=["--allpublic"]) 166 | self.obfuscate_and_write("testfiles/allpublic.py", 167 | "generated/allpublic.py") 168 | 169 | res = subprocess.call([sys.executable, "generated/allpublic.py"]) 170 | 171 | assert 1 == res, "Incorrect value returned after obfuscation" 172 | 173 | def test_allpublic_hidden(self): 174 | """ Verify that we still keep functions starting with '_' hidden """ 175 | self.obfuscate_and_write("testfiles/tobeimported_noall.py", 176 | "generated/tobeimported_noall.py", 177 | args=["--allpublic"]) 178 | self.obfuscate_and_write("testfiles/allpublic_hidden.py", 179 | "generated/allpublic_hidden.py") 180 | 181 | res = subprocess.call([sys.executable, "generated/allpublic_hidden.py"]) 182 | 183 | assert 1 == res, "Incorrect value returned after obfuscation" 184 | 185 | 186 | if "__main__" == __name__: 187 | unittest.main() 188 | -------------------------------------------------------------------------------- /test/test_utf8_declarations.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import unittest 4 | 5 | class SourceCodeEncodingDeclarationTest(unittest.TestCase): 6 | def test_default_encoding(self): 7 | symbol = "€" 8 | codepoint = "\u20ac" 9 | self.assertEqual(symbol, codepoint) 10 | 11 | if "__main__" == __name__: 12 | unittest.main() -------------------------------------------------------------------------------- /test/testfiles/.cvsignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /test/testfiles/allpublic.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import tobeimported_noall 4 | 5 | if (tobeimported_noall.one() + tobeimported_noall.two()) != 3: 6 | sys.exit(-1) 7 | 8 | sys.exit(1) -------------------------------------------------------------------------------- /test/testfiles/allpublic_hidden.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import tobeimported_noall 4 | 5 | try: 6 | tobeimported_noall._hidden() 7 | except AttributeError: 8 | sys.exit(1) 9 | 10 | sys.exit(-1) -------------------------------------------------------------------------------- /test/testfiles/bug1583.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | def foo(bar): 5 | return sum([x+bar for x in [1, 2, 3]]) 6 | 7 | sys.exit(2*foo(5)) 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/testfiles/bug1673.py: -------------------------------------------------------------------------------- 1 | __all__ = ["gvar", "colliding"] 2 | import sys 3 | gvar = 47 4 | def foo(): 5 | global gvar 6 | gvar += 2 7 | colliding = 33 8 | assert 0 == ("colliding" in locals()) 9 | return gvar 10 | sys.exit(foo()) 11 | 12 | -------------------------------------------------------------------------------- /test/testfiles/commblanks.py: -------------------------------------------------------------------------------- 1 | # 2 | # A comment at top. 3 | # 4 | 5 | import sys 6 | 7 | a = 12 8 | 9 | b = 16 10 | 11 | c = 14 12 | 13 | def test(): 14 | return a+b+c 15 | 16 | if "__main__" == __name__: 17 | sys.exit(test()) 18 | -------------------------------------------------------------------------------- /test/testfiles/defafteruse.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | class Server: 5 | def fun(self): 6 | agenthost = "arne" 7 | return get_fortytwo(agenthost, kwarg=42) 8 | 9 | def get_fortytwo(agenthost, kwarg=3): 10 | foo = agenthost 11 | return kwarg 12 | 13 | s = Server() 14 | 15 | sys.exit(s.fun()) 16 | -------------------------------------------------------------------------------- /test/testfiles/dyn_all.py: -------------------------------------------------------------------------------- 1 | foo = ["aaa"] 2 | __all__ = ["bbb"] + foo 3 | 4 | def bbb(): 5 | return 40 6 | 7 | def aaa(): 8 | return 2 9 | -------------------------------------------------------------------------------- /test/testfiles/global.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | def foo(): 5 | return glob*2 6 | 7 | def main(): 8 | global glob 9 | glob = 21 10 | return foo() 11 | 12 | sys.exit(main()) 13 | -------------------------------------------------------------------------------- /test/testfiles/import.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from tobeimported import foo 4 | 5 | sys.exit(foo()) 6 | 7 | -------------------------------------------------------------------------------- /test/testfiles/importall_star.py: -------------------------------------------------------------------------------- 1 | from tobeimported_everything import * 2 | import sys 3 | 4 | sys.exit(one()+two()+thirtynine()) 5 | 6 | -------------------------------------------------------------------------------- /test/testfiles/importpackage.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from package.tobeimported import foo 4 | 5 | sys.exit(foo()) 6 | -------------------------------------------------------------------------------- /test/testfiles/importpackage_as.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from package.tobeimported import foo as bar 4 | 5 | sys.exit(bar()) 6 | -------------------------------------------------------------------------------- /test/testfiles/keywordclass.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ["ClassWithKeywords"] 3 | 4 | class ClassWithKeywords: 5 | def __init__(self, kwarg = 3): 6 | self.kwarg = kwarg 7 | 8 | def fortytwo(self, arg=6): 9 | return self.kwarg + arg 10 | 11 | -------------------------------------------------------------------------------- /test/testfiles/keywordclassuser.py: -------------------------------------------------------------------------------- 1 | 2 | import keywordclass 3 | import sys 4 | 5 | k = keywordclass.ClassWithKeywords(kwarg=20) 6 | 7 | sys.exit(k.fortytwo(arg=22)) 8 | -------------------------------------------------------------------------------- /test/testfiles/keywordfunc.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | SOMETHING=21 5 | 6 | def foo(bar=SOMETHING): 7 | return bar 8 | 9 | def gazonk(startval=2): 10 | return startval + foo() 11 | 12 | if "__main__" == __name__: 13 | sys.exit(gazonk(startval=21)) 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /test/testfiles/lambda_global.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import functools 3 | 4 | def smallest(x, y): 5 | return min(x, y) 6 | 7 | def main(): 8 | l = [120, 300, 42] 9 | return functools.reduce(lambda x, y: smallest(x, y), l) 10 | 11 | 12 | if "__main__" == __name__: 13 | sys.exit(main()) 14 | -------------------------------------------------------------------------------- /test/testfiles/package/.cvsignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /test/testfiles/package/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/astrand/pyobfuscate/34f5f6505c338ec34cd8653579235545c5c1c9ac/test/testfiles/package/__init__.py -------------------------------------------------------------------------------- /test/testfiles/package/tobeimported.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ["foo"] 3 | 4 | def bar(): 5 | return 40 6 | 7 | def foo(): 8 | return bar() + 2 9 | 10 | -------------------------------------------------------------------------------- /test/testfiles/power.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | x = 2 5 | y = x**2 6 | sys.exit(y) 7 | -------------------------------------------------------------------------------- /test/testfiles/tobeimported.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ["foo"] 3 | 4 | def bar(): 5 | return 40 6 | 7 | def foo(): 8 | return bar() + 2 9 | -------------------------------------------------------------------------------- /test/testfiles/tobeimported_everything.py: -------------------------------------------------------------------------------- 1 | 2 | __all__ = ["one", "two", "thirtynine"] 3 | 4 | def one(): 5 | return 1 6 | 7 | def two(): 8 | return 2 9 | 10 | def thirtynine(): 11 | return 39 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /test/testfiles/tobeimported_noall.py: -------------------------------------------------------------------------------- 1 | def one(): 2 | return 1 3 | 4 | def two(): 5 | return 2 6 | 7 | def _hidden(): 8 | return 2 --------------------------------------------------------------------------------