mirror of
https://github.com/iio612/DEFENDER.git
synced 2026-02-14 03:34:23 +00:00
Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
80b329dd5d | ||
|
|
f7b49c151f | ||
|
|
1ee9b7e3ff | ||
|
|
4d0087623c | ||
|
|
dc20f5ec3c | ||
|
|
110cae3b84 | ||
|
|
857cbfc85d | ||
|
|
3518589e9c | ||
|
|
e14c97de03 | ||
|
|
69360be3ad | ||
|
|
bfa90c6bd5 | ||
|
|
5c8378a0e7 | ||
|
|
e3b212ea88 | ||
|
|
0c2a350d38 | ||
|
|
1cea8d0601 | ||
|
|
652b400d5e | ||
|
|
2f8b965b59 | ||
|
|
3c043cefd8 | ||
|
|
59a75cecd8 | ||
|
|
71053437a7 | ||
|
|
7796d05206 | ||
|
|
5f2567f9e5 | ||
|
|
aaa1dd9a1a | ||
|
|
a02f2f9a26 | ||
|
|
d73adb6f0b | ||
|
|
b812e64992 | ||
|
|
9bd1f68df2 | ||
|
|
f44b08bf36 | ||
|
|
1a19e1613a | ||
|
|
cdc15b7b47 | ||
|
|
31fe9f62ec | ||
|
|
f0853e3afb | ||
|
|
6dade09257 | ||
|
|
9533b010b2 | ||
|
|
824db73590 | ||
|
|
96bf4b6f80 | ||
|
|
922336363e |
24
core/base.py
24
core/base.py
@@ -48,6 +48,7 @@ class Base:
|
||||
with open(version_filename, 'r') as version_data:
|
||||
current_version:dict[str, str] = json.load(version_data)
|
||||
|
||||
# self.DEFENDER_VERSION = current_version["version"]
|
||||
self.Config.current_version = current_version['version']
|
||||
|
||||
return None
|
||||
@@ -80,14 +81,6 @@ class Base:
|
||||
self.logs.warning(f'Github not available to fetch latest version')
|
||||
|
||||
def check_for_new_version(self, online:bool) -> bool:
|
||||
"""Check if there is a new version available
|
||||
|
||||
Args:
|
||||
online (bool): True if you want to get the version from github (main branch)
|
||||
|
||||
Returns:
|
||||
bool: True if there is a new version available
|
||||
"""
|
||||
try:
|
||||
self.logs.debug(f'Checking for a new service version')
|
||||
|
||||
@@ -236,19 +229,6 @@ class Base:
|
||||
|
||||
return False
|
||||
|
||||
def db_update_module(self, user_cmd: str, module_name: str) -> None:
|
||||
"""Modifie la date et le user qui a rechargé le module
|
||||
|
||||
Args:
|
||||
user_cmd (str): le user qui a rechargé le module
|
||||
module_name (str): le module a rechargé
|
||||
"""
|
||||
update_cmd_query = f"UPDATE {self.Config.table_module} SET datetime = :datetime, user = :user WHERE module_name = :module_name"
|
||||
mes_donnees = {'datetime': self.get_datetime(), 'user': user_cmd, 'module_name': module_name}
|
||||
self.db_execute_query(update_cmd_query, mes_donnees)
|
||||
|
||||
return False
|
||||
|
||||
def db_delete_module(self, module_name:str) -> None:
|
||||
"""Supprime les modules de la base de données
|
||||
|
||||
@@ -611,7 +591,7 @@ class Base:
|
||||
)
|
||||
'''
|
||||
|
||||
table_core_channel = f'''CREATE TABLE IF NOT EXISTS {self.Config.table_channel} (
|
||||
table_core_channel = '''CREATE TABLE IF NOT EXISTS core_channel (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
datetime TEXT,
|
||||
module_name TEXT,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import os
|
||||
import json
|
||||
from sys import exit, prefix
|
||||
from sys import exit
|
||||
from dataclasses import dataclass
|
||||
from subprocess import check_call, run, CalledProcessError, PIPE, check_output
|
||||
from subprocess import check_call, run, CalledProcessError, PIPE
|
||||
from platform import python_version, python_version_tuple
|
||||
|
||||
class Install:
|
||||
@@ -25,23 +24,13 @@ class Install:
|
||||
venv_pip_executable: str
|
||||
venv_python_executable: str
|
||||
|
||||
@dataclass
|
||||
class Package:
|
||||
name: str = None
|
||||
version: str = None
|
||||
|
||||
DB_PACKAGES: list[Package] = []
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
self.set_configuration()
|
||||
|
||||
if self.skip_install:
|
||||
self.check_packages_version()
|
||||
return None
|
||||
|
||||
self.check_packages_version()
|
||||
|
||||
# Sinon tester les dependances python et les installer avec pip
|
||||
if self.do_install():
|
||||
|
||||
@@ -86,13 +75,11 @@ class Install:
|
||||
|
||||
if not os.path.exists(os.path.join(self.config.defender_install_folder, 'core', 'configuration.json')):
|
||||
# If configuration file do not exist
|
||||
exit("/!\\ Configuration file (core/configuration.json) doesn't exist! please create it /!\\")
|
||||
exit("/!\\ Configuration file (configuration.json) doesn't exist /!\\")
|
||||
|
||||
# Exclude Windows OS from the installation
|
||||
if os.name == 'nt':
|
||||
# If windows, modify pip and python virtual environment executable
|
||||
self.config.venv_pip_executable = f'{os.path.join(defender_install_folder, venv_folder, "Scripts")}{os.sep}pip.exe'
|
||||
self.config.venv_python_executable = f'{os.path.join(defender_install_folder, venv_folder, "Scripts")}{os.sep}python.exe'
|
||||
#print('/!\\ Skip installation /!\\')
|
||||
self.skip_install = True
|
||||
return False
|
||||
|
||||
@@ -104,7 +91,7 @@ class Install:
|
||||
def is_root(self) -> bool:
|
||||
|
||||
if os.geteuid() != 0:
|
||||
print('> User without privileges ==> OK')
|
||||
print('User without privileges ==> PASS')
|
||||
return False
|
||||
elif os.geteuid() == 0:
|
||||
print('/!\\ Do not use root to install Defender /!\\')
|
||||
@@ -136,75 +123,6 @@ class Install:
|
||||
print(f"Try to install dependencies ...")
|
||||
exit(5)
|
||||
|
||||
def get_packages_version_from_json(self) -> None:
|
||||
"""This will create Package model with package names and required version
|
||||
"""
|
||||
try:
|
||||
|
||||
version_filename = f'.{os.sep}version.json'
|
||||
with open(version_filename, 'r') as version_data:
|
||||
package_info:dict[str, str] = json.load(version_data)
|
||||
|
||||
for name, version in package_info.items():
|
||||
if name == 'version':
|
||||
continue
|
||||
|
||||
self.DB_PACKAGES.append(
|
||||
self.Package(name=name, version=version)
|
||||
)
|
||||
|
||||
return None
|
||||
except FileNotFoundError as fe:
|
||||
print(f"File not found: {fe}")
|
||||
except Exception as err:
|
||||
print(f"General Error: {err}")
|
||||
|
||||
def check_packages_version(self) -> bool:
|
||||
|
||||
try:
|
||||
newVersion = False
|
||||
self.get_packages_version_from_json()
|
||||
|
||||
if not self.config.venv_folder in prefix:
|
||||
print(f"You are probably running a new installation or you are not using your virtual env {self.config.venv_folder}")
|
||||
return newVersion
|
||||
|
||||
print(f"> Checking for dependencies versions ==> WAIT")
|
||||
for package in self.DB_PACKAGES:
|
||||
newVersion = False
|
||||
required_version = package.version
|
||||
installed_version = None
|
||||
|
||||
output = check_output([self.config.venv_pip_executable, 'show', package.name])
|
||||
for line in output.decode().splitlines():
|
||||
if line.startswith('Version:'):
|
||||
installed_version = line.split(':')[1].strip()
|
||||
break
|
||||
|
||||
required_major, required_minor, required_patch = required_version.split('.')
|
||||
installed_major, installed_minor, installed_patch = installed_version.split('.')
|
||||
|
||||
if required_major > installed_major:
|
||||
print(f'> New version of {package.name} is available {installed_version} ==> {required_version}')
|
||||
newVersion = True
|
||||
elif required_major == installed_major and required_minor > installed_minor:
|
||||
print(f'> New version of {package.name} is available {installed_version} ==> {required_version}')
|
||||
newVersion = True
|
||||
elif required_major == installed_major and required_minor == installed_minor and required_patch > installed_patch:
|
||||
print(f'> New version of {package.name} is available {installed_version} ==> {required_version}')
|
||||
newVersion = True
|
||||
|
||||
if newVersion:
|
||||
self.run_subprocess([self.config.venv_pip_executable, 'install', '--upgrade', package.name])
|
||||
|
||||
print(f"> Dependencies versions ==> OK")
|
||||
return newVersion
|
||||
|
||||
except CalledProcessError:
|
||||
print(f"/!\\ Package {package.name} not installed /!\\")
|
||||
except Exception as err:
|
||||
print(f"General Error: {err}")
|
||||
|
||||
def check_python_version(self) -> bool:
|
||||
"""Test si la version de python est autorisée ou non
|
||||
|
||||
|
||||
152
core/irc.py
152
core/irc.py
@@ -95,15 +95,13 @@ class Irc:
|
||||
return None
|
||||
|
||||
except ssl.SSLEOFError as soe:
|
||||
self.Base.logs.critical(f"SSLEOFError: {soe} - {soc.fileno()}")
|
||||
self.Base.logs.critical(f"SSLEOFError __create_socket: {soe} - {soc.fileno()}")
|
||||
except ssl.SSLError as se:
|
||||
self.Base.logs.critical(f"SSLError: {se} - {soc.fileno()}")
|
||||
self.Base.logs.critical(f"SSLError __create_socket: {se} - {soc.fileno()}")
|
||||
except OSError as oe:
|
||||
self.Base.logs.critical(f"OSError: {oe} - {soc.fileno()}")
|
||||
if 'connection refused' in str(oe).lower():
|
||||
sys.exit(oe)
|
||||
self.Base.logs.critical(f"OSError __create_socket: {oe} - {soc.fileno()}")
|
||||
except AttributeError as ae:
|
||||
self.Base.logs.critical(f"AttributeError: {ae} - {soc.fileno()}")
|
||||
self.Base.logs.critical(f"AttributeError __create_socket: {ae} - {soc.fileno()}")
|
||||
|
||||
def __ssl_context(self) -> ssl.SSLContext:
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
@@ -313,7 +311,7 @@ class Irc:
|
||||
|
||||
def send_response(self, responses:list[bytes]) -> None:
|
||||
try:
|
||||
# print(responses)
|
||||
# print(data)
|
||||
for data in responses:
|
||||
response = data.decode(self.CHARSET[0]).split()
|
||||
self.cmd(response)
|
||||
@@ -490,8 +488,7 @@ class Irc:
|
||||
self.Base.db_record_module(fromuser, module_name)
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} chargé")
|
||||
|
||||
# self.Base.logs.info(self.loaded_classes)
|
||||
self.Base.logs.info(f"Module {class_name} has been loaded")
|
||||
self.Base.logs.info(self.loaded_classes)
|
||||
return True
|
||||
|
||||
except ModuleNotFoundError as moduleNotFound:
|
||||
@@ -535,56 +532,6 @@ class Irc:
|
||||
self.Base.logs.error(f"General Error: {err}")
|
||||
return False
|
||||
|
||||
def reload_module(self, from_user: str, mod_name: str) -> bool:
|
||||
try:
|
||||
module_name = mod_name.lower() # ==> mod_defender
|
||||
class_name = module_name.split('_')[1].capitalize() # ==> Defender
|
||||
|
||||
if 'mods.' + module_name in sys.modules:
|
||||
self.Base.logs.info('Unload the module ...')
|
||||
self.loaded_classes[class_name].unload()
|
||||
self.Base.logs.info('Module Already Loaded ... reloading the module ...')
|
||||
the_module = sys.modules['mods.' + module_name]
|
||||
importlib.reload(the_module)
|
||||
|
||||
# Supprimer la class déja instancier
|
||||
if class_name in self.loaded_classes:
|
||||
# Supprimer les commandes déclarer dans la classe
|
||||
for level, command in self.loaded_classes[class_name].commands_level.items():
|
||||
# Supprimer la commande de la variable commands
|
||||
for c in self.loaded_classes[class_name].commands_level[level]:
|
||||
self.commands.remove(c)
|
||||
self.commands_level[level].remove(c)
|
||||
|
||||
del self.loaded_classes[class_name]
|
||||
|
||||
my_class = getattr(the_module, class_name, None)
|
||||
new_instance = my_class(self.ircObject)
|
||||
self.loaded_classes[class_name] = new_instance
|
||||
|
||||
self.Base.db_update_module(from_user, mod_name)
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} rechargé")
|
||||
return False
|
||||
else:
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} n'est pas chargé !")
|
||||
|
||||
except TypeError as te:
|
||||
self.Base.logs.error(f"A TypeError raised: {te}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :A TypeError raised: {te}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
except AttributeError as ae:
|
||||
self.Base.logs.error(f"Missing Attribute: {ae}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Missing Attribute: {ae}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
except KeyError as ke:
|
||||
self.Base.logs.error(f"Key Error: {ke}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Key Error: {ke}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
except Exception as e:
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to reload: {e}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Something went wrong with the module: {e}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
|
||||
def insert_db_admin(self, uid:str, level:int) -> None:
|
||||
|
||||
if self.User.get_User(uid) is None:
|
||||
@@ -882,13 +829,6 @@ class Irc:
|
||||
self.sendPrivMsg(msg=f'[{self.Config.COLORS.green}INFORMATION{self.Config.COLORS.nogc}] >> Defender is ready', channel=self.Config.SERVICE_CHANLOG)
|
||||
self.INIT = 0
|
||||
|
||||
# Send EOF to other modules
|
||||
for classe_name, classe_object in self.loaded_classes.items():
|
||||
classe_object.cmd(original_response)
|
||||
|
||||
# Stop here When EOS
|
||||
return None
|
||||
|
||||
case _:
|
||||
pass
|
||||
|
||||
@@ -1063,8 +1003,7 @@ class Irc:
|
||||
arg.remove(f':{self.Config.SERVICE_PREFIX}')
|
||||
if not arg[0].lower() in self.commands:
|
||||
self.Base.logs.debug(f"This command {arg[0]} is not available")
|
||||
self.sendNotice(f"This command [{self.Config.COLORS.bold}{arg[0]}{self.Config.COLORS.bold}] is not available", user_trigger)
|
||||
return None
|
||||
return False
|
||||
|
||||
cmd_to_send = convert_to_string.replace(':','')
|
||||
self.Base.log_cmd(user_trigger, cmd_to_send)
|
||||
@@ -1100,7 +1039,7 @@ class Irc:
|
||||
ping_response = current_unixtime - recieved_unixtime
|
||||
|
||||
self.send2socket(f'PONG :{recieved_unixtime}')
|
||||
self.send2socket(f':{dnickname} NOTICE {user_trigger} :\x01PING {ping_response} secs\x01')
|
||||
self.send2socket(f':{dnickname} NOTICE {user_trigger} :\x01PING {recieved_unixtime} secs\x01')
|
||||
return False
|
||||
|
||||
if not arg[0].lower() in self.commands:
|
||||
@@ -1409,21 +1348,14 @@ class Irc:
|
||||
batch_commands = ' | '.join(groupe)
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : {batch_commands}')
|
||||
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : ')
|
||||
|
||||
count_level_definition += 1
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : ')
|
||||
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : ***************** FIN DES COMMANDES *****************')
|
||||
|
||||
case 'load':
|
||||
try:
|
||||
# Load a module ex: .load mod_defender
|
||||
mod_name = str(cmd[1])
|
||||
self.load_module(fromuser, mod_name)
|
||||
except KeyError as ke:
|
||||
self.Base.logs.error(f"Key Error: {ke} - list recieved: {cmd}")
|
||||
except Exception as err:
|
||||
self.Base.logs.error(f"General Error: {ke} - list recieved: {cmd}")
|
||||
|
||||
self.load_module(fromuser, str(cmd[1]))
|
||||
|
||||
case 'unload':
|
||||
# unload mod_defender
|
||||
@@ -1434,10 +1366,50 @@ class Irc:
|
||||
self.Base.logs.error(f"General Error: {err}")
|
||||
|
||||
case 'reload':
|
||||
# reload mod_defender
|
||||
# reload mod_dktmb
|
||||
try:
|
||||
module_name = str(cmd[1]).lower() # ==> mod_defender
|
||||
self.reload_module(from_user=fromuser, mod_name=module_name)
|
||||
class_name = module_name.split('_')[1].capitalize() # ==> Defender
|
||||
|
||||
if 'mods.' + module_name in sys.modules:
|
||||
self.Base.logs.info('Unload the module ...')
|
||||
self.loaded_classes[class_name].unload()
|
||||
self.Base.logs.info('Module Already Loaded ... reloading the module ...')
|
||||
the_module = sys.modules['mods.' + module_name]
|
||||
importlib.reload(the_module)
|
||||
|
||||
# Supprimer la class déja instancier
|
||||
if class_name in self.loaded_classes:
|
||||
# Supprimer les commandes déclarer dans la classe
|
||||
for level, command in self.loaded_classes[class_name].commands_level.items():
|
||||
# Supprimer la commande de la variable commands
|
||||
for c in self.loaded_classes[class_name].commands_level[level]:
|
||||
self.commands.remove(c)
|
||||
self.commands_level[level].remove(c)
|
||||
|
||||
del self.loaded_classes[class_name]
|
||||
|
||||
my_class = getattr(the_module, class_name, None)
|
||||
new_instance = my_class(self.ircObject)
|
||||
self.loaded_classes[class_name] = new_instance
|
||||
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} rechargé")
|
||||
return False
|
||||
else:
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} n'est pas chargé !")
|
||||
|
||||
except TypeError as te:
|
||||
self.Base.logs.error(f"A TypeError raised: {te}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :A TypeError raised: {te}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
except AttributeError as ae:
|
||||
self.Base.logs.error(f"Missing Attribute: {ae}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Missing Attribute: {ae}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
except KeyError as ke:
|
||||
self.Base.logs.error(f"Key Error: {ke}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Key Error: {ke}")
|
||||
self.Base.db_delete_module(module_name)
|
||||
except Exception as e:
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to reload: {e}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Something went wrong with the module: {e}")
|
||||
@@ -1488,24 +1460,24 @@ class Irc:
|
||||
|
||||
self.Base.logs.debug(self.loaded_classes)
|
||||
all_modules = self.Base.get_all_modules()
|
||||
loaded = False
|
||||
|
||||
results = self.Base.db_execute_query(f'SELECT datetime, user, module_name FROM {self.Config.table_module}')
|
||||
results = self.Base.db_execute_query(f'SELECT module_name FROM {self.Config.table_module}')
|
||||
results = results.fetchall()
|
||||
|
||||
found = False
|
||||
|
||||
for module in all_modules:
|
||||
for loaded_mod in results:
|
||||
if module == loaded_mod[2]:
|
||||
loaded_datetime = loaded_mod[0]
|
||||
loaded_user = loaded_mod[1]
|
||||
loaded = True
|
||||
if module == loaded_mod[0]:
|
||||
found = True
|
||||
|
||||
if loaded:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :{module} - {self.Config.COLORS.green}Loaded{self.Config.COLORS.nogc} by {loaded_user} on {loaded_datetime}")
|
||||
loaded = False
|
||||
if found:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :{module} - {self.Config.COLORS.green}Loaded{self.Config.COLORS.nogc}")
|
||||
else:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :{module} - {self.Config.COLORS.red}Not Loaded{self.Config.COLORS.nogc}")
|
||||
|
||||
found = False
|
||||
|
||||
case 'show_timers':
|
||||
|
||||
if self.Base.running_timers:
|
||||
|
||||
@@ -60,7 +60,6 @@ class Clone():
|
||||
|
||||
self.Base.db_query_channel(action='add', module_name=self.module_name, channel_name=self.Config.CLONE_CHANNEL)
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} JOIN {self.Config.CLONE_CHANNEL}")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} SAMODE {self.Config.CLONE_CHANNEL} +o {self.Config.SERVICE_NICKNAME}")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} MODE {self.Config.CLONE_CHANNEL} +nts")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} MODE {self.Config.CLONE_CHANNEL} +k {self.Config.CLONE_CHANNEL_PASSWORD}")
|
||||
|
||||
@@ -127,8 +126,6 @@ class Clone():
|
||||
self.Irc.send2socket(f':{self.Config.SERVICE_NICKNAME} PRIVMSG {clone} :KILL')
|
||||
|
||||
self.Base.db_query_channel(action='del', module_name=self.module_name, channel_name=self.Config.CLONE_CHANNEL)
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} MODE {self.Config.CLONE_CHANNEL} -nts")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} MODE {self.Config.CLONE_CHANNEL} -k {self.Config.CLONE_CHANNEL_PASSWORD}")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} PART {self.Config.CLONE_CHANNEL}")
|
||||
return None
|
||||
|
||||
|
||||
@@ -150,7 +150,6 @@ class Command():
|
||||
try:
|
||||
message = ' '.join(cmd[3:])
|
||||
self.Irc.send2socket(f":{dnickname} NOTICE {self.user_to_notice} :[{red}ERROR MSG{nogc}] {message}")
|
||||
self.Base.logs.error(f"{cmd[1]} - {message}")
|
||||
except KeyError as ke:
|
||||
self.Base.logs.error(ke)
|
||||
except Exception as err:
|
||||
@@ -213,7 +212,6 @@ class Command():
|
||||
dnickname = self.Config.SERVICE_NICKNAME
|
||||
service_id = self.Config.SERVICE_ID
|
||||
dchanlog = self.Config.SERVICE_CHANLOG
|
||||
self.user_to_notice = user
|
||||
fromuser = user
|
||||
fromchannel = channel
|
||||
|
||||
|
||||
@@ -111,6 +111,9 @@ class Defender():
|
||||
self.__load_module_configuration()
|
||||
# End of mandatory methods you can start your customization #
|
||||
|
||||
# # Rejoindre les salons
|
||||
# self.join_saved_channels()
|
||||
|
||||
self.timeout = self.Config.API_TIMEOUT
|
||||
|
||||
# Listes qui vont contenir les ip a scanner avec les différentes API
|
||||
@@ -147,8 +150,7 @@ class Defender():
|
||||
self.Base.create_thread(func=self.thread_reputation_timer)
|
||||
|
||||
if self.ModConfig.reputation == 1:
|
||||
self.Irc.send2socket(f":{self.Config.SERVEUR_ID} SJOIN {self.Base.get_unixtime()} {self.Config.SALON_JAIL} + :{self.Config.SERVICE_NICKNAME}")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} SAMODE {self.Config.SALON_JAIL} +o {self.Config.SERVICE_NICKNAME}")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_ID} SAMODE {self.Config.SALON_JAIL} +{self.Config.SERVICE_UMODES} {self.Config.SERVICE_NICKNAME}")
|
||||
|
||||
return None
|
||||
|
||||
@@ -247,6 +249,40 @@ class Defender():
|
||||
self.reputationTimer_isRunning:bool = False
|
||||
return None
|
||||
|
||||
def add_defender_channel(self, channel:str) -> bool:
|
||||
"""Cette fonction ajoute les salons de join de Defender
|
||||
|
||||
Args:
|
||||
channel (str): le salon à enregistrer.
|
||||
"""
|
||||
mes_donnees = {'channel': channel}
|
||||
response = self.Base.db_execute_query("SELECT id FROM def_channels WHERE channel = :channel", mes_donnees)
|
||||
|
||||
isChannelExist = response.fetchone()
|
||||
|
||||
if isChannelExist is None:
|
||||
mes_donnees = {'datetime': self.Base.get_datetime(), 'channel': channel}
|
||||
insert = self.Base.db_execute_query(f"INSERT INTO def_channels (datetime, channel) VALUES (:datetime, :channel)", mes_donnees)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def delete_defender_channel(self, channel:str) -> bool:
|
||||
"""Cette fonction supprime les salons de join de Defender
|
||||
|
||||
Args:
|
||||
channel (str): le salon à enregistrer.
|
||||
"""
|
||||
mes_donnes = {'channel': channel}
|
||||
response = self.Base.db_execute_query("DELETE FROM def_channels WHERE channel = :channel", mes_donnes)
|
||||
|
||||
affected_row = response.rowcount
|
||||
|
||||
if affected_row > 0:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def reputation_insert(self, reputationModel: ReputationModel) -> bool:
|
||||
|
||||
response = False
|
||||
@@ -336,7 +372,7 @@ class Defender():
|
||||
|
||||
def join_saved_channels(self) -> None:
|
||||
|
||||
result = self.Base.db_execute_query(f"SELECT distinct channel_name FROM {self.Config.table_channel}")
|
||||
result = self.Base.db_execute_query("SELECT id, channel FROM def_channels")
|
||||
channels = result.fetchall()
|
||||
jail_chan = self.Config.SALON_JAIL
|
||||
jail_chan_mode = self.Config.SALON_JAIL_MODES
|
||||
@@ -347,7 +383,7 @@ class Defender():
|
||||
unixtime = self.Base.get_unixtime()
|
||||
|
||||
for channel in channels:
|
||||
chan = channel[0]
|
||||
id, chan = channel
|
||||
self.Irc.send2socket(f":{self.Config.SERVEUR_ID} SJOIN {unixtime} {chan} + :{self.Config.SERVICE_ID}")
|
||||
if chan == jail_chan:
|
||||
self.Irc.send2socket(f":{service_id} SAMODE {jail_chan} +{dumodes} {dnickname}")
|
||||
@@ -964,12 +1000,19 @@ class Defender():
|
||||
self.Logs.error(f"Thread_cloudfilt_scan Error : {ve}")
|
||||
|
||||
def cmd(self, data: list) -> None:
|
||||
try:
|
||||
|
||||
service_id = self.Config.SERVICE_ID # Defender serveur id
|
||||
cmd = list(data).copy()
|
||||
|
||||
if len(cmd) < 2:
|
||||
return None
|
||||
|
||||
match cmd[1]:
|
||||
|
||||
case 'EOS':
|
||||
if self.Irc.INIT == 0:
|
||||
self.Irc.send2socket(f":{service_id} SAMODE {self.Config.SALON_JAIL} +{self.Config.SERVICE_UMODES} {self.Config.SERVICE_NICKNAME}")
|
||||
|
||||
case 'REPUTATION':
|
||||
# :001 REPUTATION 91.168.141.239 118
|
||||
try:
|
||||
@@ -986,23 +1029,8 @@ class Defender():
|
||||
except IndexError as ie:
|
||||
self.Logs.error(f'cmd reputation: index error: {ie}')
|
||||
|
||||
if len(cmd) < 3:
|
||||
return None
|
||||
|
||||
match cmd[2]:
|
||||
|
||||
case 'MODE':
|
||||
# ['...', ':001XSCU0Q', 'MODE', '#jail', '+b', '~security-group:unknown-users']
|
||||
channel = str(cmd[3])
|
||||
mode = str(cmd[4])
|
||||
group_to_check = str(cmd[5:])
|
||||
group_to_unban = '~security-group:unknown-users'
|
||||
|
||||
if self.Config.SALON_JAIL == channel:
|
||||
if mode == '+b' and group_to_unban in group_to_check:
|
||||
self.Irc.send2socket(f":{service_id} MODE {self.Config.SALON_JAIL} -b ~security-group:unknown-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {self.Config.SALON_JAIL} -eee ~security-group:webirc-users ~security-group:known-users ~security-group:websocket-users")
|
||||
|
||||
case 'PRIVMSG':
|
||||
cmd.pop(0)
|
||||
user_trigger = str(cmd[0]).replace(':','')
|
||||
@@ -1068,7 +1096,6 @@ class Defender():
|
||||
|
||||
get_reputation = self.reputation_get_Reputation(parsed_UID)
|
||||
|
||||
if parsed_chan != self.Config.SALON_JAIL:
|
||||
self.Irc.send2socket(f":{service_id} MODE {parsed_chan} +b ~security-group:unknown-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {parsed_chan} +eee ~security-group:webirc-users ~security-group:known-users ~security-group:websocket-users")
|
||||
|
||||
@@ -1158,13 +1185,6 @@ class Defender():
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -b {final_nickname}!*@*")
|
||||
self.reputation_delete(final_UID)
|
||||
|
||||
except KeyError as ke:
|
||||
self.Logs.error(f"{ke} / {cmd} / length {str(len(cmd))}")
|
||||
except IndexError as ie:
|
||||
self.Logs.error(f"{ie} / {cmd} / length {str(len(cmd))}")
|
||||
except Exception as err:
|
||||
self.Logs.error(f"General Error: {err}")
|
||||
|
||||
def _hcmds(self, user:str, channel: any, cmd: list, fullcmd: list = []) -> None:
|
||||
|
||||
command = str(cmd[0]).lower()
|
||||
|
||||
@@ -10,7 +10,8 @@ class Jsonrpc():
|
||||
class ModConfModel:
|
||||
"""The Model containing the module parameters
|
||||
"""
|
||||
jsonrpc: int = 0
|
||||
param_exemple1: str
|
||||
param_exemple2: int
|
||||
|
||||
def __init__(self, ircInstance:Irc) -> None:
|
||||
|
||||
@@ -58,21 +59,9 @@ class Jsonrpc():
|
||||
self.__load_module_configuration()
|
||||
# End of mandatory methods you can start your customization #
|
||||
|
||||
# self.UnrealIrcdRpcLive: Live = Live(
|
||||
# req_method='unixsocket',
|
||||
# path_to_socket_file=self.Config.JSONRPC_PATH_TO_SOCKET_FILE,
|
||||
# callback_object_instance=self,
|
||||
# callback_method_name='callback_sent_to_irc'
|
||||
# )
|
||||
|
||||
self.UnrealIrcdRpcLive: Live = Live(
|
||||
req_method='websocket',
|
||||
url=self.Config.JSONRPC_URL,
|
||||
username=self.Config.JSONRPC_USER,
|
||||
password=self.Config.JSONRPC_PASSWORD,
|
||||
self.UnrealIrcdRpcLive: Live = Live(path_to_socket_file=self.Config.JSONRPC_PATH_TO_SOCKET_FILE,
|
||||
callback_object_instance=self,
|
||||
callback_method_name='callback_sent_to_irc',
|
||||
debug_level=10
|
||||
callback_method_name='callback_sent_to_irc'
|
||||
)
|
||||
|
||||
self.Rpc: Loader = Loader(
|
||||
@@ -90,9 +79,6 @@ class Jsonrpc():
|
||||
if self.UnrealIrcdRpcLive.Error.code != 0:
|
||||
self.Irc.sendPrivMsg(f"[{self.Config.COLORS.red}ERROR{self.Config.COLORS.nogc}] {self.UnrealIrcdRpcLive.Error.message}", self.Config.SERVICE_CHANLOG)
|
||||
|
||||
if self.ModConfig.jsonrpc == 1:
|
||||
self.Base.create_thread(self.thread_start_jsonrpc, run_once=True)
|
||||
|
||||
return None
|
||||
|
||||
def __set_commands(self, commands:dict[int, list[str]]) -> None:
|
||||
@@ -165,10 +151,10 @@ class Jsonrpc():
|
||||
"""
|
||||
try:
|
||||
# Build the default configuration model (Mandatory)
|
||||
self.ModConfig = self.ModConfModel(jsonrpc=0)
|
||||
self.ModConfig = self.ModConfModel(param_exemple1='param value 1', param_exemple2=1)
|
||||
|
||||
# Sync the configuration with core configuration (Mandatory)
|
||||
self.Base.db_sync_core_config(self.module_name, self.ModConfig)
|
||||
#self.Base.db_sync_core_config(self.module_name, self.ModConfig)
|
||||
|
||||
return None
|
||||
|
||||
@@ -197,7 +183,6 @@ class Jsonrpc():
|
||||
|
||||
command = str(cmd[0]).lower()
|
||||
dnickname = self.Config.SERVICE_NICKNAME
|
||||
dchannel = self.Config.SERVICE_CHANLOG
|
||||
fromuser = user
|
||||
fromchannel = str(channel) if not channel is None else None
|
||||
|
||||
@@ -214,19 +199,10 @@ class Jsonrpc():
|
||||
match option:
|
||||
|
||||
case 'on':
|
||||
for thread in self.Base.running_threads:
|
||||
if thread.getName() == 'thread_start_jsonrpc':
|
||||
if thread.is_alive():
|
||||
self.Irc.sendPrivMsg(f"Thread {thread.getName()} is running", dchannel)
|
||||
else:
|
||||
self.Irc.sendPrivMsg(f"Thread {thread.getName()} is not running, wait untill the process will be cleaned up", dchannel)
|
||||
|
||||
self.Base.create_thread(self.thread_start_jsonrpc, run_once=True)
|
||||
self.__update_configuration('jsonrpc', 1)
|
||||
|
||||
case 'off':
|
||||
self.UnrealIrcdRpcLive.unsubscribe()
|
||||
self.__update_configuration('jsonrpc', 0)
|
||||
|
||||
except IndexError as ie:
|
||||
self.Logs.error(ie)
|
||||
@@ -276,9 +252,6 @@ class Jsonrpc():
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :CLIENT PORT : {UserInfo.client_port}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :SERVER PORT : {UserInfo.server_port}')
|
||||
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :CERTFP : {UserInfo.tls.certfp}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :CIPHER : {UserInfo.tls.cipher}')
|
||||
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :IDLE SINCE : {UserInfo.idle_since}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :CONNECTED SINCE : {UserInfo.connected_since}')
|
||||
|
||||
|
||||
@@ -124,16 +124,8 @@ class Test():
|
||||
return None
|
||||
|
||||
def cmd(self, data:list) -> None:
|
||||
try:
|
||||
cmd = list(data).copy()
|
||||
|
||||
return None
|
||||
except KeyError as ke:
|
||||
self.Base.logs.error(f"Key Error: {ke}")
|
||||
except IndexError as ie:
|
||||
self.Base.logs.error(f"{ie} / {cmd} / length {str(len(cmd))}")
|
||||
except Exception as err:
|
||||
self.Base.logs.error(f"General Error: {err}")
|
||||
|
||||
def _hcmds(self, user:str, channel: any, cmd: list, fullcmd: list = []) -> None:
|
||||
|
||||
|
||||
@@ -242,16 +242,15 @@ class Votekick():
|
||||
return None
|
||||
|
||||
def cmd(self, data:list) -> None:
|
||||
try:
|
||||
cmd = list(data).copy()
|
||||
return None
|
||||
|
||||
except KeyError as ke:
|
||||
self.Base.logs.error(f"Key Error: {ke}")
|
||||
except IndexError as ie:
|
||||
self.Base.logs.error(f"{ie} / {cmd} / length {str(len(cmd))}")
|
||||
except Exception as err:
|
||||
self.Base.logs.error(f"General Error: {err}")
|
||||
match cmd[2]:
|
||||
case 'SJOIN':
|
||||
pass
|
||||
case _:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
def _hcmds(self, user:str, channel: any, cmd: list, fullcmd: list = []) -> None:
|
||||
# cmd is the command starting from the user command
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
{
|
||||
"version": "5.4.0",
|
||||
|
||||
"requests": "2.32.3",
|
||||
"psutil": "6.0.0",
|
||||
"unrealircd_rpc_py": "1.0.6",
|
||||
"sqlalchemy": "2.0.35",
|
||||
"faker": "30.1.0"
|
||||
"version": "5.3.4"
|
||||
}
|
||||
Reference in New Issue
Block a user