sandbox.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import os
  2. import sys
  3. import tempfile
  4. import operator
  5. import functools
  6. import itertools
  7. import re
  8. import contextlib
  9. import pickle
  10. import textwrap
  11. import builtins
  12. import pkg_resources
  13. from distutils.errors import DistutilsError
  14. from pkg_resources import working_set
  15. if sys.platform.startswith('java'):
  16. import org.python.modules.posix.PosixModule as _os
  17. else:
  18. _os = sys.modules[os.name]
  19. try:
  20. _file = file
  21. except NameError:
  22. _file = None
  23. _open = open
  24. __all__ = [
  25. "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",
  26. ]
  27. def _execfile(filename, globals, locals=None):
  28. """
  29. Python 3 implementation of execfile.
  30. """
  31. mode = 'rb'
  32. with open(filename, mode) as stream:
  33. script = stream.read()
  34. if locals is None:
  35. locals = globals
  36. code = compile(script, filename, 'exec')
  37. exec(code, globals, locals)
  38. @contextlib.contextmanager
  39. def save_argv(repl=None):
  40. saved = sys.argv[:]
  41. if repl is not None:
  42. sys.argv[:] = repl
  43. try:
  44. yield saved
  45. finally:
  46. sys.argv[:] = saved
  47. @contextlib.contextmanager
  48. def save_path():
  49. saved = sys.path[:]
  50. try:
  51. yield saved
  52. finally:
  53. sys.path[:] = saved
  54. @contextlib.contextmanager
  55. def override_temp(replacement):
  56. """
  57. Monkey-patch tempfile.tempdir with replacement, ensuring it exists
  58. """
  59. os.makedirs(replacement, exist_ok=True)
  60. saved = tempfile.tempdir
  61. tempfile.tempdir = replacement
  62. try:
  63. yield
  64. finally:
  65. tempfile.tempdir = saved
  66. @contextlib.contextmanager
  67. def pushd(target):
  68. saved = os.getcwd()
  69. os.chdir(target)
  70. try:
  71. yield saved
  72. finally:
  73. os.chdir(saved)
  74. class UnpickleableException(Exception):
  75. """
  76. An exception representing another Exception that could not be pickled.
  77. """
  78. @staticmethod
  79. def dump(type, exc):
  80. """
  81. Always return a dumped (pickled) type and exc. If exc can't be pickled,
  82. wrap it in UnpickleableException first.
  83. """
  84. try:
  85. return pickle.dumps(type), pickle.dumps(exc)
  86. except Exception:
  87. # get UnpickleableException inside the sandbox
  88. from setuptools.sandbox import UnpickleableException as cls
  89. return cls.dump(cls, cls(repr(exc)))
  90. class ExceptionSaver:
  91. """
  92. A Context Manager that will save an exception, serialized, and restore it
  93. later.
  94. """
  95. def __enter__(self):
  96. return self
  97. def __exit__(self, type, exc, tb):
  98. if not exc:
  99. return
  100. # dump the exception
  101. self._saved = UnpickleableException.dump(type, exc)
  102. self._tb = tb
  103. # suppress the exception
  104. return True
  105. def resume(self):
  106. "restore and re-raise any exception"
  107. if '_saved' not in vars(self):
  108. return
  109. type, exc = map(pickle.loads, self._saved)
  110. raise exc.with_traceback(self._tb)
  111. @contextlib.contextmanager
  112. def save_modules():
  113. """
  114. Context in which imported modules are saved.
  115. Translates exceptions internal to the context into the equivalent exception
  116. outside the context.
  117. """
  118. saved = sys.modules.copy()
  119. with ExceptionSaver() as saved_exc:
  120. yield saved
  121. sys.modules.update(saved)
  122. # remove any modules imported since
  123. del_modules = (
  124. mod_name for mod_name in sys.modules
  125. if mod_name not in saved
  126. # exclude any encodings modules. See #285
  127. and not mod_name.startswith('encodings.')
  128. )
  129. _clear_modules(del_modules)
  130. saved_exc.resume()
  131. def _clear_modules(module_names):
  132. for mod_name in list(module_names):
  133. del sys.modules[mod_name]
  134. @contextlib.contextmanager
  135. def save_pkg_resources_state():
  136. saved = pkg_resources.__getstate__()
  137. try:
  138. yield saved
  139. finally:
  140. pkg_resources.__setstate__(saved)
  141. @contextlib.contextmanager
  142. def setup_context(setup_dir):
  143. temp_dir = os.path.join(setup_dir, 'temp')
  144. with save_pkg_resources_state():
  145. with save_modules():
  146. with save_path():
  147. hide_setuptools()
  148. with save_argv():
  149. with override_temp(temp_dir):
  150. with pushd(setup_dir):
  151. # ensure setuptools commands are available
  152. __import__('setuptools')
  153. yield
  154. _MODULES_TO_HIDE = {
  155. 'setuptools',
  156. 'distutils',
  157. 'pkg_resources',
  158. 'Cython',
  159. '_distutils_hack',
  160. }
  161. def _needs_hiding(mod_name):
  162. """
  163. >>> _needs_hiding('setuptools')
  164. True
  165. >>> _needs_hiding('pkg_resources')
  166. True
  167. >>> _needs_hiding('setuptools_plugin')
  168. False
  169. >>> _needs_hiding('setuptools.__init__')
  170. True
  171. >>> _needs_hiding('distutils')
  172. True
  173. >>> _needs_hiding('os')
  174. False
  175. >>> _needs_hiding('Cython')
  176. True
  177. """
  178. base_module = mod_name.split('.', 1)[0]
  179. return base_module in _MODULES_TO_HIDE
  180. def hide_setuptools():
  181. """
  182. Remove references to setuptools' modules from sys.modules to allow the
  183. invocation to import the most appropriate setuptools. This technique is
  184. necessary to avoid issues such as #315 where setuptools upgrading itself
  185. would fail to find a function declared in the metadata.
  186. """
  187. _distutils_hack = sys.modules.get('_distutils_hack', None)
  188. if _distutils_hack is not None:
  189. _distutils_hack.remove_shim()
  190. modules = filter(_needs_hiding, sys.modules)
  191. _clear_modules(modules)
  192. def run_setup(setup_script, args):
  193. """Run a distutils setup script, sandboxed in its directory"""
  194. setup_dir = os.path.abspath(os.path.dirname(setup_script))
  195. with setup_context(setup_dir):
  196. try:
  197. sys.argv[:] = [setup_script] + list(args)
  198. sys.path.insert(0, setup_dir)
  199. # reset to include setup dir, w/clean callback list
  200. working_set.__init__()
  201. working_set.callbacks.append(lambda dist: dist.activate())
  202. with DirectorySandbox(setup_dir):
  203. ns = dict(__file__=setup_script, __name__='__main__')
  204. _execfile(setup_script, ns)
  205. except SystemExit as v:
  206. if v.args and v.args[0]:
  207. raise
  208. # Normal exit, just return
  209. class AbstractSandbox:
  210. """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
  211. _active = False
  212. def __init__(self):
  213. self._attrs = [
  214. name for name in dir(_os)
  215. if not name.startswith('_') and hasattr(self, name)
  216. ]
  217. def _copy(self, source):
  218. for name in self._attrs:
  219. setattr(os, name, getattr(source, name))
  220. def __enter__(self):
  221. self._copy(self)
  222. if _file:
  223. builtins.file = self._file
  224. builtins.open = self._open
  225. self._active = True
  226. def __exit__(self, exc_type, exc_value, traceback):
  227. self._active = False
  228. if _file:
  229. builtins.file = _file
  230. builtins.open = _open
  231. self._copy(_os)
  232. def run(self, func):
  233. """Run 'func' under os sandboxing"""
  234. with self:
  235. return func()
  236. def _mk_dual_path_wrapper(name):
  237. original = getattr(_os, name)
  238. def wrap(self, src, dst, *args, **kw):
  239. if self._active:
  240. src, dst = self._remap_pair(name, src, dst, *args, **kw)
  241. return original(src, dst, *args, **kw)
  242. return wrap
  243. for name in ["rename", "link", "symlink"]:
  244. if hasattr(_os, name):
  245. locals()[name] = _mk_dual_path_wrapper(name)
  246. def _mk_single_path_wrapper(name, original=None):
  247. original = original or getattr(_os, name)
  248. def wrap(self, path, *args, **kw):
  249. if self._active:
  250. path = self._remap_input(name, path, *args, **kw)
  251. return original(path, *args, **kw)
  252. return wrap
  253. if _file:
  254. _file = _mk_single_path_wrapper('file', _file)
  255. _open = _mk_single_path_wrapper('open', _open)
  256. for name in [
  257. "stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir",
  258. "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat",
  259. "startfile", "mkfifo", "mknod", "pathconf", "access"
  260. ]:
  261. if hasattr(_os, name):
  262. locals()[name] = _mk_single_path_wrapper(name)
  263. def _mk_single_with_return(name):
  264. original = getattr(_os, name)
  265. def wrap(self, path, *args, **kw):
  266. if self._active:
  267. path = self._remap_input(name, path, *args, **kw)
  268. return self._remap_output(name, original(path, *args, **kw))
  269. return original(path, *args, **kw)
  270. return wrap
  271. for name in ['readlink', 'tempnam']:
  272. if hasattr(_os, name):
  273. locals()[name] = _mk_single_with_return(name)
  274. def _mk_query(name):
  275. original = getattr(_os, name)
  276. def wrap(self, *args, **kw):
  277. retval = original(*args, **kw)
  278. if self._active:
  279. return self._remap_output(name, retval)
  280. return retval
  281. return wrap
  282. for name in ['getcwd', 'tmpnam']:
  283. if hasattr(_os, name):
  284. locals()[name] = _mk_query(name)
  285. def _validate_path(self, path):
  286. """Called to remap or validate any path, whether input or output"""
  287. return path
  288. def _remap_input(self, operation, path, *args, **kw):
  289. """Called for path inputs"""
  290. return self._validate_path(path)
  291. def _remap_output(self, operation, path):
  292. """Called for path outputs"""
  293. return self._validate_path(path)
  294. def _remap_pair(self, operation, src, dst, *args, **kw):
  295. """Called for path pairs like rename, link, and symlink operations"""
  296. return (
  297. self._remap_input(operation + '-from', src, *args, **kw),
  298. self._remap_input(operation + '-to', dst, *args, **kw)
  299. )
  300. if hasattr(os, 'devnull'):
  301. _EXCEPTIONS = [os.devnull]
  302. else:
  303. _EXCEPTIONS = []
  304. class DirectorySandbox(AbstractSandbox):
  305. """Restrict operations to a single subdirectory - pseudo-chroot"""
  306. write_ops = dict.fromkeys([
  307. "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir",
  308. "utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam",
  309. ])
  310. _exception_patterns = [
  311. # Allow lib2to3 to attempt to save a pickled grammar object (#121)
  312. r'.*lib2to3.*\.pickle$',
  313. ]
  314. "exempt writing to paths that match the pattern"
  315. def __init__(self, sandbox, exceptions=_EXCEPTIONS):
  316. self._sandbox = os.path.normcase(os.path.realpath(sandbox))
  317. self._prefix = os.path.join(self._sandbox, '')
  318. self._exceptions = [
  319. os.path.normcase(os.path.realpath(path))
  320. for path in exceptions
  321. ]
  322. AbstractSandbox.__init__(self)
  323. def _violation(self, operation, *args, **kw):
  324. from setuptools.sandbox import SandboxViolation
  325. raise SandboxViolation(operation, args, kw)
  326. if _file:
  327. def _file(self, path, mode='r', *args, **kw):
  328. if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
  329. self._violation("file", path, mode, *args, **kw)
  330. return _file(path, mode, *args, **kw)
  331. def _open(self, path, mode='r', *args, **kw):
  332. if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
  333. self._violation("open", path, mode, *args, **kw)
  334. return _open(path, mode, *args, **kw)
  335. def tmpnam(self):
  336. self._violation("tmpnam")
  337. def _ok(self, path):
  338. active = self._active
  339. try:
  340. self._active = False
  341. realpath = os.path.normcase(os.path.realpath(path))
  342. return (
  343. self._exempted(realpath)
  344. or realpath == self._sandbox
  345. or realpath.startswith(self._prefix)
  346. )
  347. finally:
  348. self._active = active
  349. def _exempted(self, filepath):
  350. start_matches = (
  351. filepath.startswith(exception)
  352. for exception in self._exceptions
  353. )
  354. pattern_matches = (
  355. re.match(pattern, filepath)
  356. for pattern in self._exception_patterns
  357. )
  358. candidates = itertools.chain(start_matches, pattern_matches)
  359. return any(candidates)
  360. def _remap_input(self, operation, path, *args, **kw):
  361. """Called for path inputs"""
  362. if operation in self.write_ops and not self._ok(path):
  363. self._violation(operation, os.path.realpath(path), *args, **kw)
  364. return path
  365. def _remap_pair(self, operation, src, dst, *args, **kw):
  366. """Called for path pairs like rename, link, and symlink operations"""
  367. if not self._ok(src) or not self._ok(dst):
  368. self._violation(operation, src, dst, *args, **kw)
  369. return (src, dst)
  370. def open(self, file, flags, mode=0o777, *args, **kw):
  371. """Called for low-level os.open()"""
  372. if flags & WRITE_FLAGS and not self._ok(file):
  373. self._violation("os.open", file, flags, mode, *args, **kw)
  374. return _os.open(file, flags, mode, *args, **kw)
  375. WRITE_FLAGS = functools.reduce(
  376. operator.or_, [
  377. getattr(_os, a, 0) for a in
  378. "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()]
  379. )
  380. class SandboxViolation(DistutilsError):
  381. """A setup script attempted to modify the filesystem outside the sandbox"""
  382. tmpl = textwrap.dedent("""
  383. SandboxViolation: {cmd}{args!r} {kwargs}
  384. The package setup script has attempted to modify files on your system
  385. that are not within the EasyInstall build area, and has been aborted.
  386. This package cannot be safely installed by EasyInstall, and may not
  387. support alternate installation locations even if you run its setup
  388. script by hand. Please inform the package's author and the EasyInstall
  389. maintainers to find out if a fix or workaround is available.
  390. """).lstrip()
  391. def __str__(self):
  392. cmd, args, kwargs = self.args
  393. return self.tmpl.format(**locals())