7212b5
diff --git a/babel/localedata.py b/babel/localedata.py
7212b5
index e012abb..dea0a0f 100644
7212b5
--- a/babel/localedata.py
7212b5
+++ b/babel/localedata.py
7212b5
@@ -13,6 +13,8 @@
7212b5
 """
7212b5
 
7212b5
 import os
7212b5
+import re
7212b5
+import sys
7212b5
 import threading
7212b5
 from itertools import chain
7212b5
 
7212b5
@@ -22,6 +24,7 @@ from babel._compat import pickle, string_types, abc
7212b5
 _cache = {}
7212b5
 _cache_lock = threading.RLock()
7212b5
 _dirname = os.path.join(os.path.dirname(__file__), 'locale-data')
7212b5
+_windows_reserved_name_re = re.compile("^(con|prn|aux|nul|com[0-9]|lpt[0-9])$", re.I)
7212b5
 
7212b5
 
7212b5
 def normalize_locale(name):
7212b5
@@ -38,6 +41,22 @@ def normalize_locale(name):
7212b5
             return locale_id
7212b5
 
7212b5
 
7212b5
+def resolve_locale_filename(name):
7212b5
+    """
7212b5
+    Resolve a locale identifier to a `.dat` path on disk.
7212b5
+    """
7212b5
+
7212b5
+    # Clean up any possible relative paths.
7212b5
+    name = os.path.basename(name)
7212b5
+
7212b5
+    # Ensure we're not left with one of the Windows reserved names.
7212b5
+    if sys.platform == "win32" and _windows_reserved_name_re.match(os.path.splitext(name)[0]):
7212b5
+        raise ValueError("Name %s is invalid on Windows" % name)
7212b5
+
7212b5
+    # Build the path.
7212b5
+    return os.path.join(_dirname, '%s.dat' % name)
7212b5
+
7212b5
+
7212b5
 def exists(name):
7212b5
     """Check whether locale data is available for the given locale.
7212b5
 
7212b5
@@ -49,7 +68,7 @@ def exists(name):
7212b5
         return False
7212b5
     if name in _cache:
7212b5
         return True
7212b5
-    file_found = os.path.exists(os.path.join(_dirname, '%s.dat' % name))
7212b5
+    file_found = os.path.exists(resolve_locale_filename(name))
7212b5
     return True if file_found else bool(normalize_locale(name))
7212b5
 
7212b5
 
7212b5
@@ -102,6 +121,7 @@ def load(name, merge_inherited=True):
7212b5
     :raise `IOError`: if no locale data file is found for the given locale
7212b5
                       identifer, or one of the locales it inherits from
7212b5
     """
7212b5
+    name = os.path.basename(name)
7212b5
     _cache_lock.acquire()
7212b5
     try:
7212b5
         data = _cache.get(name)
7212b5
@@ -119,7 +139,7 @@ def load(name, merge_inherited=True):
7212b5
                     else:
7212b5
                         parent = '_'.join(parts[:-1])
7212b5
                 data = load(parent).copy()
7212b5
-            filename = os.path.join(_dirname, '%s.dat' % name)
7212b5
+            filename = resolve_locale_filename(name)
7212b5
             with open(filename, 'rb') as fileobj:
7212b5
                 if name != 'root' and merge_inherited:
7212b5
                     merge(data, pickle.load(fileobj))
7212b5
diff --git a/tests/test_localedata.py b/tests/test_localedata.py
7212b5
index dbacba0..4730096 100644
7212b5
--- a/tests/test_localedata.py
7212b5
+++ b/tests/test_localedata.py
7212b5
@@ -11,11 +11,17 @@
7212b5
 # individuals. For the exact contribution history, see the revision
7212b5
 # history and logs, available at http://babel.edgewall.org/log/.
7212b5
 
7212b5
+import os
7212b5
+import pickle
7212b5
+import sys
7212b5
+import tempfile
7212b5
 import unittest
7212b5
 import random
7212b5
 from operator import methodcaller
7212b5
 
7212b5
-from babel import localedata
7212b5
+import pytest
7212b5
+
7212b5
+from babel import localedata, Locale, UnknownLocaleError
7212b5
 
7212b5
 
7212b5
 class MergeResolveTestCase(unittest.TestCase):
7212b5
@@ -131,3 +137,34 @@ def test_locale_identifiers_cache(monkeypatch):
7212b5
     localedata.locale_identifiers.cache = None
7212b5
     assert localedata.locale_identifiers()
7212b5
     assert len(listdir_calls) == 2
7212b5
+
7212b5
+
7212b5
+def test_locale_name_cleanup():
7212b5
+    """
7212b5
+    Test that locale identifiers are cleaned up to avoid directory traversal.
7212b5
+    """
7212b5
+    no_exist_name = os.path.join(tempfile.gettempdir(), "babel%d.dat" % random.randint(1, 99999))
7212b5
+    with open(no_exist_name, "wb") as f:
7212b5
+        pickle.dump({}, f)
7212b5
+
7212b5
+    try:
7212b5
+        name = os.path.splitext(os.path.relpath(no_exist_name, localedata._dirname))[0]
7212b5
+    except ValueError:
7212b5
+        if sys.platform == "win32":
7212b5
+            pytest.skip("unable to form relpath")
7212b5
+        raise
7212b5
+
7212b5
+    assert not localedata.exists(name)
7212b5
+    with pytest.raises(IOError):
7212b5
+        localedata.load(name)
7212b5
+    with pytest.raises(UnknownLocaleError):
7212b5
+        Locale(name)
7212b5
+
7212b5
+
7212b5
+@pytest.mark.skipif(sys.platform != "win32", reason="windows-only test")
7212b5
+def test_reserved_locale_names():
7212b5
+    for name in ("con", "aux", "nul", "prn", "com8", "lpt5"):
7212b5
+        with pytest.raises(ValueError):
7212b5
+            localedata.load(name)
7212b5
+        with pytest.raises(ValueError):
7212b5
+            Locale(name)