Skip to content

Commit 412015e

Browse files
authored
Merge pull request #782 from python-babel/locale-basename
Clean locale identifiers before loading from file
2 parents 5afe2b2 + 5caf717 commit 412015e

2 files changed

Lines changed: 60 additions & 3 deletions

File tree

babel/localedata.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
"""
1414

1515
import os
16+
import re
17+
import sys
1618
import threading
1719
from itertools import chain
1820

@@ -22,6 +24,7 @@
2224
_cache = {}
2325
_cache_lock = threading.RLock()
2426
_dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
27+
_windows_reserved_name_re = re.compile("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", re.I)
2528

2629

2730
def normalize_locale(name):
@@ -38,6 +41,22 @@ def normalize_locale(name):
3841
return locale_id
3942

4043

44+
def resolve_locale_filename(name):
45+
"""
46+
Resolve a locale identifier to a `.dat` path on disk.
47+
"""
48+
49+
# Clean up any possible relative paths.
50+
name = os.path.basename(name)
51+
52+
# Ensure we're not left with one of the Windows reserved names.
53+
if sys.platform == "win32" and _windows_reserved_name_re.match(os.path.splitext(name)[0]):
54+
raise ValueError("Name %s is invalid on Windows" % name)
55+
56+
# Build the path.
57+
return os.path.join(_dirname, '%s.dat' % name)
58+
59+
4160
def exists(name):
4261
"""Check whether locale data is available for the given locale.
4362
@@ -49,7 +68,7 @@ def exists(name):
4968
return False
5069
if name in _cache:
5170
return True
52-
file_found = os.path.exists(os.path.join(_dirname, '%s.dat' % name))
71+
file_found = os.path.exists(resolve_locale_filename(name))
5372
return True if file_found else bool(normalize_locale(name))
5473

5574

@@ -102,6 +121,7 @@ def load(name, merge_inherited=True):
102121
:raise `IOError`: if no locale data file is found for the given locale
103122
identifer, or one of the locales it inherits from
104123
"""
124+
name = os.path.basename(name)
105125
_cache_lock.acquire()
106126
try:
107127
data = _cache.get(name)
@@ -119,7 +139,7 @@ def load(name, merge_inherited=True):
119139
else:
120140
parent = '_'.join(parts[:-1])
121141
data = load(parent).copy()
122-
filename = os.path.join(_dirname, '%s.dat' % name)
142+
filename = resolve_locale_filename(name)
123143
with open(filename, 'rb') as fileobj:
124144
if name != 'root' and merge_inherited:
125145
merge(data, pickle.load(fileobj))

tests/test_localedata.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,17 @@
1111
# individuals. For the exact contribution history, see the revision
1212
# history and logs, available at http://babel.edgewall.org/log/.
1313

14+
import os
15+
import pickle
16+
import sys
17+
import tempfile
1418
import unittest
1519
import random
1620
from operator import methodcaller
1721

18-
from babel import localedata
22+
import pytest
23+
24+
from babel import localedata, Locale, UnknownLocaleError
1925

2026

2127
class MergeResolveTestCase(unittest.TestCase):
@@ -131,3 +137,34 @@ def listdir_spy(*args):
131137
localedata.locale_identifiers.cache = None
132138
assert localedata.locale_identifiers()
133139
assert len(listdir_calls) == 2
140+
141+
142+
def test_locale_name_cleanup():
143+
"""
144+
Test that locale identifiers are cleaned up to avoid directory traversal.
145+
"""
146+
no_exist_name = os.path.join(tempfile.gettempdir(), "babel%d.dat" % random.randint(1, 99999))
147+
with open(no_exist_name, "wb") as f:
148+
pickle.dump({}, f)
149+
150+
try:
151+
name = os.path.splitext(os.path.relpath(no_exist_name, localedata._dirname))[0]
152+
except ValueError:
153+
if sys.platform == "win32":
154+
pytest.skip("unable to form relpath")
155+
raise
156+
157+
assert not localedata.exists(name)
158+
with pytest.raises(IOError):
159+
localedata.load(name)
160+
with pytest.raises(UnknownLocaleError):
161+
Locale(name)
162+
163+
164+
@pytest.mark.skipif(sys.platform != "win32", reason="windows-only test")
165+
def test_reserved_locale_names():
166+
for name in ("con", "aux", "nul", "prn", "com8", "lpt5"):
167+
with pytest.raises(ValueError):
168+
localedata.load(name)
169+
with pytest.raises(ValueError):
170+
Locale(name)

0 commit comments

Comments
 (0)