binding and personality services sanitized

This commit is contained in:
Saifeddine ALOUI 2024-02-17 02:53:50 +01:00
parent 8c40b159c5
commit 7128493d95
2 changed files with 65 additions and 44 deletions

View File

@ -7,9 +7,9 @@ description:
application. These routes are specific to serving files
"""
from fastapi import APIRouter, Request
from fastapi import APIRouter, Request, Depends
from fastapi import HTTPException
from pydantic import BaseModel
from pydantic import BaseModel, validator
import pkg_resources
from lollms.server.elf_server import LOLLMSElfServer
from fastapi.responses import FileResponse
@ -19,6 +19,7 @@ from lollms.utilities import load_config, trace_exception, gc
from pathlib import Path
from typing import List
import os
import re
# ----------------------- Defining router and main class ------------------------------
router = APIRouter()
@ -32,60 +33,45 @@ async def serve_user_infos(path: str):
Serve user information file.
Args:
filename (str): The name of the file to serve.
path (FilePath): The validated path to the file to be served.
Returns:
FileResponse: The file response containing the requested file.
"""
file_path = (lollmsElfServer.lollms_paths.personal_user_infos_path / path).resolve()
if not Path(file_path).exists():
raise HTTPException(status_code=404, detail="File not found")
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
file_path = (lollmsElfServer.lollms_paths.personal_user_infos_path / path.path).resolve()
return FileResponse(str(file_path))
# ----------------------------------- Lollms zoos -----------------------------------------
@router.get("/bindings/{path:path}")
async def serve_bindings(path: str):
"""
Serve personalities file.
Args:
path (str): The path of the bindings file to serve.
Returns:
FileResponse: The file response containing the requested bindings file.
"""
file_path = (lollmsElfServer.lollms_paths.bindings_zoo_path / path).resolve()
if not Path(file_path).exists():
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(str(file_path))
@router.get("/personalities/{path:path}")
async def serve_personalities(path: str):
"""
Serve personalities file.
Args:
path (str): The path of the personalities file to serve.
path (FilePath): The path of the personalities file to serve.
Returns:
FileResponse: The file response containing the requested personalities file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
if "custom_personalities" in path:
file_path = (lollmsElfServer.lollms_paths.custom_personalities_path / "/".join(str(path).split("/")[1:])).resolve()
else:
file_path = (lollmsElfServer.lollms_paths.personalities_zoo_path / path).resolve()
if not Path(file_path).exists():
raise HTTPException(status_code=404, detail="File not found")
raise ValueError("File not found")
return FileResponse(str(file_path))
@router.get("/extensions/{path:path}")
async def serve_extensions(path: str):
"""
@ -97,8 +83,16 @@ async def serve_extensions(path: str):
Returns:
FileResponse: The file response containing the requested extensions file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
file_path = (lollmsElfServer.lollms_paths.extensions_zoo_path / path).resolve()
if not Path(file_path).exists():
raise ValueError("File not found")
if not Path(file_path).exists():
raise HTTPException(status_code=404, detail="File not found")
@ -117,6 +111,10 @@ async def serve_audio(path: str):
Returns:
FileResponse: The file response containing the requested audio file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
root_dir = Path(lollmsElfServer.lollms_paths.personal_outputs_path).resolve()
file_path = root_dir/ 'audio_out' / path
@ -137,6 +135,10 @@ async def serve_images(path: str):
Returns:
FileResponse: The file response containing the requested image file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
root_dir = Path(os.getcwd())/ "images/"
file_path = (root_dir / path).resolve()
@ -159,6 +161,10 @@ async def serve_outputs(path: str):
Returns:
FileResponse: The file response containing the requested output file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
root_dir = lollmsElfServer.lollms_paths.personal_outputs_path
root_dir.mkdir(exist_ok=True, parents=True)
file_path = root_dir / path
@ -181,6 +187,10 @@ async def serve_data(path: str):
Returns:
FileResponse: The file response containing the requested data file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
root_dir = lollmsElfServer.lollms_paths.personal_path / "data"
root_dir.mkdir(exist_ok=True, parents=True)
file_path = root_dir / path
@ -204,6 +214,10 @@ async def serve_help(path: str):
Returns:
FileResponse: The file response containing the requested data file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
root_dir = Path(os.getcwd())
file_path = root_dir/'help/' / path
@ -225,6 +239,10 @@ async def serve_uploads(path: str):
Returns:
FileResponse: The file response containing the requested uploads file.
"""
if ".." in path:
ASCIIColors.error("A suspected LFI attack detected. The path sent to the server has .. in it!")
raise HTTPException(status_code=400, detail="Invalid path!")
root_dir = lollmsElfServer.lollms_paths.personal_path / "uploads"
root_dir.mkdir(exist_ok=True, parents=True)
file_path = root_dir / path

View File

@ -10,7 +10,7 @@ description:
from fastapi import APIRouter, Request
from fastapi import HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel
from pydantic import BaseModel, Field
import pkg_resources
from lollms.server.elf_server import LOLLMSElfServer
from lollms.personality import AIPersonality, InstallOption
@ -175,23 +175,26 @@ def get_current_personality_path_infos():
# ----------------------------------- Installation/Uninstallation/Reinstallation ----------------------------------------
@router.post("/reinstall_personality")
async def reinstall_personality(request: Request):
"""
Endpoint to apply configuration settings.
class PersonalityIn(BaseModel):
name: str = Field(None)
:param request: The HTTP request object.
@router.post("/reinstall_personality")
async def reinstall_personality(personality_in: PersonalityIn):
"""
Endpoint to reinstall personality
:param personality_in: PersonalityIn contans personality name.
:return: A JSON response with the status of the operation.
"""
try:
data = (await request.json())
if not 'name' in data:
data['name']=lollmsElfServer.config.personalities[lollmsElfServer.config["active_personality_id"]]
personality_path = lollmsElfServer.lollms_paths.personalities_zoo_path / data['name']
ASCIIColors.info(f"- Reinstalling personality {data['name']}...")
if(".." in personality_in.name):
raise "Detected an attempt of path traversal. Are you kidding me?"
if not personality_in.name:
personality_in.name=lollmsElfServer.config.personalities[lollmsElfServer.config["active_personality_id"]]
personality_path = lollmsElfServer.lollms_paths.personalities_zoo_path / personality_in.name
ASCIIColors.info(f"- Reinstalling personality {personality_in.name}...")
ASCIIColors.info("Unmounting personality")
idx = lollmsElfServer.config.personalities.index(data['name'])
idx = lollmsElfServer.config.personalities.index(personality_in.name)
print(f"index = {idx}")
lollmsElfServer.mounted_personalities[idx] = None
gc.collect()
@ -204,7 +207,7 @@ async def reinstall_personality(request: Request):
run_scripts=True,installation_option=InstallOption.FORCE_INSTALL)
return {"status":True}
except Exception as ex:
ASCIIColors.error(f"Personality file not found or is corrupted ({data['name']}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.")
ASCIIColors.error(f"Personality file not found or is corrupted ({personality_in.name}).\nReturned the following exception:{ex}\nPlease verify that the personality you have selected exists or select another personality. Some updates may lead to change in personality name or category, so check the personality selection in settings to be sure.")
ASCIIColors.info("Trying to force reinstall")
return {"status":False, 'error':str(e)}