forked from username/flaskpaste
add minimum size and binary content enforcement
This commit is contained in:
@@ -327,6 +327,29 @@ def detect_mime_type(content: bytes, content_type: str | None = None) -> str:
|
||||
return "application/octet-stream"
|
||||
|
||||
|
||||
def is_recognizable_format(content: bytes) -> tuple[bool, str | None]:
|
||||
"""Check if content is a recognizable (likely unencrypted) format.
|
||||
|
||||
Returns (is_recognizable, detected_format).
|
||||
Used to enforce encryption by rejecting known formats.
|
||||
"""
|
||||
# Check magic bytes
|
||||
for magic, mime in MAGIC_SIGNATURES.items():
|
||||
if content.startswith(magic):
|
||||
if magic == b"RIFF" and len(content) >= 12 and content[8:12] != b"WEBP":
|
||||
continue
|
||||
return True, mime
|
||||
|
||||
# Check if valid UTF-8 text (plaintext)
|
||||
try:
|
||||
content.decode("utf-8")
|
||||
return True, "text/plain"
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
|
||||
return False, None
|
||||
|
||||
|
||||
def generate_paste_id(content: bytes) -> str:
|
||||
"""Generate unique paste ID from content hash and timestamp."""
|
||||
data = content + str(time.time_ns()).encode()
|
||||
@@ -425,6 +448,17 @@ class IndexView(MethodView):
|
||||
authenticated=owner is not None,
|
||||
)
|
||||
|
||||
# Minimum size check (enforces encryption overhead)
|
||||
min_size = current_app.config.get("MIN_PASTE_SIZE", 0)
|
||||
if min_size > 0 and content_size < min_size:
|
||||
return error_response(
|
||||
"Paste too small",
|
||||
400,
|
||||
size=content_size,
|
||||
min_size=min_size,
|
||||
hint="Encrypt content before uploading (-e flag in fpaste)",
|
||||
)
|
||||
|
||||
# Entropy check
|
||||
min_entropy = current_app.config.get("MIN_ENTROPY", 0)
|
||||
min_entropy_size = current_app.config.get("MIN_ENTROPY_SIZE", 256)
|
||||
@@ -445,6 +479,22 @@ class IndexView(MethodView):
|
||||
hint="Encrypt content before uploading (-e flag in fpaste)",
|
||||
)
|
||||
|
||||
# Binary content requirement (reject recognizable formats)
|
||||
if current_app.config.get("REQUIRE_BINARY", False):
|
||||
is_recognized, detected_format = is_recognizable_format(content)
|
||||
if is_recognized:
|
||||
current_app.logger.warning(
|
||||
"Recognizable format rejected: %s from=%s",
|
||||
detected_format,
|
||||
request.remote_addr,
|
||||
)
|
||||
return error_response(
|
||||
"Recognizable format not allowed",
|
||||
400,
|
||||
detected=detected_format,
|
||||
hint="Encrypt content before uploading (-e flag in fpaste)",
|
||||
)
|
||||
|
||||
# Deduplication check
|
||||
content_hash = hashlib.sha256(content).hexdigest()
|
||||
is_allowed, dedup_count = check_content_hash(content_hash)
|
||||
|
||||
Reference in New Issue
Block a user