Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fixes #10464] Fix code scanning alert - Uncontrolled data used in path expression #10465

Merged
merged 3 commits into from
Dec 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion geonode/geoserver/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@
#
#########################################################################
import re
import os
import logging

from urllib.parse import urljoin
from pathvalidate import ValidationError

from django.conf import settings
from django.urls import reverse

from geonode import geoserver
from geonode import geoserver, GeoNodeException
from geonode.utils import safe_path_leaf
from geonode.decorators import on_ogc_backend
from geonode.tests.base import GeoNodeBaseTestSupport
from geonode.geoserver.views import _response_callback
Expand Down Expand Up @@ -87,6 +90,36 @@ def test_extract_name_from_sld(self):
</foo>"""
self.assertIsNone(extract_name_from_sld(gs_catalog, content))

@on_ogc_backend(geoserver.BACKEND_PACKAGE)
def test_safe_path_leaf(self):
base_path = settings.MEDIA_ROOT

malformed_paths = [
'c:/etc/passwd',
'c:\\etc\\passwd',
'\0_a*b:c<d>e%f/(g)h+i_0.txt'
]
for _path in malformed_paths:
with self.assertRaises(ValidationError):
safe_path_leaf(_path)

unsafe_paths = [
'/root/',
'~/.ssh',
'$HOME/.ssh',
'/etc/passwd',
'.../style.sld',
'fi:l*e/p"a?t>h|.t<xt',
os.path.join('/tmp/uploaded/', 'style.sld'),
os.path.join(base_path, '../etc/passwd', 'style.sld')
]
for _path in unsafe_paths:
with self.assertRaisesMessage(GeoNodeException, f"The provided path '{_path}' is not safe. The file is outside the MEDIA_ROOT '{base_path}' base path!"):
safe_path_leaf(_path)

safe_path = os.path.join(base_path, 'style.sld')
self.assertEqual(safe_path_leaf(safe_path), safe_path)

@on_ogc_backend(geoserver.BACKEND_PACKAGE)
def test_replace_callback(self):
content = f"""<Layer>
Expand Down
4 changes: 3 additions & 1 deletion geonode/geoserver/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
json_response,
_get_basic_auth_info,
http_client,
safe_path_leaf,
get_headers,
get_dataset_workspace)
from geoserver.catalog import FailedRequestError
Expand Down Expand Up @@ -175,7 +176,8 @@ def respond(*args, **kw):
try:
# Check SLD is valid
try:
if sld:
_allowed_sld_extensions = ['.sld', '.xml', '.css', '.txt', '.yml']
if sld and os.path.splitext(safe_path_leaf(sld))[1].lower() in _allowed_sld_extensions:
if isfile(sld):
with open(sld) as sld_file:
sld = sld_file.read()
Expand Down
21 changes: 21 additions & 0 deletions geonode/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import json
import time
import base64
import ntpath
import select
import shutil
import string
Expand All @@ -50,6 +51,7 @@
from rest_framework.exceptions import APIException
from math import atan, exp, log, pi, sin, tan, floor
from zipfile import ZipFile, is_zipfile, ZIP_DEFLATED
from pathvalidate import ValidationError, validate_filepath, validate_filename
from geonode.upload.api.exceptions import GeneralUploadException

from django.conf import settings
Expand Down Expand Up @@ -1905,3 +1907,22 @@ def get_supported_datasets_file_types():

def get_allowed_extensions():
return list(itertools.chain.from_iterable([_type['ext'] for _type in get_supported_datasets_file_types()]))


def safe_path_leaf(path):
"""A view that is not vulnerable to malicious file access."""
base_path = settings.MEDIA_ROOT
try:
validate_filepath(path, platform='auto')
head, tail = ntpath.split(path)
filename = tail or ntpath.basename(head)
validate_filename(filename, platform='auto')
except ValidationError as e:
logger.error(f"{e}")
raise e
# GOOD -- Verify with normalised version of path
fullpath = os.path.normpath(os.path.join(head, filename))
if not fullpath.startswith(base_path) or path != fullpath:
raise GeoNodeException(
f"The provided path '{path}' is not safe. The file is outside the MEDIA_ROOT '{base_path}' base path!")
return fullpath
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ schema==0.7.5
rdflib==6.1.1
smart_open==6.3.0
PyMuPDF==1.21.1
pathvalidate==2.5.2

# Django Apps
django-allauth==0.51.0
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ install_requires =
rdflib==6.1.1
smart_open==6.3.0
PyMuPDF==1.21.1
pathvalidate==2.5.2

# Django Apps
django-allauth==0.51.0
Expand Down