forked from goatpig/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamicImport.py
217 lines (179 loc) · 8.17 KB
/
dynamicImport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
################################################################################
# #
# Copyright (C) 2011-2015, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
################################################################################
import os
import sys
from armoryengine.ArmoryUtils import *
from zipfile import ZipFile
from CppBlockUtils import SecureBinaryData, CryptoECDSA
PY_EXTENSION = '.py'
ZIP_EXTENSION = '.zip'
SIG_EXTENSION = '.sig'
INNER_ZIP_FILENAME = 'inner.zip'
PROPERTIES_FILENAME = 'properties.txt'
SIGNATURE_FILENAME = 'signature.txt'
MODULE_PATH_KEY = 'ModulePath'
MODULE_ZIP_STATUS_KEY = 'ModulZipStatus'
MODULE_ZIP_STATUS = enum("Valid", 'Invalid', 'Unsigned')
# Module structure:
# moduleName.zip (outer zip file):
# inner.zip (inner zip file with the same name)
# moduleName.py (python module file
# <resources> (some files that are resources for the module)
# properties.txt (signature properties like valid date range)
# signature.txt (signature of the inner zip file)
def verifyZipSignature(outerZipFilePath):
result = MODULE_ZIP_STATUS.Invalid
try:
dataToSign = None
signature = None
outerZipFile = ZipFile(outerZipFilePath)
# look for a zip file in the name list.
# There should only be 2 files in this zip:
# The inner zip file and the sig file
if len(outerZipFile.namelist()) == 3:
dataToSign = sha256(sha256(outerZipFile.read(INNER_ZIP_FILENAME)) +
sha256(outerZipFile.read(PROPERTIES_FILENAME)))
signature = outerZipFile.read(SIGNATURE_FILENAME)
if dataToSign and signature:
"""
Signature file contains multiple lines, of the form "key=value\n"
The last line is the hex-encoded signature, which is over the
source code + everything in the sig file up to the last line.
The key-value lines may contain properties such as signature
validity times/expiration, contact info of author, etc.
"""
dataToSignSBD = SecureBinaryData(dataToSign)
sigSBD = SecureBinaryData(hex_to_binary(signature.strip()))
publicKeySBD = SecureBinaryData(hex_to_binary(ARMORY_INFO_SIGN_PUBLICKEY))
result = MODULE_ZIP_STATUS.Valid if CryptoECDSA().VerifyData(dataToSignSBD, sigSBD, publicKeySBD) else \
MODULE_ZIP_STATUS.Unsigned
except:
# if anything goes wrong an invalid zip file indicator will get returned
pass
return result
# TODO - Write this method - currently this just a place holder
# with comments on how to implement the required functionality
def signZipFile(zipFilePath, propertiesDictionary=None):
if propertiesDictionary:
# Create an empty properties file
pass
# if it's a string treat it like a file name and open it
# else if ti's a dictionary save it to a file and use that.
# Read the contents of the Zip File and the properties file
zipFileData = None
propertiesFileData = None
dataToSign = sha256(sha256(zipFileData) + sha256(propertiesFileData))
dataToSignSBD = SecureBinaryData(dataToSign)
# get the privKeySBD
privKeySBD = None
signature = CryptoECDSA().SignData(dataToSignSBD, privKeySBD, ENABLE_DETSIGN)
# Write the Signature to signature.txt
# rename the source Zip file to inner.zip
# Create a new Zip File with the original name of the source zip file
# add to the zip file inner.zip, properties.txt, and signature.txt
def getModuleList(zipDir):
moduleMap = {}
if os.path.exists(zipDir):
for fileName in os.listdir(zipDir):
if fileName.endswith(ZIP_EXTENSION):
try:
moduleName = fileName.split('.')[0]
if not moduleName in moduleMap:
moduleMap[moduleName] = {}
moduleZipPath = os.path.join(zipDir, fileName)
moduleMap[moduleName][MODULE_ZIP_STATUS_KEY] = verifyZipSignature(moduleZipPath)
moduleMap[moduleName][MODULE_PATH_KEY] = moduleZipPath
except:
moduleMap[moduleName][MODULE_PATH_KEY] = MODULE_ZIP_STATUS.Invalid
LOGEXCEPT('Exception while loading plugin %s.' % moduleName)
return moduleMap
def importModule(modulesDir, moduleName, injectLocals=None):
"""
We import from an arbitrary directory, we need to add the dir
to sys.path, but we want to prevent any shenanigans by an imported
module that messes with sys.path (perhaps maliciously, but trying
to import a malicious module without allowing malicious behavior
is probably impossible--make sure you're using safe code and then
assume the module is safe).
Either way, we're going to assume that the dynamically-imported
modules are really simple and have no reason to mess with sys.path.
We will revisit this later if it becomes a barrier to being useful
"""
if injectLocals is None:
injectLocals = {}
pluginPath = os.path.join(modulesDir, moduleName+'.py')
if not os.path.exists(pluginPath):
return None
# Join using a character that would be invalid in a pathname
prevSysPath = '\x00'.join(sys.path)
sys.path.append(modulesDir)
modTemp = __import__(moduleName)
modTemp.__dict__.update(injectLocals)
# Assume that sys.path was unmodified by the module
sys.path = sys.path[:-1]
currSysPath = '\x00'.join(sys.path)
if not currSysPath==prevSysPath:
print '***ERROR: Dynamically imported module messed with sys.path!'
print ' : Make sure your module does not modify sys.path'
exit(1)
return modTemp
############################################################################
def getModuleListNoZip(inDir):
moduleMap = {}
if not os.path.exists(inDir):
return moduleMap
for fn in os.listdir(inDir):
if not fn.endswith('.py') and not fn.endswith('.sig'):
continue
try:
modName = fn.split('.')[0]
fullfn = os.path.join(inDir, fn)
with open(fullfn, 'r') as f:
fileData = f.read()
if not modName in moduleMap:
moduleMap[modName] = {}
if fn.endswith('.py'):
moduleMap[modName]['SourceCode'] = fileData
moduleMap[modName]['SourceDir'] = inDir
moduleMap[modName]['Filename'] = fn
elif fn.endswith('.sig'):
moduleMap[modName]['SigData'] = fileData
except:
LOGEXCEPT('Loading plugin %s failed. Skipping' % fullfn)
return moduleMap
############################################################################
def dynamicImportNoZip(inDir, moduleName, injectLocals=None):
"""
We import from an arbitrary directory, we need to add the dir
to sys.path, but we want to prevent any shenanigans by an imported
module that messes with sys.path (perhaps maliciously, but trying
to import a malicious module without allowing malicious behavior
is probably impossible--make sure you're using safe code and then
assume the module is safe).
Either way, we're going to assume that the dynamically-imported
modules are really simple and have no reason to mess with sys.path.
We will revisit this later if it becomes a barrier to being useful
"""
if injectLocals is None:
injectLocals = {}
pluginPath = os.path.join(inDir, moduleName+'.py')
if not os.path.exists(pluginPath):
return None
# Join using a character that would be invalid in a pathname
prevSysPath = '\x00'.join(sys.path)
sys.path.append(inDir)
modTemp = __import__(moduleName)
modTemp.__dict__.update(injectLocals)
# Assume that sys.path was unmodified by the module
sys.path = sys.path[:-1]
currSysPath = '\x00'.join(sys.path)
if not currSysPath==prevSysPath:
print '***ERROR: Dynamically imported module messed with sys.path!'
print ' : Make sure your module does not modify sys.path'
exit(1)
return modTemp