diff options
author | Jacob Austin Lincoln <99031153+lincolnj1@users.noreply.github.com> | 2025-02-23 08:06:33 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-02-23 11:06:33 -0500 |
commit | 25a7ddf2efeaf77bcf94dbfca28ba3a6fe9ab57e (patch) | |
tree | 1e4c59ae665d4f14e4e714ede90375a79a30383c /Lib/configparser.py | |
parent | 1e4a4344af4f5fdc7157b195c7d333d088540035 (diff) | |
download | cpython-25a7ddf2efeaf77bcf94dbfca28ba3a6fe9ab57e.tar.gz cpython-25a7ddf2efeaf77bcf94dbfca28ba3a6fe9ab57e.zip |
gh-65697: Prevent configparser from writing keys it cannot properly read (#129270)
---------
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
Diffstat (limited to 'Lib/configparser.py')
-rw-r--r-- | Lib/configparser.py | 19 |
1 files changed, 18 insertions, 1 deletions
diff --git a/Lib/configparser.py b/Lib/configparser.py index 9ff52e03c2c..462af2f4abf 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -161,7 +161,7 @@ __all__ = ("NoSectionError", "DuplicateOptionError", "DuplicateSectionError", "InterpolationMissingOptionError", "InterpolationSyntaxError", "ParsingError", "MissingSectionHeaderError", "MultilineContinuationError", "UnnamedSectionDisabledError", - "ConfigParser", "RawConfigParser", + "InvalidWriteError", "ConfigParser", "RawConfigParser", "Interpolation", "BasicInterpolation", "ExtendedInterpolation", "SectionProxy", "ConverterMapping", "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH", "UNNAMED_SECTION") @@ -375,6 +375,14 @@ class _UnnamedSection: def __repr__(self): return "<UNNAMED_SECTION>" +class InvalidWriteError(Error): + """Raised when attempting to write data that the parser would read back differently. + ex: writing a key which begins with the section header pattern would read back as a + new section """ + + def __init__(self, msg=''): + Error.__init__(self, msg) + UNNAMED_SECTION = _UnnamedSection() @@ -973,6 +981,7 @@ class RawConfigParser(MutableMapping): if not unnamed: fp.write("[{}]\n".format(section_name)) for key, value in section_items: + self._validate_key_contents(key) value = self._interpolation.before_write(self, section_name, key, value) if value is not None or not self._allow_no_value: @@ -1210,6 +1219,14 @@ class RawConfigParser(MutableMapping): raise ValueError('Not a boolean: %s' % value) return self.BOOLEAN_STATES[value.lower()] + def _validate_key_contents(self, key): + """Raises an InvalidWriteError for any keys containing + delimiters or that match the section header pattern""" + if re.match(self.SECTCRE, key): + raise InvalidWriteError("Cannot write keys matching section pattern") + if any(delim in key for delim in self._delimiters): + raise InvalidWriteError("Cannot write key that contains delimiters") + def _validate_value_types(self, *, section="", option="", value=""): """Raises a TypeError for illegal non-string values. |