From 06144a9898c6b1408f70b119078ee848a02d713f Mon Sep 17 00:00:00 2001 From: "Phillip J. Wolfram" Date: Thu, 2 Feb 2017 13:37:35 -0700 Subject: [PATCH] Increased safety for config file with numpy eval Prevents use of system built in variables by restricting string to exclude `__` for use in numpy evaluation. --- mpas_analysis/configuration/MpasAnalysisConfigParser.py | 7 ++++++- mpas_analysis/test/test_mpas_config_parser.py | 2 ++ mpas_analysis/test/test_mpas_config_parser/config.analysis | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/mpas_analysis/configuration/MpasAnalysisConfigParser.py b/mpas_analysis/configuration/MpasAnalysisConfigParser.py index 63c2dad98..fb9b484ed 100644 --- a/mpas_analysis/configuration/MpasAnalysisConfigParser.py +++ b/mpas_analysis/configuration/MpasAnalysisConfigParser.py @@ -66,7 +66,12 @@ def getExpression(self, section, option, elementType=None, usenumpyfunc=False): """ expressionString = self.get(section, option) if usenumpyfunc: - sanitizedstr = expressionString.replace('np.', '').replace('numpy.','') + assert '__' not in expressionString, \ + "'__' is not allowed in {} "\ + "for `usenumpyfunc=True`".format(expressionString) + sanitizedstr = expressionString.replace('np.', '')\ + .replace('numpy.','')\ + .replace('__','') result = eval(sanitizedstr, npallow) else: result = ast.literal_eval(expressionString) diff --git a/mpas_analysis/test/test_mpas_config_parser.py b/mpas_analysis/test/test_mpas_config_parser.py index 0365dbdeb..4865e9a22 100644 --- a/mpas_analysis/test/test_mpas_config_parser.py +++ b/mpas_analysis/test/test_mpas_config_parser.py @@ -79,5 +79,7 @@ def test_read_config_numpy(self): np.linspace(0, 1, 10)) for testNumpy in ['testNumpypi' + str(ii) for ii in np.arange(3)] + ['testNumpyPi']: self.assertEqual(self.config.getExpression('TestNumpy', testNumpy, usenumpyfunc=True), np.pi) + with self.assertRaisesRegexp(AssertionError, "'__' is not allowed in .* for `usenumpyfunc=True`"): + self.config.getExpression('TestNumpy', 'testBadStr', usenumpyfunc=True), # vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python diff --git a/mpas_analysis/test/test_mpas_config_parser/config.analysis b/mpas_analysis/test/test_mpas_config_parser/config.analysis index 2fd5ed0cb..583bb48ee 100644 --- a/mpas_analysis/test/test_mpas_config_parser/config.analysis +++ b/mpas_analysis/test/test_mpas_config_parser/config.analysis @@ -43,3 +43,4 @@ testNumpypi0 = pi testNumpypi1 = np.pi testNumpypi2 = numpy.pi testNumpyPi = Pi +testBadStr = __bad_string__