PGP/GPG Signed Python code

六月ゝ 毕业季﹏ 提交于 2019-11-30 07:07:46

Python's import mechanism already provide all the tools necessary to achieve what you want. You can install different kinds of import hooks in order to support what you want.

In particular you'll probably find convenient to install a meta path hook that searches for "signed modules" and returns a Loader that is able to perform the imports from this signed format.

A very simple and convenient format for your signed plug-ins would be a zip archive containing:

  1. The code of the plug-in in the form of modules/packages
  2. A PGP signature of the above code

In this way:

  • Your loader should unpack the zip, and check the signature. If it matches then you can safely load the plug-in, if it doesn't match you should ask the user to trust the plug-in (or not and abort)
  • If the user wants to modify the plug-in it can simply unpack the zip archive and modify it as he wishes.
  • Imports from zip archives are already implemented in the zipimport module. This means that you don't have to rewrite a loader from scratch.

Actually if you want to reduce the code for the hooks to the minimum you'd simply need to verify the signature and then add the path to the zip archive into sys.path, since python already handles imports from zip archive even without explicitly using zipimport.

Using this design you just have to install these hooks and then you can import the plug-in as if they were normal modules and the verification etc. will be done automatically.

I know this is an old post, but we've developed a new solution. We were confronted with the same challenge -- to distribute python source code, but to prevent hackers from tampering with the code. The solution we developed was to create a custom loader for our application using signet http://jamercee.github.io/signet/.

What signet does is scans your script and it's dependencies creating sha1 hashes. It embeds these hashes into a custom loader which you deliver to your customer with your script. Your customers run the loader which re-verifies the hashes before it transfers control to your script for normal execution. If there's been tampering it emits an error message, and refuses to run the tampered code.

Signet is multiplatform and runs on windows, unix, linux, freebsd, etc... If you deploy to windows, the loader building process can even apply your company code certificate for 100% verification of your code. It also does PE verification.

The code is fully open source including the c++ source code to the default loader template. You can extend the loader to do additional verifications and even take actions if it detects code tampering (like undoing the tampering...).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!