-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
161 lines (134 loc) · 5.3 KB
/
Copy pathutils.py
File metadata and controls
161 lines (134 loc) · 5.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import os
import sys
import logging
from pathlib import Path
from exceptions import ForbiddenException, InternalServerException
def get_args(index: int, default: str):
"""
Get command line argument by index with default value
"""
return default if len(sys.argv) <= index + 1 else sys.argv[index + 1]
def validate_path(requested_path: str, base_dir: str = 'resources') -> str:
"""
Validate and sanitize file path to prevent directory traversal attacks
Returns the safe absolute path or raises ForbiddenException
"""
logger = logging.getLogger('PathValidator')
# Remove leading slash if present
if requested_path.startswith('/'):
requested_path = requested_path[1:]
# Check for dangerous patterns
dangerous_patterns = ['..', './', '//', '\\', '\x00']
for pattern in dangerous_patterns:
if pattern in requested_path:
logger.warning(f'Path traversal attempt blocked: {requested_path}')
raise ForbiddenException(403, 'Forbidden: Path traversal detected')
# Convert to absolute path and ensure it's within base directory
base_path = Path(base_dir).resolve()
requested_file = base_path / requested_path
try:
# Resolve the path to handle any remaining . or .. components
resolved_path = requested_file.resolve()
# Ensure the resolved path is still within the base directory
if not str(resolved_path).startswith(str(base_path)):
logger.warning(f'Path outside base directory blocked: {requested_path}')
raise ForbiddenException(403, 'Forbidden: Access outside base directory')
return str(resolved_path)
except Exception as e:
logger.error(f'Path validation error: {e}')
raise ForbiddenException(403, 'Forbidden: Invalid path')
def read_file_safe(path: str, mode: str = 'r') -> tuple:
"""
Safely read file with proper error handling
Returns (success: bool, data: str/bytes, error: str)
"""
logger = logging.getLogger('FileReader')
try:
# Validate path first
safe_path = validate_path(path)
# Check if file exists
if not os.path.exists(safe_path):
return False, None, 'File not found'
# Check if it's actually a file (not a directory)
if not os.path.isfile(safe_path):
return False, None, 'Not a file'
# Read file
with open(safe_path, mode) as file:
data = file.read()
logger.info(f'Successfully read file: {path} ({len(data)} bytes)')
return True, data, None
except ForbiddenException:
raise # Re-raise security exceptions
except FileNotFoundError:
return False, None, 'File not found'
except PermissionError:
logger.error(f'Permission denied reading file: {path}')
return False, None, 'Permission denied'
except Exception as e:
logger.error(f'Error reading file {path}: {e}')
return False, None, f'Read error: {str(e)}'
def get_file_mimetype(filename: str) -> str:
"""
Get MIME type based on file extension
"""
ext = os.path.splitext(filename)[1].lower()
mime_types = {
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.txt': 'application/octet-stream',
'.png': 'application/octet-stream',
'.jpg': 'application/octet-stream',
'.jpeg': 'application/octet-stream',
'.json': 'application/json',
'.css': 'text/css',
'.js': 'application/javascript',
}
return mime_types.get(ext, 'application/octet-stream')
def is_supported_file_type(filename: str) -> bool:
"""
Check if file type is supported by the server
"""
ext = os.path.splitext(filename)[1].lower()
supported_extensions = ['.html', '.htm', '.txt', '.png', '.jpg', '.jpeg']
return ext in supported_extensions
def validate_host_header(host_header: str, server_host: str, server_port: int) -> bool:
"""
Validate Host header to prevent host header injection attacks
"""
if not host_header:
return False
# Expected host formats
expected_hosts = [
f'{server_host}:{server_port}',
server_host, # Allow without port for default ports
]
# Handle localhost variations
if server_host == '127.0.0.1':
expected_hosts.extend([
f'localhost:{server_port}',
'localhost'
])
elif server_host == 'localhost':
expected_hosts.extend([
f'127.0.0.1:{server_port}',
'127.0.0.1'
])
return host_header.lower() in [h.lower() for h in expected_hosts]
def create_upload_filename(extension: str = 'json') -> str:
"""
Create unique filename for uploaded files
Format: upload_[timestamp]_[random_id].json
"""
import time
import random
import string
timestamp = int(time.time())
random_id = ''.join(random.choices(string.ascii_lowercase + string.digits, k=4))
return f'upload_{timestamp}_{random_id}.{extension}'
def ensure_upload_directory() -> str:
"""
Ensure uploads directory exists and return its path
"""
upload_dir = os.path.join('resources', 'uploads')
os.makedirs(upload_dir, exist_ok=True)
return upload_dir