Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.21 KB | None | 0 0
  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2015 David Wison (original code)
  4. # Copyright (c) 2019 Moshe Malawach (modified for smart contract use)
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. # THE SOFTWARE.
  23. import ctypes
  24. import json
  25. import os
  26. import resource
  27. import signal
  28. import socket
  29. import struct
  30. from multiprocessing import Process
  31. from RestrictedPython import (compile_restricted, safe_builtins,
  32. utility_builtins)
  33.  
  34. builtins = {**safe_builtins, **utility_builtins}
  35. #builtins['__metaclass__'] = type
  36. builtins['__name__'] = "SC"
  37. del builtins['random']
  38. del builtins['whrandom']
  39. _libc = ctypes.CDLL(None)
  40. _exit = _libc._exit
  41. _prctl = _libc.prctl
  42. PR_SET_SECCOMP = 22
  43. SECCOMP_MODE_STRICT = 1
  44.  
  45.  
  46. def enable_seccomp():
  47. rc = _prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT, 0)
  48. assert rc == 0
  49.  
  50.  
  51. def read_exact(fp, n):
  52. buf = b''
  53. while len(buf) < n:
  54. buf2 = os.read(fp.fileno(), n)
  55. if not buf2:
  56. _exit(123)
  57. buf += buf2
  58. return buf2
  59.  
  60.  
  61. def write_exact(fp, s):
  62. done = 0
  63. while done < len(s):
  64. written = os.write(fp.fileno(), s[done:])
  65. if not written:
  66. _exit(123)
  67. done += written
  68.  
  69.  
  70. class SecureEvalHost(object):
  71. def __init__(self):
  72. self.host, self.child = socket.socketpair()
  73. self.pid = None
  74.  
  75. def start_child(self):
  76. assert not self.pid
  77. self.pid = os.fork()
  78. if not self.pid:
  79. self._child_main()
  80. self.child.close()
  81.  
  82. def kill_child(self):
  83. assert self.pid
  84. pid, status = os.waitpid(self.pid, os.WNOHANG)
  85. os.kill(self.pid, signal.SIGKILL)
  86.  
  87. def do_eval(self, msg):
  88. return {'result': eval(msg['body'])}
  89.  
  90. def _do_exec(self, msg):
  91. locs = {}
  92. globs = {'__builtins__': builtins}
  93. byte_code = compile(msg['body'], '<restricted-python>', 'exec')
  94. exec(byte_code, globs, locs)
  95. return locs
  96.  
  97. def do_exec_func(self, msg):
  98. try:
  99. locs = self._do_exec(msg)
  100. except Exception as e:
  101. return {'error': repr(e), 'error_step': 'prepare', 'result': None}
  102.  
  103. try:
  104. result = locs[msg['func']](*msg['args'], **msg['kwargs'])
  105. return {'result': result}
  106. except Exception as e:
  107. return {'error': repr(e), 'error_step': 'call', 'result': None}
  108.  
  109. def do_construct(self, msg):
  110. try:
  111. locs = self._do_exec(msg)
  112. except Exception as e:
  113. return {'error': repr(e), 'error_step': 'prepare', 'result': None}
  114.  
  115. try:
  116. item_class = locs['SmartContract']
  117. obj = item_class(*msg['args'], **msg['kwargs'])
  118. return {'result': True, 'state': obj.__dict__}
  119. except Exception as e:
  120. return {'error': repr(e), 'error_step': 'call', 'result': None}
  121.  
  122. def do_call(self, msg):
  123. try:
  124. locs = self._do_exec(msg)
  125. except Exception as e:
  126. return {'error': repr(e), 'error_step': 'prepare', 'result': None}
  127.  
  128. try:
  129. item_class = locs['SmartContract']
  130. instance = item_class.__new__(item_class)
  131. instance.__dict__ = msg['state']
  132. result = getattr(instance, msg['func'])(*msg['args'],
  133. **msg['kwargs'])
  134. return {'result': result, 'state': instance.__dict__}
  135. except Exception as e:
  136. return {'error': repr(e), 'error_step': 'call', 'result': None}
  137.  
  138. def _child_main(self):
  139. self.host.close()
  140. for fd in map(int, os.listdir('/proc/self/fd')):
  141. try:
  142. if fd != self.child.fileno():
  143. os.close(fd)
  144. except OSError:
  145. pass
  146. resource.setrlimit(resource.RLIMIT_CPU, (1, 1))
  147. soft, hard = resource.getrlimit(resource.RLIMIT_AS)
  148. resource.setrlimit(resource.RLIMIT_AS, (64 * 1024, 128 * 1024))
  149. soft, hard = resource.getrlimit(resource.RLIMIT_AS)
  150. print(soft, hard)
  151.  
  152. enable_seccomp()
  153. while True:
  154. sz, = struct.unpack('>L', read_exact(self.child, 4))
  155. doc = json.loads(read_exact(self.child, sz))
  156. try:
  157. if doc['cmd'] == 'eval':
  158. resp = self.do_eval(doc)
  159. elif doc['cmd'] == 'exec_func':
  160. resp = self.do_exec_func(doc)
  161. elif doc['cmd'] == 'construct':
  162. resp = self.do_construct(doc)
  163. elif doc['cmd'] == 'call':
  164. resp = self.do_call(doc)
  165. elif doc['cmd'] == 'exit':
  166. _exit(0)
  167. except Exception as e:
  168. resp = {'error': repr(e), 'error_step': 'unhandled',
  169. 'result': None}
  170. goobs = json.dumps(resp)
  171. write_exact(self.child, struct.pack('>L', len(goobs)))
  172. write_exact(self.child, goobs.encode('utf-8'))
  173.  
  174. def eval(self, s):
  175. msg = json.dumps({'cmd': 'eval', 'body': s})
  176. write_exact(self.host, struct.pack('>L', len(msg)))
  177. write_exact(self.host, msg.encode('utf-8'))
  178. sz, = struct.unpack('>L', read_exact(self.host, 4))
  179. goobs = json.loads(read_exact(self.host, sz).decode('utf-8'))
  180. return goobs['result']
  181.  
  182. def exec_func(self, s, func, *args, **kwargs):
  183. msg = json.dumps({'cmd': 'exec_func', 'body': s,
  184. 'func': func, 'args': args,
  185. 'kwargs': kwargs})
  186. write_exact(self.host, struct.pack('>L', len(msg)))
  187. write_exact(self.host, msg.encode('utf-8'))
  188. sz, = struct.unpack('>L', read_exact(self.host, 4))
  189. goobs = json.loads(read_exact(self.host, sz).decode('utf-8'))
  190. return goobs
  191.  
  192. def construct(self, s, args, kwargs={}):
  193. msg = json.dumps({'cmd': 'construct', 'body': s,
  194. 'args': args,
  195. 'kwargs': kwargs})
  196. write_exact(self.host, struct.pack('>L', len(msg)))
  197. write_exact(self.host, msg.encode('utf-8'))
  198. sz, = struct.unpack('>L', read_exact(self.host, 4))
  199. goobs = json.loads(read_exact(self.host, sz).decode('utf-8'))
  200. return goobs
  201.  
  202. def call(self, s, func, state, args, kwargs={}):
  203. msg = json.dumps({'cmd': 'call', 'body': s, 'state': state,
  204. 'func': func, 'args': args,
  205. 'kwargs': kwargs})
  206. write_exact(self.host, struct.pack('>L', len(msg)))
  207. write_exact(self.host, msg.encode('utf-8'))
  208. sz, = struct.unpack('>L', read_exact(self.host, 4))
  209. goobs = json.loads(read_exact(self.host, sz).decode('utf-8'))
  210. return goobs
  211.  
  212.  
  213.  
  214. def go():
  215. insecure_code = open('token_class.py', 'r').read()
  216. sec = SecureEvalHost()
  217. sec.start_child()
  218. try:
  219. print(sec.eval('1+100'))
  220. res = sec.construct(insecure_code, [{'from': '0xblah'}, 'Test Token', 'TST', 1000])
  221. print(res)
  222. res = sec.call(insecure_code, 'transfer', res['state'],
  223. [{'from': '0xblah'}, "0xbluh", 2])
  224. print(res)
  225. res = sec.call(insecure_code, 'transfer', res['state'],
  226. [{'from': '0xbluh'}, "0xblih", 3])
  227. print(res)
  228.  
  229. except:
  230. print("error in process")
  231.  
  232. finally:
  233. sec.kill_child()
  234. print("finished")
  235.  
  236.  
  237. if __name__ == '__main__':
  238. go()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement