fixed vulenerability in calculator

This commit is contained in:
Saifeddine ALOUI 2024-10-01 02:06:04 +02:00
parent cca3553ce1
commit 295d4a9d00
5 changed files with 132 additions and 38 deletions

View File

@ -451,6 +451,18 @@ class LollmsApplication(LoLLMsCom):
ASCIIColors.execute_with_animation("Loading loacal TTI services", start_tti, ASCIIColors.color_blue)
print("OK")
def start_ttv(*args, **kwargs):
if self.config.active_ttv_service == "lumalabs" and (self.ttv is None or self.tti.name!="lumalabs"):
try:
from lollms.services.ttv.lumalabs.lollms_lumalabs import LollmsLumaLabs
self.sd = LollmsLumaLabs(self.config.lumalabs_key)
except:
self.warning(f"Couldn't load SD")
ASCIIColors.execute_with_animation("Loading loacal TTV services", start_ttv, ASCIIColors.color_blue)
print("OK")
def verify_servers(self, reload_all=False):
@ -566,6 +578,14 @@ class LollmsApplication(LoLLMsCom):
from lollms.services.stt.whisper.lollms_whisper import LollmsWhisper
self.stt = LollmsWhisper(self, self.config.whisper_model)
if self.config.active_ttv_service == "lumalabs" and (self.ttv is None or self.tti.name!="lumalabs"):
try:
from lollms.services.ttv.lumalabs.lollms_lumalabs import LollmsLumaLabs
self.sd = LollmsLumaLabs(self.config.lumalabs_key)
except:
self.warning(f"Couldn't load SD")
except Exception as ex:
trace_exception(ex)

View File

@ -1,17 +1,115 @@
import math
from functools import partial
import sympy as sp
import ast
import math
import operator
import re
import threading
import logging
from typing import Union
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TimeoutException(Exception):
pass
def is_valid_expression(expression: str) -> bool:
allowed_chars = r'^[0-9+\-*/^()., a-zA-Z]+$'
return bool(re.match(allowed_chars, expression))
def is_expression_too_complex(expression: str, max_length: int = 100, max_operations: int = 10) -> bool:
if len(expression) > max_length:
return True
operation_count = sum(expression.count(op) for op in '+-*/^')
return operation_count > max_operations
def calculate(expression: str, timeout: int = 5) -> Union[float, str]:
logger.info(f"Calculating expression: {expression}")
if not is_valid_expression(expression):
logger.warning(f"Invalid characters in expression: {expression}")
return "Invalid characters in expression"
if is_expression_too_complex(expression):
logger.warning(f"Expression too complex: {expression}")
return "Expression too complex"
result = []
exception = []
def calculate_with_timeout():
try:
# Define allowed operations
allowed_ops = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Pow: operator.pow,
ast.USub: operator.neg,
}
# Define allowed functions from math module
allowed_functions = {
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'sqrt': math.sqrt,
'log': math.log,
'exp': math.exp,
# Add more functions as needed
}
def eval_expr(node):
if isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.Name):
if node.id in allowed_functions:
return allowed_functions[node.id]
raise ValueError(f"Unknown variable: {node.id}")
elif isinstance(node, ast.BinOp):
op = type(node.op)
if op not in allowed_ops:
raise ValueError(f"Unsupported operation: {op}")
return allowed_ops[op](eval_expr(node.left), eval_expr(node.right))
elif isinstance(node, ast.UnaryOp):
op = type(node.op)
if op not in allowed_ops:
raise ValueError(f"Unsupported operation: {op}")
return allowed_ops[op](eval_expr(node.operand))
elif isinstance(node, ast.Call):
if not isinstance(node.func, ast.Name) or node.func.id not in allowed_functions:
raise ValueError(f"Unsupported function: {node.func.id}")
return allowed_functions[node.func.id](*[eval_expr(arg) for arg in node.args])
else:
raise ValueError(f"Unsupported node type: {type(node)}")
tree = ast.parse(expression, mode='eval')
result.append(eval_expr(tree.body))
except Exception as e:
exception.append(str(e))
calculation_thread = threading.Thread(target=calculate_with_timeout)
calculation_thread.start()
calculation_thread.join(timeout)
if calculation_thread.is_alive():
logger.warning(f"Calculation timed out: {expression}")
return "Calculation timed out"
if exception:
logger.error(f"Error during calculation: {exception[0]}")
return exception[0]
if result:
logger.info(f"Calculation result: {result[0]}")
return result[0]
return "Unexpected error occurred"
def calculate(expression: str) -> float:
try:
# Add the math module functions to the local namespace
allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")}
# Evaluate the expression safely using the allowed names
result = eval(expression, {"__builtins__": None}, allowed_names)
return result
except Exception as e:
return str(e)
def calculate_function(processor, client):

View File

@ -2,7 +2,7 @@ import requests
from typing import Optional, Dict
from lollms.ttv import LollmsTTV
class LumaLabsVideo(LollmsTTV):
class LollmsLumaLabs(LollmsTTV):
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.lumalabs.ai/dream-machine/v1/generations"

View File

@ -1,18 +1,5 @@
@echo off
@echo Starting LOLLMS Web UI...
echo " ___ ___ ___ ___ ___ ___ "
echo " /\__\ /\ \ /\__\ /\__\ /\__\ /\ \ "
echo " /:/ / /::\ \ /:/ / /:/ / /::| | /::\ \ "
echo " /:/ / /:/\:\ \ /:/ / /:/ / /:|:| | /:/\ \ \ "
echo " /:/ / /:/ \:\ \ /:/ / /:/ / /:/|:|__|__ _\:\~\ \ \ "
echo "/:/__/ /:/__/ \:\__\ /:/__/ /:/__/ /:/ |::::\__\ /\ \:\ \ \__\ "
echo "\:\ \ \:\ \ /:/ / \:\ \ \:\ \ \/__/~~/:/ / \:\ \:\ \/__/ "
echo " \:\ \ \:\ /:/ / \:\ \ \:\ \ /:/ / \:\ \:\__\ "
echo " \:\ \ \:\/:/ / \:\ \ \:\ \ /:/ / \:\/:/ / "
echo " \:\__\ \::/ / \:\__\ \:\__\ /:/ / \::/ / "
echo " \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ "
echo By ParisNeo
cd /D "%~dp0"
@rem better isolation for virtual environment

View File

@ -20,18 +20,7 @@ pause
cls
md
echo " ___ ___ ___ ___ ___ ___ "
echo " /\__\ /\ \ /\__\ /\__\ /\__\ /\ \ "
echo " /:/ / /::\ \ /:/ / /:/ / /::| | /::\ \ "
echo " /:/ / /:/\:\ \ /:/ / /:/ / /:|:| | /:/\ \ \ "
echo " /:/ / /:/ \:\ \ /:/ / /:/ / /:/|:|__|__ _\:\~\ \ \ "
echo " /:/__/ /:/__/ \:\__\ /:/__/ /:/__/ /:/ |::::\__\ /\ \:\ \ \__\ "
echo " \:\ \ \:\ \ /:/ / \:\ \ \:\ \ \/__/~~/:/ / \:\ \:\ \/__/ "
echo " \:\ \ \:\ /:/ / \:\ \ \:\ \ /:/ / \:\ \:\__\ "
echo " \:\ \ \:\/:/ / \:\ \ \:\ \ /:/ / \:\/:/ / "
echo " \:\__\ \::/ / \:\__\ \:\__\ /:/ / \::/ / "
echo " \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ "
echo Lollms windows installer
echo By ParisNeo
:retry