Adding filepath sanitization

This commit is contained in:
Captain-T2004 2024-09-12 10:16:52 +05:30
parent d94f11860a
commit c640dcd1cf
4 changed files with 36 additions and 4 deletions

View File

@ -23,7 +23,7 @@ from nettacker.api.core import (
languages_to_country,
api_key_is_valid,
)
from nettacker.api.helpers import structure
from nettacker.api.helpers import structure, sanitize_path
from nettacker.config import Config
from nettacker.core.app import Nettacker
from nettacker.core.die import die_failure
@ -230,9 +230,17 @@ def compare_scans():
compare_report_path_filename = get_value(flask_request, "compare_report_path")
if not compare_report_path_filename:
compare_report_path_filename = nettacker_application_config["compare_report_path_filename"]
base_path = str(nettacker_application_config['api_base_path'])
compare_report_path_filename = sanitize_path(compare_report_path_filename)
fullpath = os.path.normpath(os.path.join(base_path, compare_report_path_filename))
if not fullpath.startswith(base_path):
return jsonify(structure(status="error", msg="Invalid file path")), 500
compare_options = {
"scan_compare_id": scan_id_second,
"compare_report_path_filename": compare_report_path_filename,
"compare_report_path_filename": fullpath,
}
try:
result = create_compare_report(compare_options, scan_id_first)

View File

@ -1,3 +1,5 @@
import re
def structure(status="", msg=""):
"""
basic JSON message structure
@ -10,3 +12,25 @@ def structure(status="", msg=""):
a JSON message
"""
return {"status": status, "msg": msg}
def sanitize_path(path):
"""
Sanitize the file path to preven unathorized access
Args:
path: filepath(user input)
Returns:
sanitized_path
"""
allowed_pattern = r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)?$'
components = re.split(r'[/\\]', path)
sanitized_components = []
for component in components:
if re.match(allowed_pattern, component):
sanitized_components.append(component)
sanitized_path = '_'.join(sanitized_components)
return sanitized_path

View File

@ -151,6 +151,7 @@ class DefaultSettings(ConfigBase):
date_time=now(format="%Y_%m_%d_%H_%M_%S"),
random_chars=generate_random_token(10),
)
api_base_path = CWD / "results"
class Config:

View File

@ -396,8 +396,7 @@
<h3>Output(HTML/JSON/CSV/TXT)</h3>
<div class="input-group col-xs-5">
<span class="input-group-addon">filename</span>
<input id="compare_report_path" type="text" class="form-control" placeholder="Additional Info"
value="{% autoescape off %}{{filename}}{% endautoescape %}">
<input id="compare_report_path" type="text" class="form-control" placeholder="Additional Info">
</div>
<br>
<ul id="create_compare_report" class="btn btn-primary" action="javascript:create_compare_report()">