├── .cvsignore ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── 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_globals.py ├── test_lambda.py ├── test_literals.py ├── test_locals.py ├── test_pyobfuscate.py └── testfiles ├── .cvsignore ├── 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 /.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.md: -------------------------------------------------------------------------------- 1 | pyobfuscate -- Python source code obfuscator 2 | ============================================ 3 | 4 | This is a fork of the original pyobfuscate https://github.com/astrand/pyobfuscate, which has been dead for a couple of years now. 5 | 6 | I'll be trying to continue the development of the project with the focus of automating the obfuscation and randomization of python based payloads to avoid AV detection. 7 | 8 | All of the limitations of the original project currently still apply to this fork, so far the only changes have been: 9 | 10 | - Random character pool has been expanded to all upper and lowercase ASCII letters 11 | - Randomization seed now (properly) defaults to the system time (originally was hardcoded to 54) 12 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | * Obfuscate strings, by using \x sequences. 2 | 3 | 4 | * Obfuscate attributes and methods. The fundamental problem is that 5 | when referencing attributes/methods (with obj.attr or obj.meth), we 6 | do not know the type of obj. The Bicycle Repair Man project has some 7 | type detection code, which might be useful. 8 | 9 | 10 | * Replace all "import foo" with "import foo as somethingobfuscated". 11 | 12 | 13 | * Do not put noop-lines before from __future__ imports. 14 | 15 | 16 | * Make noop-lines even more unreadable by introducing variables in the 17 | "if" expression, and possible let multiple adjacent noop-lines form 18 | a single if-statement. 19 | -------------------------------------------------------------------------------- /pyobfuscate: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*-mode: python; coding: utf-8 -*- 3 | # 4 | # pyobfuscate - Python source code obfuscator 5 | # 6 | # Copyright 2004-2007 Peter Astrand for Cendio AB 7 | # 8 | # This program is free software; you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation; version 2 of the License. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program; if not, write to the Free Software 19 | # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 20 | 21 | import sys 22 | import datetime 23 | import types 24 | import symbol 25 | import token 26 | import keyword 27 | import tokenize 28 | import compiler 29 | import parser 30 | import random 31 | import symtable 32 | import StringIO 33 | import string 34 | import getopt 35 | import re 36 | 37 | TOKENBLANKS=1 38 | 39 | class NameTranslator: 40 | def __init__(self): 41 | self.realnames = {} 42 | self.bogusnames = [] 43 | 44 | 45 | def get_name(self, name): 46 | """Get a translation for a real name""" 47 | if not self.realnames.has_key(name): 48 | self.realnames[name] = self.gen_unique_name() 49 | return self.realnames[name] 50 | 51 | 52 | def get_bogus_name(self,): 53 | """Get a random bogus name""" 54 | if len(self.bogusnames) < 20: 55 | newname = self.gen_unique_name() 56 | self.bogusnames.append(newname) 57 | return newname 58 | else: 59 | return random.choice(self.bogusnames) 60 | 61 | 62 | def gen_unique_name(self): 63 | """Generate a name that hasn't been used before; 64 | not as a real name, not as a bogus name""" 65 | existing_names = self.realnames.values() + self.bogusnames 66 | name = "" 67 | while 1: 68 | name += self.gen_name() 69 | if name not in existing_names: 70 | break 71 | return name 72 | 73 | 74 | def gen_name(): 75 | length = random.randrange(5,20) 76 | chars = ''.join(random.choice(string.ascii_letters) for x in range(length)) 77 | # Name must'nt begin with a number 78 | return chars 79 | gen_name = staticmethod(gen_name) 80 | 81 | 82 | 83 | class LambdaSymTable: 84 | def __init__(self, symtabs, argnames): 85 | # Well, lambdas have no name, so they are safe to obfuscate... 86 | self.symtabs = symtabs 87 | self.mysymbs = {} 88 | for argname in argnames: 89 | self.mysymbs[argname] = symtable.Symbol(argname, symtable.DEF_PARAM) 90 | 91 | 92 | def lookup(self, name): 93 | lsymb = self.mysymbs.get(name) 94 | if lsymb: 95 | return lsymb 96 | else: 97 | # If the symbol is not found in the current sumboltable, 98 | # then look in the toplevel symtable. Perhaps we should 99 | # even look in all symtabs. 100 | try: 101 | return self.symtabs[-1].lookup(name) 102 | except KeyError: 103 | return self.symtabs[0].lookup(name) 104 | 105 | 106 | def get_type(self): 107 | return self.symtabs[-1].get_type() 108 | 109 | 110 | def is_lambda_arg(self, id): 111 | return self.mysymbs.has_key(id) 112 | 113 | 114 | class CSTWalker: 115 | def __init__(self, source_no_encoding, pubapi): 116 | # Our public API (__all__) 117 | self.pubapi = pubapi 118 | # Names of imported modules 119 | self.modnames = [] 120 | self.symtab = symtable.symtable(source_no_encoding, "-", "exec") 121 | cst = parser.suite(source_no_encoding) 122 | elements = parser.ast2tuple(cst, line_info=1) 123 | self.names = {} 124 | self.walk(elements, [self.symtab]) 125 | 126 | 127 | 128 | def getNames(self): 129 | return self.names 130 | 131 | 132 | def addToNames(self, line, name, doreplace): 133 | namedict = self.names.get(line, {}) 134 | if not namedict: 135 | self.names[line] = namedict 136 | 137 | occurancelist = namedict.get(name, []) 138 | if not occurancelist: 139 | namedict[name] = occurancelist 140 | 141 | occurancelist.append(doreplace) 142 | 143 | 144 | def res_name(self, name): 145 | if name.startswith("__") and name.endswith("__"): 146 | return 1 147 | if name in self.modnames: 148 | return 1 149 | if hasattr(__builtins__, name): 150 | return 1 151 | return 0 152 | 153 | 154 | def walk(self, elements, symtabs): 155 | # We are not interested in terminal tokens 156 | if type(elements) != types.TupleType: 157 | return 158 | if token.ISTERMINAL(elements[0]): 159 | return 160 | 161 | production = elements[0] 162 | if production == symbol.funcdef: 163 | self.handle_funcdef(elements, symtabs) 164 | elif production == symbol.varargslist: 165 | self.handle_varargslist(elements, symtabs) 166 | elif production == symbol.fpdef: 167 | self.handle_fpdef(elements, symtabs) 168 | elif production == symbol.import_as_name: 169 | self.handle_import_as_name(elements, symtabs) 170 | elif production == symbol.dotted_as_name: 171 | self.handle_dotted_as_name(elements, symtabs) 172 | elif production == symbol.dotted_name: 173 | self.handle_dotted_name(elements, symtabs) 174 | elif production == symbol.global_stmt: 175 | self.handle_global_stmt(elements, symtabs) 176 | elif production == symbol.atom: 177 | self.handle_atom(elements, symtabs) 178 | elif production == symbol.trailer: 179 | self.handle_trailer(elements, symtabs) 180 | elif production == symbol.classdef: 181 | self.handle_classdef(elements, symtabs) 182 | elif production == symbol.argument: 183 | self.handle_argument(elements, symtabs) 184 | elif production == symbol.lambdef: 185 | self.handle_lambdef(elements, symtabs) 186 | elif production == symbol.decorator: 187 | self.handle_decorator(elements, symtabs) 188 | else: 189 | for node in elements: 190 | self.walk(node, symtabs) 191 | 192 | 193 | def mangle_name(self, symtabs, name): 194 | if self.res_name(name): 195 | return name 196 | 197 | if not name.startswith("__"): 198 | return name 199 | 200 | for i in xrange(len(symtabs)): 201 | tab = symtabs[-1 - i] 202 | tabtype = tab.get_type() 203 | if tabtype == "class": 204 | classname = tab.get_name().lstrip("_") 205 | return "_" + classname + name 206 | 207 | return name 208 | 209 | def should_obfuscate(self, id, symtabs): 210 | # This is the primary location of the magic in pyobfuscate, 211 | # where we try to figure out if a given symbol should be 212 | # obfuscated or left alone. 213 | 214 | tab = symtabs[-1] 215 | 216 | # Don't touch reserved names 217 | if self.res_name(id): 218 | return False 219 | 220 | # Need to get the internal symbol name before we can look it 221 | # up (needed for private class/object members) 222 | orig_id = id 223 | id = self.mangle_name(symtabs, id) 224 | try: 225 | s = tab.lookup(id) 226 | except Exception: 227 | return False 228 | 229 | # XXX: Debug code 230 | # Add the symbols you want to examine to this list 231 | debug_symbols = [] 232 | if id in debug_symbols: 233 | print >>sys.stderr, "%s:" % id 234 | print >>sys.stderr, " Imported:", s.is_imported() 235 | print >>sys.stderr, " Parameter:", s.is_parameter() 236 | print >>sys.stderr, " Global:", s.is_global() 237 | print >>sys.stderr, " Local:", s.is_local() 238 | 239 | # Explicit imports are a clear no 240 | if s.is_imported(): 241 | return False 242 | 243 | # Don't obfuscate arguments as the caller might be external 244 | # and referencing them by name 245 | if s.is_parameter(): 246 | # But we assume that lambda arguments are never referenced 247 | # by name. FIXME? 248 | if isinstance(tab, LambdaSymTable): 249 | if tab.is_lambda_arg(id): 250 | return True 251 | 252 | return False 253 | 254 | # Lambda scopes have some kind of pseudo-inheritance from 255 | # the surounding scope. As lambdas can only declare arguments 256 | # (which we just handled), we should start digging upwards for 257 | # all other symbols. 258 | if isinstance(tab, LambdaSymTable): 259 | while True: 260 | symtabs = symtabs[:-1] 261 | if symtabs == []: 262 | raise RuntimeError("Lambda symbol '%s' is not present on any scope" % id) 263 | 264 | if id in symtabs[-1].get_identifiers(): 265 | return self.should_obfuscate(orig_id, symtabs) 266 | 267 | # Global objects require special consideration. Need to figure 268 | # out where the symbol originated... 269 | if s.is_global(): 270 | topsymtab = symtabs[0] 271 | 272 | # A global that's not in the global symbol table is a symbol 273 | # that Python has no idea where it comes from (it is only 274 | # "read" in every context in the module). That means either 275 | # buggy code, or that it got dragged in via "import *". Assume 276 | # the latter and don't obfuscate it. 277 | if id not in topsymtab.get_identifiers(): 278 | return False 279 | 280 | topsym = topsymtab.lookup(id) 281 | 282 | # XXX: See above: 283 | if id in debug_symbols: 284 | print >>sys.stderr, " Imported (G):", topsym.is_imported() 285 | print >>sys.stderr, " Parameter (G):", topsym.is_parameter() 286 | print >>sys.stderr, " Global (G):", topsym.is_global() 287 | print >>sys.stderr, " Local (G):", topsym.is_local() 288 | 289 | # Explicit imports are a clear no 290 | if topsym.is_imported(): 291 | return False 292 | 293 | # "Local" really means "written to", or "declared". So a 294 | # global that is not "local" in the global symbol table is 295 | # something that was created in another scope. This can happen 296 | # in two cases: 297 | # 298 | # a) Imported via * 299 | # 300 | # b) Created via "global foo" inside a function 301 | # 302 | # We want to obfuscate b), but not a). But we cannot tell which 303 | # is which, so just leave both alone. 304 | if not topsym.is_local(): 305 | return False 306 | 307 | # This is something we declared, so obfuscate unless it is 308 | # part of the module API. 309 | return id not in self.pubapi 310 | 311 | # If it's not global, nor local, then it must come from a 312 | # containing scope (e.g. function inside another function). 313 | if not s.is_local(): 314 | # Any more scopes to try? 315 | if len(symtabs) <= 2: 316 | raise RuntimeError("Symbol '%s' is not present on any scope" % id) 317 | return self.should_obfuscate(orig_id, symtabs[:-1]) 318 | 319 | # Local symbols are handled differently depending on what 320 | # our current scope is. 321 | tabtype = tab.get_type() 322 | if tabtype == "module": 323 | # Toplevel. Check with pubapi. 324 | return id not in self.pubapi 325 | elif tabtype == "function": 326 | # Function/method. Always OK. 327 | return True 328 | elif tabtype == "class": 329 | # This is a class method/variable (or, perhaps, a class in a class) 330 | # FIXME: We cannot obfuscate methods right now, 331 | # because we cannot handle calls like obj.meth(), 332 | # since we do not know the type of obj. 333 | return False 334 | else: 335 | raise RuntimeError("Unknown scope '%s' for symbol '%s'" % (tabtype, id)) 336 | 337 | def handle_funcdef(self, elements, symtabs): 338 | # funcdef: 'def' NAME parameters ':' suite 339 | # elements is something like: 340 | # (259, (1, 'def', 6), (1, 'f', 6), (260, ... 341 | name = elements[2] 342 | assert name[0] == token.NAME 343 | id = name[1] 344 | line = name[2] 345 | obfuscate = self.should_obfuscate(id, symtabs) 346 | 347 | self.addToNames(line, id, obfuscate) 348 | 349 | tab = symtabs[-1] 350 | 351 | orig_id = id 352 | id = self.mangle_name(symtabs, id) 353 | 354 | functabs = tab.lookup(id).get_namespaces() 355 | 356 | # Mangled names mess up the association with the symbol table, so 357 | # we need to find it manually 358 | if len(functabs) == 0: 359 | functabs = [] 360 | for child in tab.get_children(): 361 | if child.get_name() == orig_id: 362 | functabs.append(child) 363 | 364 | for node in elements: 365 | self.walk(node, symtabs + functabs) 366 | 367 | 368 | def handle_varargslist(self, elements, symtabs): 369 | # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) ... 370 | # elements is something like: 371 | # (261, (262, (1, 'XXX', 37)), (12, ',', 37), (262, (1, 'bar', 38)), (22, '=', 38), (292, (293, (294, 372 | # The purpose of this method is to find vararg and kwarg names 373 | # (which are not fpdefs). 374 | tab = symtabs[-1] 375 | 376 | for tok in elements: 377 | if type(tok) != types.TupleType: 378 | continue 379 | 380 | toktype = tok[0] 381 | if toktype == symbol.test: 382 | # This is a "= test" expression 383 | for node in tok: 384 | # The [:-1] is because we actually are not in the 385 | # functions scope yet. 386 | self.walk(node, symtabs[:-1]) 387 | elif toktype == token.NAME: 388 | # This is either an "*args" or an "**kwargs". We could 389 | # in theory obfuscate these as they cannot be referenced 390 | # directly by the caller. However, we currently have no 391 | # idea of telling that these are special when we hit the 392 | # references to them. So for now we treat them as we 393 | # would any other argument. 394 | id = tok[1] 395 | line = tok[2] 396 | obfuscate = self.should_obfuscate(id, symtabs) 397 | self.addToNames(line, id, obfuscate) 398 | elif toktype == symbol.fpdef: 399 | self.handle_fpdef(tok, symtabs) 400 | else: 401 | assert(toktype in [token.STAR, token.DOUBLESTAR, 402 | token.COMMA, token.EQUAL]) 403 | 404 | def handle_fpdef(self, elements, symtabs): 405 | # fpdef: NAME | '(' fplist ')' 406 | # elements is something like: 407 | # (262, (1, 'self', 13)) 408 | name = elements[1] 409 | assert name[0] == token.NAME 410 | id = name[1] 411 | line = name[2] 412 | obfuscate = self.should_obfuscate(id, symtabs) 413 | 414 | self.addToNames(line, id, obfuscate) 415 | for node in elements: 416 | self.walk(node, symtabs) 417 | 418 | 419 | def handle_import_as_name(self, elements, symtabs): 420 | # import_as_name: NAME [NAME NAME] 421 | # elements is something like: 422 | # (279, (1, 'format_tb', 11)) 423 | # or 424 | # (279, (1, 'format_tb', 11), (1, 'as', 11), (1, 'ftb', 11)) 425 | name1 = elements[1] 426 | assert name1[0] == token.NAME 427 | id1 = name1[1] 428 | line1 = name1[2] 429 | self.addToNames(line1, id1, 0) 430 | 431 | if len(elements) > 2: 432 | assert len(elements) == 4 433 | 434 | name2 = elements[2] 435 | assert name2[0] == token.NAME 436 | id2 = name2[1] 437 | assert id2 == "as" 438 | line2 = name2[2] 439 | self.addToNames(line2, id2, 0) 440 | 441 | name3 = elements[3] 442 | assert name3[0] == token.NAME 443 | id3 = name3[1] 444 | line3 = name3[2] 445 | # FIXME: Later, obfuscate if scope/pubabi etc OK 446 | self.addToNames(line3, id3, 0) 447 | self.modnames.append(id3) 448 | 449 | for node in elements: 450 | self.walk(node, symtabs) 451 | 452 | 453 | def handle_dotted_as_name(self, elements, symtabs): 454 | # dotted_as_name: dotted_name [NAME NAME] 455 | # elements is something like: 456 | # (280, (281, (1, 'os', 2))) 457 | # or 458 | # (280, (281, (1, 'traceback', 11)), (1, 'as', 11), (1, 'tb', 11)) 459 | # handle_dotted_name takes care of dotted_name 460 | dotted_name = elements[1] 461 | 462 | modname = dotted_name[1] 463 | assert modname[0] == token.NAME 464 | mod_id = modname[1] 465 | mod_line = modname[2] 466 | self.addToNames(mod_line, mod_id, 0) 467 | self.modnames.append(mod_id) 468 | 469 | if len(elements) > 2: 470 | # import foo as bar ... 471 | assert len(elements) == 4 472 | 473 | asname = elements[2] 474 | assert asname[0] == token.NAME 475 | asid = asname[1] 476 | assert asid == "as" 477 | asline = asname[2] 478 | self.addToNames(asline, asid, 0) 479 | 480 | name = elements[3] 481 | assert name[0] == token.NAME 482 | id = name[1] 483 | line = name[2] 484 | # FIXME: Later, obfuscate if scope/pubabi etc OK 485 | self.addToNames(line, id, 0) 486 | self.modnames.append(id) 487 | 488 | for node in elements: 489 | self.walk(node, symtabs) 490 | 491 | 492 | def handle_dotted_name(self, elements, symtabs): 493 | # dotted_name: NAME ('.' NAME)* 494 | # elements is something like: 495 | # (281, (1, 'os', 2)) 496 | # or 497 | # (281, (1, 'compiler', 11), (23, '.', 11), (1, 'ast', 11)) 498 | # or 499 | # (281, (1, 'bike', 11), (23, '.', 11), (1, 'bikefacade', 11), (23, '.', 11), (1, 'visitor', 11)) 500 | name = elements[1] 501 | assert name[0] == token.NAME 502 | id = name[1] 503 | line = name[2] 504 | self.addToNames(line, id, 0) 505 | 506 | # Sequence length should be even 507 | assert (len(elements) % 2 == 0) 508 | for x in range(2, len(elements), 2): 509 | dot = elements[x] 510 | name = elements[x+1] 511 | 512 | assert dot[0] == token.DOT 513 | assert name[0] == token.NAME 514 | id = name[1] 515 | line = name[2] 516 | self.addToNames(line, id, 0) 517 | for node in elements: 518 | self.walk(node, symtabs) 519 | 520 | 521 | def handle_global_stmt(self, elements, symtabs): 522 | # global_stmt: 'global' NAME (',' NAME)* 523 | # elements is something like: 524 | # (282, (1, 'global', 41), (1, 'foo', 41)) 525 | # or 526 | # (282, (1, 'global', 32), (1, 'aaaa', 32), (12, ',', 32), (1, 'bbbb', 32)) 527 | gname = elements[1] 528 | assert gname[0] == token.NAME 529 | gid = gname[1] 530 | assert gid == "global" 531 | 532 | name1 = elements[2] 533 | assert name1[0] == token.NAME 534 | id1 = name1[1] 535 | line1 = name1[2] 536 | obfuscate = self.should_obfuscate(id1, symtabs) 537 | self.addToNames(line1, id1, obfuscate) 538 | 539 | # Sequence length should be odd 540 | assert (len(elements) % 2) 541 | for x in range(3, len(elements), 2): 542 | comma = elements[x] 543 | name = elements[x+1] 544 | assert comma[0] == token.COMMA 545 | assert name[0] == token.NAME 546 | id = name[1] 547 | line = name[2] 548 | obfuscate = id not in self.pubapi 549 | self.addToNames(line, id, obfuscate) 550 | for node in elements: 551 | self.walk(node, symtabs) 552 | 553 | 554 | def handle_atom(self, elements, symtabs): 555 | # atom: ... | NAME | ... 556 | # elements is something like: 557 | # (305, (1, 'os', 15)) 558 | name = elements[1] 559 | if name[0] == token.NAME: 560 | id = name[1] 561 | line = name[2] 562 | obfuscate = self.should_obfuscate(id, symtabs) 563 | 564 | self.addToNames(line, id, obfuscate) 565 | 566 | for node in elements: 567 | self.walk(node, symtabs) 568 | 569 | 570 | def handle_trailer(self, elements, symtabs): 571 | # trailer: ... | '.' NAME 572 | # elements is something like: 573 | # (308, (23, '.', 33), (1, 'poll', 33)) 574 | trailer = elements[1] 575 | if trailer[0] == token.DOT: 576 | name = elements[2] 577 | assert name[0] == token.NAME 578 | id = name[1] 579 | line = name[2] 580 | # Cannot obfuscate these as we have no idea what the base 581 | # object is. 582 | self.addToNames(line, id, 0) 583 | for node in elements: 584 | self.walk(node, symtabs) 585 | 586 | 587 | def handle_classdef(self, elements, symtabs): 588 | # classdef: 'class' NAME ['(' testlist ')'] ':' suite 589 | # elements is something like: 590 | # (316, (1, 'class', 48), (1, 'SuperMyClass', 48), (11, ':', 48), 591 | name = elements[2] 592 | assert name[0] == token.NAME 593 | id = name[1] 594 | line = name[2] 595 | obfuscate = self.should_obfuscate(id, symtabs) 596 | 597 | self.addToNames(line, id, obfuscate) 598 | 599 | aftername = elements[3] 600 | aftername2 = elements[4] 601 | # Should be either a colon or left paren 602 | assert aftername[0] in (token.COLON, token.LPAR) 603 | if aftername[0] == token.LPAR and aftername2[0] != token.RPAR: 604 | # This class is inherited 605 | testlist = elements[4] 606 | assert testlist[0] == symbol.testlist 607 | # Parsing of testlist should be done in the original scope 608 | for node in testlist: 609 | self.walk(node, symtabs) 610 | elements = elements[5:] 611 | 612 | tab = symtabs[-1] 613 | classtab = tab.lookup(id).get_namespace() 614 | 615 | for node in elements: 616 | self.walk(node, symtabs + [classtab]) 617 | 618 | 619 | def handle_argument(self, elements, symtabs): 620 | # argument: [test '='] test # Really [keyword '='] test 621 | # elements is like: 622 | # (318, (292, (293, (294, (295, (297, (298, (299, (300, (301, 623 | # (302, (303, (304, (305, (3, '"SC_OPEN_MAX"', 15 624 | 625 | # Keyword argument? 626 | if len(elements) >= 4: 627 | # keyword=test 628 | # FIXME: A bit ugly... 629 | if sys.hexversion >= 0x2040000: 630 | keyword = elements[1][1][1][1][1][1][1][1][1][1][1][1][1][1][1] 631 | else: 632 | keyword = elements[1][1][1][1][1][1][1][1][1][1][1][1][1][1] 633 | assert keyword[0] == token.NAME 634 | keyword_id = keyword[1] 635 | keyword_line = keyword[2] 636 | 637 | # Argument names have to be in the clear as we cannot track all 638 | # callers. See should_obfuscate(). 639 | self.addToNames(keyword_line, keyword_id, False) 640 | 641 | # Let the obfuscator continue handling the value 642 | elements = elements[3] 643 | 644 | for node in elements: 645 | self.walk(node, symtabs) 646 | 647 | 648 | def handle_lambdef(self, elements, symtabs): 649 | # lambdef: 'lambda' [varargslist] ':' test 650 | # elements is like: 651 | # (307, (1, 'lambda', 588), (261, (262, (1, 'e', 588))), (11, ':', 588) 652 | # or 653 | # (307, (1, 'lambda', 40), (11, ':', 40), (292 ... 654 | if elements[2][0] == token.COLON: 655 | # There are no lambda arguments. Simple! 656 | # We still need to create a LambdaSymTable though since we 657 | # rely on some magic lookup that it does. 658 | test = elements[3] 659 | lambdatab = LambdaSymTable(symtabs, []) 660 | for node in test: 661 | self.walk(node, symtabs + [lambdatab]) 662 | else: 663 | # The more common case: You have a varargslist. 664 | varargslist = elements[2] 665 | 666 | # Part 1: Deal with varargslist. Fetch the names of the 667 | # arguments. Construct a LambdaSymTable. 668 | arguments = self.get_varargs_names(varargslist) 669 | for line, name in arguments: 670 | self.addToNames(line, name, 1) 671 | 672 | argnames = [e[1] for e in arguments] 673 | lambdatab = LambdaSymTable(symtabs, argnames) 674 | 675 | # Part 2: Parse the 'test' part, using the LambdaSymTable. 676 | test = elements[4] 677 | for node in test: 678 | self.walk(node, symtabs + [lambdatab]) 679 | 680 | def handle_decorator(self, elements, symtabs): 681 | # decorator: '@' NAME parameters 682 | # elements is something like: 683 | # (259, (50, '@', 39), (288, (1, 'f', 39)), (4, '', 39)) 684 | name = elements[2][1] 685 | assert name[0] == token.NAME 686 | id = name[1] 687 | line = name[2] 688 | obfuscate = self.should_obfuscate(id, symtabs) 689 | 690 | self.addToNames(line, id, obfuscate) 691 | for node in elements: 692 | self.walk(node, symtabs) 693 | 694 | def get_varargs_names(elements): 695 | """Extract all argument names and lines from varargslist""" 696 | result = [] 697 | 698 | next_is_name = False 699 | for tok in elements: 700 | if type(tok) != types.TupleType: 701 | continue 702 | 703 | toktype = tok[0] 704 | if next_is_name: 705 | assert tok[0] == token.NAME 706 | id = tok[1] 707 | line = tok[2] 708 | result.append((line, id)) 709 | next_is_name = False 710 | elif toktype in [token.STAR, token.DOUBLESTAR]: 711 | next_is_name = True 712 | elif toktype == symbol.fpdef: 713 | result.extend(CSTWalker.get_fpdef_names(tok)) 714 | 715 | return result 716 | 717 | get_varargs_names = staticmethod(get_varargs_names) 718 | 719 | 720 | def get_fpdef_names(elements): 721 | """Extract all argument names from fpdef""" 722 | result = [] 723 | 724 | # We are not interested in terminal tokens 725 | if type(elements) != types.TupleType: 726 | return result 727 | if token.ISTERMINAL(elements[0]): 728 | return result 729 | 730 | name = elements[1] 731 | assert name[0] == token.NAME 732 | id = name[1] 733 | line = name[2] 734 | result.append((line, id)) 735 | for node in elements: 736 | result.extend(CSTWalker.get_fpdef_names(node)) 737 | return result 738 | 739 | get_fpdef_names = staticmethod(get_fpdef_names) 740 | 741 | 742 | 743 | class PubApiExtractor: 744 | def __init__(self, source_no_encoding): 745 | ast = compiler.parse(source_no_encoding) 746 | self.pubapi = None 747 | self.matches = 0 748 | compiler.walk(ast, self) 749 | if self.pubapi == None: 750 | # Didn't find __all__. 751 | if conf.allpublic: 752 | symtab = symtable.symtable(source_no_encoding, "-", "exec") 753 | self.pubapi = filter(lambda s: s[0] != "_", 754 | symtab.get_identifiers()) 755 | else: 756 | self.pubapi = [] 757 | 758 | if self.matches > 1: 759 | print >>sys.stderr, "Warning: Found multiple __all__ definitions" 760 | print >>sys.stderr, "Using last definition" 761 | 762 | 763 | def visitAssign(self, node): 764 | for assnode in node.nodes: 765 | if not isinstance(assnode, compiler.ast.AssName): 766 | continue 767 | 768 | if assnode.name == "__all__" \ 769 | and assnode.flags == compiler.consts.OP_ASSIGN: 770 | self.matches += 1 771 | self.pubapi = [] 772 | # Verify that the expression is a list 773 | constant = isinstance(node.expr, compiler.ast.List) 774 | if constant: 775 | # Verify that each element in list is a Const node. 776 | for node in node.expr.getChildNodes(): 777 | if isinstance(node, compiler.ast.Const): 778 | self.pubapi.append(node.value) 779 | else: 780 | constant = False 781 | break 782 | 783 | if not constant: 784 | print >>sys.stderr, "Error: __all__ is not a list of constants." 785 | sys.exit(1) 786 | 787 | 788 | 789 | class ColumnExtractor: 790 | def __init__(self, source, names): 791 | 792 | self.indent = 0 793 | self.first_on_line = 1 794 | # How many times have we seen this symbol on this line before? 795 | self.symboltimes = {} 796 | self.names = names 797 | # Dictionary indexed on (row, column), containing name 798 | self.result = {} 799 | # To detect line num changes; backslash constructs doesn't 800 | # generate any token 801 | self.this_lineno = 1 802 | f = StringIO.StringIO(source) 803 | self.parse(f) 804 | 805 | 806 | def parse(self, f): 807 | for tok in tokenize.generate_tokens(f.readline): 808 | t_type, t_string, t_srow_scol, t_erow_ecol, t_line = tok 809 | 810 | assert self.this_lineno <= t_srow_scol[0] 811 | if self.this_lineno < t_srow_scol[0]: 812 | # Gosh, line has skipped. This must be due to an 813 | # ending backslash. 814 | self.this_lineno = t_srow_scol[0] 815 | self.symboltimes = {} 816 | 817 | if t_type in [tokenize.NL, tokenize.NEWLINE]: 818 | self.this_lineno += 1 819 | self.symboltimes = {} 820 | elif t_type == tokenize.NAME: 821 | # Make life easier on us by ignoring keywords 822 | if keyword.iskeyword(t_string): 823 | continue 824 | 825 | srow = t_srow_scol[0] 826 | scol = t_srow_scol[1] 827 | 828 | namedict = self.names.get(srow) 829 | if not namedict: 830 | raise RuntimeError("Overlooked symbol '%s' on line %d column %d" % (t_string, srow, scol)) 831 | 832 | occurancelist = namedict.get(t_string) 833 | if not occurancelist: 834 | raise RuntimeError("Overlooked symbol '%s' on line %d column %d" % (t_string, srow, scol)) 835 | 836 | seen_times = self.saw_symbol(t_string) 837 | if seen_times > len(occurancelist): 838 | raise RuntimeError("Overlooked symbol '%s' on line %d column %d" % (t_string, srow, scol)) 839 | 840 | if occurancelist[seen_times]: 841 | # This occurance should be obfuscated. 842 | assert self.result.get((srow, scol)) == None 843 | self.result[(srow, scol)] = t_string 844 | 845 | 846 | def saw_symbol(self, name): 847 | """Update self.symboltimes, when we have seen a symbol 848 | Return the current seen_times for this symbol""" 849 | seen_times = self.symboltimes.get(name, -1) 850 | seen_times += 1 851 | self.symboltimes[name] = seen_times 852 | return seen_times 853 | 854 | 855 | 856 | class TokenPrinter: 857 | AFTERCOMMENT = 0 858 | INSIDECOMMENT = 1 859 | BEFORECOMMENT = 2 860 | 861 | def __init__(self, source, names): 862 | self.indent = 0 863 | self.first_on_line = 1 864 | self.symboltimes = {} 865 | self.names = names 866 | self.nametranslator = NameTranslator() 867 | # Pending, obfuscated noop lines. We cannot add the noop lines 868 | # until we know what comes after. 869 | self.pending = [] 870 | self.pending_indent = 0 871 | # To detect line num changes; backslash constructs doesn't 872 | # generate any token 873 | self.this_lineno = 1 874 | self.pending_newlines = 0 875 | # Skip next token? 876 | self.skip_token = 0 877 | # Keep track of constructions that can span multiple lines 878 | self.paren_count = 0 879 | self.curly_count = 0 880 | self.square_count = 0 881 | # Comment state. One of AFTERCOMMENT, INSIDECOMMENT, BEFORECOMMENT 882 | if conf.firstcomment: 883 | self.commentstate = TokenPrinter.AFTERCOMMENT 884 | else: 885 | self.commentstate = TokenPrinter.BEFORECOMMENT 886 | f = StringIO.StringIO(source) 887 | self.play(f) 888 | 889 | 890 | def play(self, f): 891 | for tok in tokenize.generate_tokens(f.readline): 892 | t_type, t_string, t_srow_scol, t_erow_ecol, t_line = tok 893 | 894 | #print >>sys.stderr, "TTTT", tokenize.tok_name[t_type], repr(t_string), self.this_lineno, t_srow_scol[0] 895 | 896 | if t_type == tokenize.OP: 897 | if t_string == "(": 898 | self.paren_count += 1 899 | elif t_string == ")": 900 | self.paren_count -= 1 901 | elif t_string == "{": 902 | self.curly_count += 1 903 | elif t_string == "}": 904 | self.curly_count -= 1 905 | elif t_string == "[": 906 | self.square_count += 1 907 | elif t_string == "]": 908 | self.square_count -= 1 909 | 910 | assert self.paren_count >= 0 911 | assert self.curly_count >= 0 912 | assert self.square_count >= 0 913 | 914 | if self.skip_token: 915 | self.skip_token = 0 916 | continue 917 | 918 | # Make sure we keep line numbers 919 | # line numbers may not decrease 920 | assert self.this_lineno <= t_srow_scol[0] 921 | if self.this_lineno < t_srow_scol[0]: 922 | # Gosh, line has skipped. This must be due to an 923 | # ending backslash. 924 | self.pending_newlines += t_srow_scol[0] - self.this_lineno 925 | self.this_lineno = t_srow_scol[0] 926 | 927 | if t_type in [tokenize.NL, tokenize.NEWLINE]: 928 | for x in range(self.pending_newlines): 929 | if conf.blanks != conf.KEEP_BLANKS: 930 | self.pending.append(self.gen_noop_line() + "\n") 931 | self.pending_indent = self.indent 932 | else: 933 | sys.stdout.write("\n") 934 | self.pending_newlines = 0 935 | 936 | if t_type == tokenize.NL: 937 | if self.first_on_line and conf.blanks != conf.KEEP_BLANKS: 938 | self.pending.append(self.gen_noop_line() + "\n") 939 | self.pending_indent = self.indent 940 | else: 941 | sys.stdout.write("\n") 942 | self.this_lineno += 1 943 | if self.commentstate == TokenPrinter.INSIDECOMMENT: 944 | self.commentstate = TokenPrinter.AFTERCOMMENT 945 | 946 | elif t_type == tokenize.NEWLINE: 947 | self.first_on_line = 1 948 | self.this_lineno += 1 949 | sys.stdout.write("\n") 950 | if self.commentstate == TokenPrinter.INSIDECOMMENT: 951 | self.commentstate = TokenPrinter.AFTERCOMMENT 952 | 953 | elif t_type == tokenize.INDENT: 954 | self.indent += conf.indent 955 | elif t_type == tokenize.DEDENT: 956 | self.indent -= conf.indent 957 | elif t_type == tokenize.COMMENT: 958 | if self.commentstate == TokenPrinter.BEFORECOMMENT: 959 | self.commentstate = TokenPrinter.INSIDECOMMENT 960 | 961 | if self.first_on_line: 962 | if self.commentstate in [TokenPrinter.BEFORECOMMENT, TokenPrinter.INSIDECOMMENT]: 963 | # Output comment. Only old Python includes newline. 964 | if sys.hexversion >= 0x2040000: 965 | t_string += "\n" 966 | self.line_append(t_string) 967 | elif conf.blanks != conf.KEEP_BLANKS: 968 | self.pending.append(self.gen_noop_line() + "\n") 969 | self.pending_indent = self.indent 970 | else: 971 | sys.stdout.write("\n") 972 | 973 | self.this_lineno += 1 974 | else: 975 | if sys.hexversion >= 0x2040000: 976 | sys.stdout.write("\n") 977 | self.this_lineno += 1 978 | 979 | # tokenizer does not generate a NEWLINE after comment 980 | self.first_on_line = 1 981 | if sys.hexversion >= 0x2040000: 982 | # tokinizer generates NL after each COMMENT 983 | self.skip_token = 1 984 | elif t_type == tokenize.STRING: 985 | if self.first_on_line: 986 | # Skip over docstrings 987 | # FIXME: This simple approach fails with: 988 | # "foo"; print 3 989 | if self.paren_count > 0 or \ 990 | self.curly_count > 0 or \ 991 | self.square_count > 0: 992 | self.line_append(t_string) 993 | self.this_lineno += t_string.count("\n") 994 | else: 995 | self.skip_token = 1 996 | else: 997 | self.line_append(t_string) 998 | self.this_lineno += t_string.count("\n") 999 | elif t_type == tokenize.NAME: 1000 | (srow, scol) = t_srow_scol 1001 | if self.names.get(t_srow_scol): 1002 | t_string = self.nametranslator.get_name(t_string) 1003 | 1004 | self.line_append(t_string) 1005 | else: 1006 | self.line_append(t_string) 1007 | 1008 | 1009 | def line_append(self, s): 1010 | if self.pending: 1011 | indent = max(self.indent, self.pending_indent) 1012 | self.pending = map(lambda row: " "*indent + row, 1013 | self.pending) 1014 | if conf.blanks == conf.OBFUSCATE_BLANKS: 1015 | sys.stdout.write(''.join(self.pending)) 1016 | self.pending = [] 1017 | 1018 | if self.first_on_line: 1019 | sys.stdout.write(" "*self.indent) 1020 | else: 1021 | sys.stdout.write(" "*TOKENBLANKS) 1022 | sys.stdout.write(s) 1023 | self.first_on_line = 0 1024 | 1025 | 1026 | def gen_noop_line(self): 1027 | if self.paren_count > 0 or \ 1028 | self.curly_count > 0 or \ 1029 | self.square_count > 0: 1030 | result = "# " 1031 | else: 1032 | testint = random.randint(1, 100) 1033 | result = "if %d - %d: " % (testint, testint) 1034 | num_words = random.randint(1, 6) 1035 | for x in range(num_words - 1): 1036 | op = random.choice((".", "/", "+", "-", "%", "*")) 1037 | result += self.nametranslator.get_bogus_name() + " %s " % op 1038 | result += self.nametranslator.get_bogus_name() 1039 | return result 1040 | 1041 | 1042 | 1043 | def strip_encoding(source): 1044 | f = StringIO.StringIO(source) 1045 | lines = [f.readline(), f.readline()] 1046 | buf = "" 1047 | for line in lines: 1048 | if re.search("coding[:=]\s*([-\w_.]+)", line): 1049 | if line.strip().startswith("#"): 1050 | # Add a empty line instead 1051 | buf += "\n" 1052 | else: 1053 | # Gosh, not a comment. 1054 | print >>sys.stderr, "ERROR: Python 2.3 with coding declaration in non-comment!" 1055 | sys.exit(1) 1056 | else: 1057 | # Coding declaration not found on this line; add 1058 | # unmodified 1059 | buf += line 1060 | 1061 | return buf + f.read() 1062 | 1063 | 1064 | 1065 | def usage(): 1066 | print >>sys.stderr, """ 1067 | Usage: 1068 | 1069 | pyobfuscate [options] 1070 | 1071 | Options: 1072 | 1073 | -h, --help Print this help. 1074 | -i, --indent Indentation to use. Default is 1. 1075 | -s, --seed Seed to use for name randomization. Default is 1076 | system time. 1077 | -r, --removeblanks Remove blank lines, instead of obfuscate 1078 | -k, --keepblanks Keep blank lines, instead of obfuscate 1079 | -f, --firstcomment Remove first block of comments as well 1080 | -a, --allpublic When __all__ is missing, assume everything is public. 1081 | The default is to assume nothing is public. 1082 | -v, --verbose Verbose mode. 1083 | """ 1084 | 1085 | 1086 | class Configuration: 1087 | KEEP_BLANKS = 0 1088 | OBFUSCATE_BLANKS = 1 1089 | REMOVE_BLANKS = 2 1090 | 1091 | def __init__(self): 1092 | try: 1093 | opts, args = getopt.getopt(sys.argv[1:], "hi:s:rkfav", 1094 | ["help", "indent=", "seed=", "removeblanks", 1095 | "keepblanks", "firstcomment", "allpublic", 1096 | "verbose"]) 1097 | if len(args) != 1: 1098 | raise getopt.GetoptError("A filename is required", "") 1099 | except getopt.GetoptError, e: 1100 | print >>sys.stderr, "Error:", e 1101 | usage() 1102 | sys.exit(2) 1103 | 1104 | d = datetime.datetime.now() 1105 | 1106 | self.file = args[0] 1107 | self.indent = 1 1108 | self.seed = d.microsecond + d.second + d.day + d.month + d.year 1109 | self.blanks = self.OBFUSCATE_BLANKS 1110 | self.firstcomment = False 1111 | self.allpublic = False 1112 | self.verbose = False 1113 | 1114 | for o, a in opts: 1115 | if o in ("-h", "--help"): 1116 | usage() 1117 | sys.exit() 1118 | if o in ("-i", "--indent"): 1119 | self.indent = int(a) 1120 | if o in ("-s", "--seed"): 1121 | self.seed = a 1122 | if o in ("-r", "--removeblanks"): 1123 | self.blanks = self.REMOVE_BLANKS 1124 | if o in ("-k", "--keepblanks"): 1125 | self.blanks = self.KEEP_BLANKS 1126 | if o in ("-f", "--firstcomment"): 1127 | self.firstcomment = True 1128 | if o in ("-a", "--allpublic"): 1129 | self.allpublic = True 1130 | if o == ("-v", "--verbose"): 1131 | self.verbose = True 1132 | 1133 | 1134 | 1135 | def main(): 1136 | global conf 1137 | conf = Configuration() 1138 | random.seed(conf.seed) 1139 | 1140 | source = open(conf.file, 'rU').read() 1141 | 1142 | if sys.version_info[:2] == (2, 3): 1143 | # Enable Python 2.3 workaround for bug 898271. 1144 | source_no_encoding = strip_encoding(source) 1145 | else: 1146 | source_no_encoding = source 1147 | 1148 | 1149 | # Step 1: Extract __all__ from source. 1150 | pae = PubApiExtractor(source_no_encoding) 1151 | 1152 | 1153 | # Step 2: Walk the CST tree. The result of this step is a 1154 | # dictionary indexed on line numbers, which contains dictionaries 1155 | # indexed on symbols, which contains a list of the occurances of 1156 | # this symbol on this line. A 1 in this list means that the 1157 | # occurance should be obfuscated; 0 means not. Example: {64: 1158 | # {'foo': [0, 1], 'run': [0]} 1159 | cw = CSTWalker(source_no_encoding, pae.pubapi) 1160 | 1161 | 1162 | # Step 3: We need those column numbers! Use the tokenize module to 1163 | # step through the source code to gather this information. The 1164 | # result of this step is a dictionary indexed on tuples (row, 1165 | # column), which contains the symbol names. Example: {(55, 6): 1166 | # 'MyClass'} Only symbols that should be replaced are returned. 1167 | # (This step could perhaps be merged with step 4, but there are 1168 | # two reasons for not doing so: 1) Make each step less 1169 | # complicated. 2) If we want to use BRM some day, then we'll need 1170 | # the column numbers.) 1171 | ce = ColumnExtractor(source, cw.names) 1172 | 1173 | 1174 | # Step 4: Play the tokenizer game! Step through the source 1175 | # code. Obfuscate those symbols gathered earlier. Change 1176 | # indentation, blank lines etc. 1177 | TokenPrinter(source, ce.result) 1178 | 1179 | # Step 5: Output a marker that makes it possible to recognize 1180 | # obfuscated files 1181 | print "# dd678faae9ac167bc83abf78e5cb2f3f0688d3a3" 1182 | 1183 | if __name__ == "__main__": 1184 | main() 1185 | 1186 | -------------------------------------------------------------------------------- /pyobfuscate-install: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 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 >>sys.stderr, """ 32 | Install and obfuscate a Python file in one step. 33 | 34 | Usage: 35 | pyobfuscate-install [-m ] [pyobfuscate-args] 36 | 37 | """ 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 = 0755 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[0] 59 | dest = rest[1] 60 | 61 | if os.path.isdir(dest): 62 | dest = os.path.join(dest, os.path.basename(source)) 63 | 64 | cmd = os.path.join(origin, "pyobfuscate") 65 | cmd += " " + source + " >" + dest 66 | print >>sys.stderr, "Calling", cmd 67 | retcode = os.system(cmd) 68 | os.chmod(dest, mode) 69 | if retcode > 254: 70 | retcode = 254 71 | sys.exit(retcode) 72 | 73 | 74 | if __name__ == "__main__": 75 | main() 76 | 77 | -------------------------------------------------------------------------------- /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 python 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 | execfile(root) 9 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | 2 | [bdist_rpm] 3 | doc_files = README TODO 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 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 | data_files=[('/usr/bin', ['pyobfuscate'])] 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 | # Obfuscate the obfuscator as a torture test 4 | 5 | ../pyobfuscate ../pyobfuscate > pyobfuscate 6 | chmod u+x pyobfuscate 7 | 8 | for fn in test_*.py; do 9 | ./pyobfuscate $fn | python - 10 | done 11 | -------------------------------------------------------------------------------- /test/test_args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 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 python 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 ClassTest(unittest.TestCase): 29 | def test_local(self): 30 | self.assertFalse("LocalClass" in globals()) 31 | 32 | def test_local_method(self): 33 | obj = LocalClass() 34 | # Method names should not be obfuscated as we don't 35 | # know what the object is until runtime 36 | self.assertTrue(hasattr(obj, "method_a")) 37 | 38 | def test_global(self): 39 | self.assertTrue("GlobalClass" in globals()) 40 | 41 | def test_global_method(self): 42 | obj = GlobalClass() 43 | # See test_local_method() 44 | self.assertTrue(hasattr(obj, "method_b")) 45 | 46 | def test_nested_class(self): 47 | self.assertFalse("OuterNestedClass" in globals()) 48 | self.assertTrue(hasattr(OuterNestedClass, "InnerNestedClass")) 49 | 50 | def test_nested_function(self): 51 | nested_function(self) 52 | 53 | if "__main__" == __name__: 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /test/test_globals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 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 python 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_literals.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 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 dictionary.keys()) 23 | self.assertTrue("key2" in 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 python 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_pyobfuscate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 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 '' == stderr, "pyobfuscate wrote to stderr: %s" % stderr 27 | return stdout 28 | 29 | def obfuscate_and_write(self, testfile, outfile, args=[]): 30 | open(outfile, 'w').write(self.run_pyobfuscate(testfile, args)) 31 | 32 | def run_src(self, src): 33 | f, fname = self.mkstemp() 34 | os.write(f, src) 35 | os.close(f) 36 | retcode = subprocess.call([sys.executable, fname]) 37 | os.remove(fname) 38 | return retcode 39 | 40 | def obfuscate_and_run_file(self, testfile, args=[]): 41 | output = self.run_pyobfuscate(testfile, args) 42 | return self.run_src(output) 43 | 44 | def obfuscate_and_run_src(self, src, args=[]): 45 | f, fname = self.mkstemp() 46 | os.write(f, src) 47 | os.close(f) 48 | retcode = self.obfuscate_and_run_file(fname, args) 49 | os.remove(fname) 50 | return retcode 51 | 52 | def test_DontKeepblanks(self): 53 | """Don't keep blanks unless told so""" 54 | output = self.run_pyobfuscate("testfiles/commblanks.py") 55 | assert None == re.search(output, "^$"), "Blank lines in output" 56 | lines = output.split("\n") 57 | assert "#" == lines[0][0], "First line is not a comment" 58 | assert 42 == self.run_src(output) 59 | 60 | def test_Keepblanks(self): 61 | """Keep blanks when told so""" 62 | output = self.run_pyobfuscate("testfiles/commblanks.py", 63 | args=["--keepblanks"]) 64 | lines = output.split("\n") 65 | assert '' == lines[5], "Blank lines removed" 66 | assert 42 == self.run_src(output) 67 | 68 | def test_lambdaGlobal(self): 69 | """Support lambda constructs referencing global functions. 70 | Test inspired by log message for revision 1.15""" 71 | assert 42 == self.obfuscate_and_run_file("testfiles/lambda_global.py"), "Incorrect value returned after obfuscation" 72 | 73 | def test_power(self): 74 | """Handle power operator correctly. Bug 1411""" 75 | assert 4 == self.obfuscate_and_run_file("testfiles/power.py"), "Incorrect value returned after obfuscation" 76 | 77 | def test_keywordfunc(self): 78 | """Handle keyword functions correctly. 79 | Test inspired by revision 1.8 and revision 1.9""" 80 | assert 42 == self.obfuscate_and_run_file("testfiles/keywordfunc.py"), "Incorrect value returned after obfuscation" 81 | 82 | def test_importlist(self): 83 | """Handle from import """ 84 | self.obfuscate_and_write("testfiles/tobeimported.py", 85 | "generated/tobeimported.py") 86 | self.obfuscate_and_write("testfiles/import.py", 87 | "generated/import.py") 88 | assert 42 == subprocess.call([sys.executable, "generated/import.py"]), "Incorrect value returned after obfuscation" 89 | 90 | def test_import_package(self): 91 | """Handle from x.y import z""" 92 | self.obfuscate_and_write("testfiles/package/tobeimported.py", 93 | "generated/package/tobeimported.py") 94 | self.obfuscate_and_write("testfiles/package/__init__.py", 95 | "generated/package/__init__.py") 96 | 97 | self.obfuscate_and_write("testfiles/importpackage.py", 98 | "generated/importpackage.py") 99 | assert 42 == subprocess.call([sys.executable, 100 | "generated/importpackage.py"], 101 | env={"PYTHONPATH":"generated"}), "Incorrect value returned after obfuscation" 102 | 103 | def test_import_package_as(self): 104 | """Handle from x.y import z as a""" 105 | self.obfuscate_and_write("testfiles/package/tobeimported.py", 106 | "generated/package/tobeimported.py") 107 | self.obfuscate_and_write("testfiles/package/__init__.py", 108 | "generated/package/__init__.py") 109 | 110 | self.obfuscate_and_write("testfiles/importpackage_as.py", 111 | "generated/importpackage_as.py") 112 | assert 42 == subprocess.call([sys.executable, 113 | "generated/importpackage_as.py"], 114 | env={"PYTHONPATH":"generated"}), "Incorrect value returned after obfuscation" 115 | 116 | def test_import_everything(self): 117 | self.obfuscate_and_write("testfiles/tobeimported_everything.py", 118 | "generated/tobeimported_everything.py") 119 | self.obfuscate_and_write("testfiles/importall_star.py", 120 | "generated/importall_star.py") 121 | assert 42 == subprocess.call([sys.executable, "generated/importall_star.py"]), "Incorrect value returned after obfuscation" 122 | 123 | def test_import_dyn_all(self): 124 | """Verify that trying to import from a file with dynamic __all__ fails""" 125 | cmdline = ["../pyobfuscate", "testfiles/dyn_all.py"] 126 | p = subprocess.Popen(cmdline, 127 | stdout=subprocess.PIPE, 128 | stderr=subprocess.PIPE) 129 | (stdout, stderr) = p.communicate() 130 | assert -1 != stderr.find("__all__ is not a list of constants"), "pyobufscate didn't bail out with an error on file with dynamic __all__" 131 | 132 | def test_import_with_keywords(self): 133 | """Verify that an imported class, defined in __all__, does not get obfuscated keyword arguments""" 134 | self.obfuscate_and_write("testfiles/keywordclass.py", 135 | "generated/keywordclass.py") 136 | self.obfuscate_and_write("testfiles/keywordclassuser.py", 137 | "generated/keywordclassuser.py") 138 | assert 42 == subprocess.call([sys.executable, "generated/keywordclassuser.py"]), "Incorrect value returned after obfuscation" 139 | 140 | def test_global_stmt(self): 141 | """Verify use of 'global' keyword""" 142 | assert 42 == self.obfuscate_and_run_file("testfiles/global.py"), "Incorrect value returned after obfuscation" 143 | 144 | def test_definition_after_use(self): 145 | """Verify that a function defined after it's used works as expected""" 146 | output = self.run_pyobfuscate("testfiles/defafteruse.py") 147 | assert 42 == self.run_src(output), "Incorrect value returned after obfuscation" 148 | 149 | def test_bug1583(self): 150 | """Verify that bug 1583 is not present (lambda obfuscation problems)""" 151 | output = self.run_pyobfuscate("testfiles/bug1583.py") 152 | assert 42 == self.run_src(output), "Incorrect value returned after obfuscation" 153 | 154 | def test_bug1673(self): 155 | """Verify that bug 1673 is not present (global variable handling)""" 156 | output = self.run_pyobfuscate("testfiles/bug1673.py") 157 | assert 49 == self.run_src(output), "Incorrect value returned after obfuscation" 158 | 159 | 160 | 161 | 162 | if "__main__" == __name__: 163 | unittest.main() 164 | -------------------------------------------------------------------------------- /test/testfiles/.cvsignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /test/testfiles/bug1583.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | def foo(bar): 5 | return sum(map(lambda x: x+bar, [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 == locals().has_key("colliding") 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 | 2 | import sys 3 | 4 | def sort(x, y): 5 | return cmp(x,y) 6 | 7 | def main(): 8 | l = [120,300,42] 9 | l.sort(lambda x, y: sort(x, y)) 10 | return l[0] 11 | 12 | 13 | if "__main__" == __name__: 14 | sys.exit(main()) 15 | -------------------------------------------------------------------------------- /test/testfiles/package/.cvsignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -------------------------------------------------------------------------------- /test/testfiles/package/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/byt3bl33d3r/pyobfuscate/1c3cbda38813bb7656d41b02b2b4e4bbeddf4f5c/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 | --------------------------------------------------------------------------------