mirror of
https://github.com/iio612/DEFENDER.git
synced 2026-02-13 19:24:23 +00:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31fe9f62ec | ||
|
|
637cd7e9d2 | ||
|
|
933509b1b6 | ||
|
|
290d7123fd | ||
|
|
f0853e3afb | ||
|
|
88b9b056ca | ||
|
|
6dade09257 | ||
|
|
d7fab2d701 | ||
|
|
9533b010b2 | ||
|
|
dbfc04a936 | ||
|
|
824db73590 | ||
|
|
bfb449f804 | ||
|
|
96bf4b6f80 | ||
|
|
8c772f5882 | ||
|
|
922336363e |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -3,4 +3,5 @@ db/
|
||||
logs/
|
||||
__pycache__/
|
||||
configuration.json
|
||||
install.log
|
||||
test.py
|
||||
140
README.md
140
README.md
@@ -2,70 +2,104 @@
|
||||
Defender est un service IRC basé sur la sécurité des réseaux IRC ( UnrealIRCD )
|
||||
Il permet d'ajouter une sécurité supplémentaire pour vérifier les users connectés au réseau
|
||||
en demandant aux user un code de validation.
|
||||
Il permet aux opérateurs de gérer efficacement un canal, tout en offrant aux utilisateurs des outils d'interaction et de décision collective.
|
||||
|
||||
Pré-requis :
|
||||
# Fonctionnalités principales
|
||||
Commandes opérateurs complètes:
|
||||
Kick: Expulser un utilisateur du canal.
|
||||
Ban: Interdire définitivement l'accès au canal.
|
||||
Unban: Lever une interdiction.
|
||||
Op/Deop: Attribuer ou retirer les droits d'opérateur.
|
||||
Halfop/Dehalfop: Attribuer ou retirer les droits
|
||||
Voice/Devoice: Attribuer ou retirer les droits de voix.
|
||||
|
||||
- Python version >= 3.10
|
||||
- Pip de python installé sur la machine
|
||||
- Python librairies psutil & sqlalchemy & requests
|
||||
- IRC Serveur Version >= UnrealIRCd-6.1.2.2
|
||||
Système de quarantaine:
|
||||
Mise en quarantaine: Isoler temporairement un utilisateur dans un canal privé.
|
||||
Libération: Permettre à un utilisateur de quitter la quarantaine en entrant un code spécifique.
|
||||
|
||||
Lancement de Defender :
|
||||
Système de vote:
|
||||
Kick: Les utilisateurs peuvent voter pour expulser un membre du canal.
|
||||
Autres actions: Possibilité d'étendre le système de vote à d'autres actions (ban, etc.).
|
||||
|
||||
- Installer les librairies python : psutil & sqlalchemy & requests
|
||||
- pip3 install psutil sqlalchemy requests ou pip install psutil sqlalchemy requests
|
||||
- Ne pas lancer Defender en tant que root
|
||||
- Créer plutot un service qui lancera Defender en tant qu'utilisateur non root
|
||||
- Un fichier PID sera crée.
|
||||
# Installation automatique sur une machine Debian/Ubuntu
|
||||
|
||||
# TO DO LIST
|
||||
Prérequis:
|
||||
- Système d'exploitation Linux (Windows non supporté)
|
||||
- Droits d'administrateur (root) pour l'exécution du script
|
||||
- Python version 3.10 ou supérieure
|
||||
|
||||
- Optimiser le systeme de réputation:
|
||||
- lorsque les users ce connectent, Ils entrent dans un salon puis une fraction de seconde le service les bans
|
||||
Bash:
|
||||
$ git clone https://github.com/adator85/IRC_DEFENDER_MODULES.git
|
||||
- Renommer le fichier exemple_configuration.json en configuration.json
|
||||
- Configurer le fichier configuration.json
|
||||
$ sudo python3 install.py
|
||||
|
||||
# VERSION 1
|
||||
Si votre configuration est bonne, votre service est censé etre connecté a votre réseau IRC
|
||||
|
||||
[02.01.2024]
|
||||
- Rajout de l'activation de la commande flood
|
||||
- Les deux variables RESTART et INIT ont été déplacées vers le module Irc
|
||||
- Nouvelle class Install:
|
||||
- Le programme va vérifier si les 3 librairies sont installées (SQLAlchemy & requests & psutil)
|
||||
- Une fois la vérification, il va mêtre a jour pip puis installera les dépendances
|
||||
# Installation manuelle:
|
||||
Bash:
|
||||
$ git clone https://github.com/adator85/IRC_DEFENDER_MODULES.git
|
||||
$ cd IRC_DEFENDER_MODULES
|
||||
$ python3 -m venv .pyenv
|
||||
$ source .pyenv/bin/activate
|
||||
- Créer un service nommé "Defender.service" pour votre service et placer le dans "/etc/systemd/system/"
|
||||
$ sudo systemctl start Defender
|
||||
|
||||
[28.12.2023]
|
||||
- Changement de méthode pour récuperer la version actuelle de python
|
||||
- Ajout de la réponse a une PING de la part d'un utilisateur
|
||||
- Installation automatique des packages sqlalchemy, requests et psutil
|
||||
# Configuration
|
||||
|
||||
# BUG FIX
|
||||
SERVEUR (Serveur)
|
||||
SERVEUR_IP: Adresse IP du serveur IRC à rejoindre.
|
||||
SERVEUR_HOSTNAME: Nom d'hôte du serveur IRC à rejoindre (optionnel).
|
||||
SERVEUR_LINK: Lien vers le serveur IRC (optionnel).
|
||||
SERVEUR_PORT: Port de connexion au serveur IRC.
|
||||
SERVEUR_PASSWORD: Mot de passe d'enregistrement du service sur le serveur IRC.
|
||||
SERVEUR_ID: Identifiant unique du service.
|
||||
SERVEUR_SSL: Active la connexion SSL sécurisée au serveur IRC (true/false).
|
||||
SERVICE (Service)
|
||||
SERVICE_NAME: Nom du service IRC.
|
||||
SERVICE_NICKNAME: Surnom utilisé par le service sur le serveur IRC.
|
||||
SERVICE_REALNAME: Nom réel du service affiché sur le serveur IRC.
|
||||
SERVICE_USERNAME: Nom d'utilisateur utilisé par le service pour se connecter au serveur IRC.
|
||||
SERVICE_HOST: Nom d'hôte du service affiché sur le serveur IRC (optionnel).
|
||||
SERVICE_INFO: Description du service.
|
||||
SERVICE_CHANLOG: Canal utilisé pour la journalisation des actions du service.
|
||||
SERVICE_SMODES: Modes serveur appliqués aux canaux rejoints par le service.
|
||||
SERVICE_CMODES: Modes de canal appliqués aux canaux rejoints par le service.
|
||||
SERVICE_UMODES: Modes utilisateur appliqués au service.
|
||||
SERVICE_PREFIX: Caractère utilisé comme préfixe des commandes du service.
|
||||
COMPTE (Compte)
|
||||
OWNER: Nom d'utilisateur possédant les droits d'administration du service.
|
||||
PASSWORD: Mot de passe de l'administrateur du service.
|
||||
CANAUX (Canaux)
|
||||
SALON_JAIL: Canal utilisé comme prison pour les utilisateurs sanctionnés.
|
||||
SALON_JAIL_MODES: Modes appliqués au canal de prison.
|
||||
SALON_LIBERER: Canal utilisé pour la libération des utilisateurs sanctionnés.
|
||||
API (API)
|
||||
API_TIMEOUT: Durée maximale d'attente d'une réponse de l'API en secondes.
|
||||
SCANNER (Scanner)
|
||||
PORTS_TO_SCAN: Liste des ports à scanner pour détecter des serveurs potentiellement malveillants.
|
||||
SÉCURITÉ (Sécurité)
|
||||
WHITELISTED_IP: Liste d'adresses IP autorisées à contourner certaines restrictions.
|
||||
GLINE_DURATION: Durée de bannissement temporaire d'un utilisateur en minutes.
|
||||
DEBUG (Debug)
|
||||
DEBUG_LEVEL: Niveau de verbosité des messages de debug (plus grand est le nombre, plus il y a d'informations).
|
||||
COULEURS (Couleurs)
|
||||
CONFIG_COLOR: Dictionnaire contenant des codes de couleurs IRC pour un meilleur affichage des messages.
|
||||
|
||||
[29.12.2023]
|
||||
- Correction des messages de receptions trop longs > 4070 caractéres;
|
||||
- la méthode boucle et incrémente la réponse tant que le nombre de caractére reçu est supérieur a 4072
|
||||
- Rajout du protocol MTAGS a la connexion du service
|
||||
- Impact majeur dans la lecture des messages reçu du serveur ( PRIVMSG, SLOGS, UID, QUIT, NICK, PONG, SJOIN)
|
||||
Modification de la configuration
|
||||
|
||||
# ALREADY IMPLEMENTED
|
||||
Vous devez modifier le fichier config.json en remplaçant les valeurs par défaut avec vos propres informations. Assurez-vous de bien lire la description de chaque paramètre pour une configuration optimale du service.
|
||||
|
||||
- Connexion en tant que service
|
||||
- Gestion des messages reçus/envoyés par le serveur
|
||||
- Gestion des caractéres spéciaux
|
||||
- Gestion des logs (salon, fichiers et console)
|
||||
- Mode debug : gestion des logs coté console
|
||||
- Création du systeme de gestion de commandes
|
||||
- Defender reconnait les commandes qui commence par le suffix définit dans la configuration
|
||||
- Defender reconnait aussi reconnaitre les commandes qui viennent de /msg Defender [commande]
|
||||
- Identifications
|
||||
- Systéme d'identification [OK]
|
||||
- Systéme de changement d'information [OK]
|
||||
- Suppression d'un admin
|
||||
- Systéme de groupe d'accés [OK]
|
||||
Attention
|
||||
|
||||
Reputation security
|
||||
- Activation ou désaction du systéme --> OK | .reputation ON/off
|
||||
- Le user sera en mesure de changer la limite de la réputation --> OK | .reputation set limit 120
|
||||
- Defender devra envoyer l'utilisateur dans un salon définit dans la configuration --> OK
|
||||
- Defender bannira l'utilisateur de la totalité des salons, il le bannira aussi lorsqu'il souhaitera accéder a de nouveau salon --> OK
|
||||
- Defender devra envoyer un message du type "Merci de taper cette comande /msg {nomdudefender} code {un code générer aléatoirement} --> OK
|
||||
- Defender devra reconnaitre le code --> OK
|
||||
- Defender devra liberer l'utilisateur et l'envoyer vers un salon définit dans la configuration --> OK
|
||||
Le mot de passe de l'administrateur et le mot de passe du service doivent être modifiés pour des raisons de sécurité.
|
||||
Ne partagez pas vos informations de connexion au serveur IRC avec des tiers.
|
||||
|
||||
#Extension:
|
||||
Le code est modulaire et conçu pour être facilement étendu. Vous pouvez ajouter de nouvelles commandes, de nouvelles fonctionnalités (mods/mod_test.py est un exemple pour bien demarrer la création de son module).
|
||||
|
||||
# Contributions:
|
||||
Les contributions sont les bienvenues ! N'hésitez pas à ouvrir des issues ou des pull requests.
|
||||
|
||||
# Avertissement:
|
||||
Ce bot est fourni "tel quel" sans aucune garantie. Utilisez-le à vos risques et périls.
|
||||
@@ -38,8 +38,10 @@ class User:
|
||||
|
||||
for record in self.UID_DB:
|
||||
if record.uid == newUser.uid:
|
||||
# If the user exist then return False and do not go further
|
||||
exist = True
|
||||
self.log.debug(f'{record.uid} already exist')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
self.UID_DB.append(newUser)
|
||||
@@ -65,9 +67,11 @@ class User:
|
||||
|
||||
for record in self.UID_DB:
|
||||
if record.uid == uid:
|
||||
# If the user exist then update and return True and do not go further
|
||||
record.nickname = newNickname
|
||||
result = True
|
||||
self.log.debug(f'UID ({record.uid}) has been updated with new nickname {newNickname}')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.log.critical(f'The new nickname {newNickname} was not updated, uid = {uid}')
|
||||
@@ -87,9 +91,11 @@ class User:
|
||||
|
||||
for record in self.UID_DB:
|
||||
if record.uid == uid:
|
||||
# If the user exist then remove and return True and do not go further
|
||||
self.UID_DB.remove(record)
|
||||
result = True
|
||||
self.log.debug(f'UID ({record.uid}) has been deleted')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.log.critical(f'The UID {uid} was not deleted')
|
||||
@@ -179,8 +185,10 @@ class Admin:
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == newAdmin.uid:
|
||||
# If the admin exist then return False and do not go further
|
||||
exist = True
|
||||
self.log.debug(f'{record.uid} already exist')
|
||||
return result
|
||||
|
||||
if not exist:
|
||||
self.UID_ADMIN_DB.append(newAdmin)
|
||||
@@ -191,37 +199,41 @@ class Admin:
|
||||
self.log.critical(f'The User Object was not inserted {newAdmin}')
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def update(self, uid: str, newNickname: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == uid:
|
||||
# If the admin exist, update and do not go further
|
||||
record.nickname = newNickname
|
||||
result = True
|
||||
self.log.debug(f'UID ({record.uid}) has been updated with new nickname {newNickname}')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.log.critical(f'The new nickname {newNickname} was not updated, uid = {uid}')
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def delete(self, uid: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_ADMIN_DB:
|
||||
if record.uid == uid:
|
||||
# If the admin exist, delete and do not go further
|
||||
self.UID_ADMIN_DB.remove(record)
|
||||
result = True
|
||||
self.log.debug(f'UID ({record.uid}) has been created')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.log.critical(f'The UID {uid} was not deleted')
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_Admin(self, uidornickname: str) -> Union[AdminModel, None]:
|
||||
|
||||
Admin = None
|
||||
@@ -263,10 +275,19 @@ class Channel:
|
||||
@dataclass
|
||||
class ChannelModel:
|
||||
name: str
|
||||
mode: str
|
||||
"""### Channel name
|
||||
It include the #"""
|
||||
uids: list
|
||||
"""### List of UID available in the channel
|
||||
including their modes ~ @ % + *
|
||||
|
||||
Returns:
|
||||
list: The list of UID's including theirs modes
|
||||
"""
|
||||
|
||||
UID_CHANNEL_DB: list[ChannelModel] = []
|
||||
"""List that contains all the Channels objects (ChannelModel)
|
||||
"""
|
||||
|
||||
def __init__(self, Base: Base) -> None:
|
||||
self.log = Base.logs
|
||||
@@ -274,15 +295,23 @@ class Channel:
|
||||
pass
|
||||
|
||||
def insert(self, newChan: ChannelModel) -> bool:
|
||||
"""This method will insert a new channel and if the channel exist it will update the user list (uids)
|
||||
|
||||
Args:
|
||||
newChan (ChannelModel): The channel model object
|
||||
|
||||
Returns:
|
||||
bool: True if new channel, False if channel exist (However UID could be updated)
|
||||
"""
|
||||
result = False
|
||||
exist = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == newChan.name:
|
||||
# If the channel exist, update the user list and do not go further
|
||||
exist = True
|
||||
self.log.debug(f'{record.name} already exist')
|
||||
|
||||
|
||||
for user in newChan.uids:
|
||||
record.uids.append(user)
|
||||
|
||||
@@ -290,9 +319,11 @@ class Channel:
|
||||
del_duplicates = list(set(record.uids))
|
||||
record.uids = del_duplicates
|
||||
self.log.debug(f'Updating a new UID to the channel {record}')
|
||||
return result
|
||||
|
||||
|
||||
if not exist:
|
||||
# If the channel don't exist, then create it
|
||||
self.UID_CHANNEL_DB.append(newChan)
|
||||
result = True
|
||||
self.log.debug(f'New Channel Created: ({newChan})')
|
||||
@@ -302,30 +333,18 @@ class Channel:
|
||||
|
||||
return result
|
||||
|
||||
def update(self, name: str, newMode: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == name:
|
||||
record.mode = newMode
|
||||
result = True
|
||||
self.log.debug(f'Mode ({record.name}) has been updated with new mode {newMode}')
|
||||
|
||||
if not result:
|
||||
self.log.critical(f'The channel mode {newMode} was not updated, name = {name}')
|
||||
|
||||
return result
|
||||
|
||||
def delete(self, name: str) -> bool:
|
||||
|
||||
result = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == name:
|
||||
# If the channel exist, then remove it and return True.
|
||||
# As soon as the channel found, return True and stop the loop
|
||||
self.UID_CHANNEL_DB.remove(record)
|
||||
result = True
|
||||
self.log.debug(f'Channel ({record.name}) has been created')
|
||||
return result
|
||||
|
||||
if not result:
|
||||
self.log.critical(f'The Channel {name} was not deleted')
|
||||
@@ -341,13 +360,33 @@ class Channel:
|
||||
for user_id in record.uids:
|
||||
if self.Base.clean_uid(user_id) == uid:
|
||||
record.uids.remove(user_id)
|
||||
self.log.debug(f'uid {uid} has been removed, here is the new object: {record}')
|
||||
self.log.debug(f'The UID {uid} has been removed, here is the new object: {record}')
|
||||
result = True
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if not record.uids:
|
||||
self.UID_CHANNEL_DB.remove(record)
|
||||
self.log.debug(f'Channel {record.name} has been removed, here is the new object: {record}')
|
||||
self.log.debug(f'The Channel {record.name} has been removed, here is the new object: {record}')
|
||||
|
||||
return result
|
||||
except ValueError as ve:
|
||||
self.log.error(f'{ve}')
|
||||
|
||||
def delete_user_from_all_channel(self, uid:str) -> bool:
|
||||
try:
|
||||
result = False
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
for user_id in record.uids:
|
||||
if self.Base.clean_uid(user_id) == self.Base.clean_uid(uid):
|
||||
record.uids.remove(user_id)
|
||||
self.log.debug(f'The UID {uid} has been removed, here is the new object: {record}')
|
||||
result = True
|
||||
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if not record.uids:
|
||||
self.UID_CHANNEL_DB.remove(record)
|
||||
self.log.debug(f'The Channel {record.name} has been removed, here is the new object: {record}')
|
||||
|
||||
return result
|
||||
except ValueError as ve:
|
||||
@@ -363,13 +402,3 @@ class Channel:
|
||||
self.log.debug(f'Search {name} -- result = {Channel}')
|
||||
|
||||
return Channel
|
||||
|
||||
def get_mode(self, name:str) -> Union[str, None]:
|
||||
|
||||
mode = None
|
||||
for record in self.UID_CHANNEL_DB:
|
||||
if record.name == name:
|
||||
mode = record.mode
|
||||
|
||||
self.log.debug(f'The mode of the channel {name} has been found: {mode}')
|
||||
return mode
|
||||
|
||||
18
core/base.py
18
core/base.py
@@ -56,9 +56,9 @@ class Base:
|
||||
}
|
||||
|
||||
if token == '':
|
||||
response = requests.get(json_url)
|
||||
response = requests.get(json_url, timeout=self.Config.API_TIMEOUT)
|
||||
else:
|
||||
response = requests.get(json_url, headers=headers)
|
||||
response = requests.get(json_url, headers=headers, timeout=self.Config.API_TIMEOUT)
|
||||
|
||||
response.raise_for_status() # Vérifie si la requête a réussi
|
||||
json_response:dict = response.json()
|
||||
@@ -120,6 +120,16 @@ class Base:
|
||||
currentdate = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
|
||||
return currentdate
|
||||
|
||||
def get_all_modules(self) -> list:
|
||||
|
||||
all_files = os.listdir('mods/')
|
||||
all_modules: list = []
|
||||
for module in all_files:
|
||||
if module.endswith('.py') and not module == '__init__.py':
|
||||
all_modules.append(module.replace('.py', '').lower())
|
||||
|
||||
return all_modules
|
||||
|
||||
def create_log(self, log_message: str) -> None:
|
||||
"""Enregiste les logs
|
||||
|
||||
@@ -302,7 +312,7 @@ class Base:
|
||||
if thread.getName() != 'heartbeat':
|
||||
if not thread.is_alive():
|
||||
self.running_threads.remove(thread)
|
||||
self.logs.debug(f"Thread {str(thread.getName())} {str(thread.native_id)} removed")
|
||||
self.logs.info(f"Thread {str(thread.getName())} {str(thread.native_id)} removed")
|
||||
|
||||
# print(threading.enumerate())
|
||||
except AssertionError as ae:
|
||||
@@ -522,7 +532,7 @@ class Base:
|
||||
parsed_UID = re.sub(pattern, '', uid)
|
||||
|
||||
return parsed_UID
|
||||
|
||||
|
||||
def Is_Channel(self, channelToCheck: str) -> bool:
|
||||
"""Check if the string has the # caractere and return True if this is a channel
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
from importlib.util import find_spec
|
||||
from subprocess import check_call, run
|
||||
from platform import python_version
|
||||
from subprocess import check_call, run, CalledProcessError
|
||||
from platform import python_version, python_version_tuple
|
||||
from sys import exit
|
||||
import os
|
||||
|
||||
class Install:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.PYTHON_MIN_VERSION = '3.10'
|
||||
|
||||
self.venv_folder_name = '.pyenv'
|
||||
self.cmd_venv_command = ['python3', '-m', 'venv', self.venv_folder_name]
|
||||
self.module_to_install = ['sqlalchemy','psutil','requests']
|
||||
|
||||
if not self.checkPythonVersion():
|
||||
@@ -24,20 +28,36 @@ class Install:
|
||||
Returns:
|
||||
bool: True si la version de python est autorisé sinon False
|
||||
"""
|
||||
python_required_version = self.PYTHON_MIN_VERSION.split('.')
|
||||
python_current_version = python_version().split('.')
|
||||
# Current system version
|
||||
sys_major, sys_minor, sys_patch = python_version_tuple()
|
||||
|
||||
if int(python_current_version[0]) < int(python_required_version[0]):
|
||||
# min python version required
|
||||
python_required_version = self.PYTHON_MIN_VERSION.split('.')
|
||||
min_major, min_minor = tuple((python_required_version[0], python_required_version[1]))
|
||||
|
||||
if int(sys_major) < int(min_major):
|
||||
print(f"## Your python version must be greather than or equal to {self.PYTHON_MIN_VERSION} ##")
|
||||
return False
|
||||
elif int(python_current_version[1]) < int(python_required_version[1]):
|
||||
print(f"### Your python version must be greather than or equal to {self.PYTHON_MIN_VERSION} ###")
|
||||
|
||||
elif (int(sys_major) <= int(min_major)) and (int(sys_minor) < int(min_minor)):
|
||||
print(f"## Your python version must be greather than or equal to {self.PYTHON_MIN_VERSION} ##")
|
||||
return False
|
||||
|
||||
print(f"===> Version of python : {python_version()} ==> OK")
|
||||
|
||||
return True
|
||||
|
||||
def run_subprocess(self, command:list) -> None:
|
||||
|
||||
print(command)
|
||||
try:
|
||||
check_call(command)
|
||||
print("La commande s'est terminée avec succès.")
|
||||
except CalledProcessError as e:
|
||||
print(f"La commande a échoué avec le code de retour :{e.returncode}")
|
||||
print(f"Try to install dependencies ...")
|
||||
exit(5)
|
||||
|
||||
def checkDependencies(self) -> None:
|
||||
"""### Verifie les dépendances si elles sont installées
|
||||
- Test si les modules sont installés
|
||||
@@ -46,6 +66,11 @@ class Install:
|
||||
"""
|
||||
do_install = False
|
||||
|
||||
# Check if virtual env exist
|
||||
if not os.path.exists(f'{self.venv_folder_name}'):
|
||||
self.run_subprocess(self.cmd_venv_command)
|
||||
do_install = True
|
||||
|
||||
for module in self.module_to_install:
|
||||
if find_spec(module) is None:
|
||||
do_install = True
|
||||
@@ -70,3 +95,10 @@ class Install:
|
||||
print(f"====> Module {module} installé")
|
||||
else:
|
||||
print(f"==> {module} already installed")
|
||||
|
||||
print(f"#"*12)
|
||||
print("Installation complete ...")
|
||||
print("You must change environment using the command below")
|
||||
print(f"source {self.venv_folder_name}{os.sep}bin{os.sep}activate")
|
||||
print(f"#"*12)
|
||||
exit(1)
|
||||
118
core/irc.py
118
core/irc.py
@@ -28,9 +28,9 @@ class Irc:
|
||||
|
||||
# Liste des commandes internes du bot
|
||||
self.commands_level = {
|
||||
0: ['help', 'auth', 'copyright'],
|
||||
1: ['load','reload','unload', 'deauth', 'uptime', 'checkversion'],
|
||||
2: ['show_modules', 'show_timers', 'show_threads', 'show_channels'],
|
||||
0: ['help', 'auth', 'copyright', 'uptime'],
|
||||
1: ['load','reload','unload', 'deauth', 'checkversion'],
|
||||
2: ['show_modules', 'show_timers', 'show_threads', 'show_channels', 'show_users', 'show_admins'],
|
||||
3: ['quit', 'restart','addaccess','editaccess', 'delaccess']
|
||||
}
|
||||
|
||||
@@ -418,6 +418,7 @@ class Irc:
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :[ {self.Config.CONFIG_COLOR['rouge']}MODULE_NOT_FOUND{self.Config.CONFIG_COLOR['noire']} ]: {moduleNotFound}")
|
||||
except Exception as e:
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to load : {e}")
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :[ {self.Config.CONFIG_COLOR['rouge']}ERROR{self.Config.CONFIG_COLOR['noire']} ]: {e}")
|
||||
|
||||
def insert_db_admin(self, uid:str, level:int) -> None:
|
||||
|
||||
@@ -619,8 +620,18 @@ class Irc:
|
||||
# if self.Config.ABUSEIPDB == 1:
|
||||
# self.Base.create_thread(self.abuseipdb_scan, (cmd[2], ))
|
||||
self.first_connexion_ip = cmd[2]
|
||||
self.first_score = int(cmd[3])
|
||||
pass
|
||||
|
||||
self.first_score = 0
|
||||
if str(cmd[3]).find('*') != -1:
|
||||
# If * available, it means that an ircop changed the repurtation score
|
||||
# means also that the user exist will try to update all users with same IP
|
||||
self.first_score = int(str(cmd[3]).replace('*',''))
|
||||
for user in self.User.UID_DB:
|
||||
if user.remote_ip == self.first_connexion_ip:
|
||||
user.score_connexion = self.first_score
|
||||
else:
|
||||
self.first_score = int(cmd[3])
|
||||
|
||||
# Possibilité de déclancher les bans a ce niveau.
|
||||
except IndexError as ie:
|
||||
self.Base.logs.error(f'{ie}')
|
||||
@@ -695,6 +706,7 @@ class Irc:
|
||||
cmd.pop(0)
|
||||
uid_who_quit = str(cmd[0]).replace(':', '')
|
||||
self.User.delete(uid_who_quit)
|
||||
self.Channel.delete_user_from_all_channel(uid_who_quit)
|
||||
|
||||
case 'PONG':
|
||||
# ['@msgid=aTNJhp17kcPboF5diQqkUL;time=2023-12-28T20:35:58.411Z', ':irc.deb.biz.st', 'PONG', 'irc.deb.biz.st', ':Dev-PyDefender']
|
||||
@@ -713,41 +725,43 @@ class Irc:
|
||||
case 'MODE':
|
||||
#['@msgid=d0ySx56Yd0nc35oHts2SkC-/J9mVUA1hfM6+Z4494xWUg;time=2024-08-09T12:45:36.651Z',
|
||||
# ':001', 'MODE', '#a', '+nt', '1723207536']
|
||||
cmd.pop(0)
|
||||
if '#' in cmd[2]:
|
||||
channel = cmd[2]
|
||||
mode = cmd[3]
|
||||
self.Channel.update(channel, mode)
|
||||
pass
|
||||
|
||||
case 'SJOIN':
|
||||
# ['@msgid=5sTwGdj349D82L96p749SY;time=2024-08-15T09:50:23.528Z', ':001', 'SJOIN', '1721564574', '#welcome', ':001JD94QH']
|
||||
# ['@msgid=bvceb6HthbLJapgGLXn1b0;time=2024-08-15T09:50:11.464Z', ':001', 'SJOIN', '1721564574', '#welcome', '+lnrt', '13', ':001CIVLQF', '+11ZAAAAAB', '001QGR10C', '*@0014UE10B', '001NL1O07', '001SWZR05', '001HB8G04', '@00BAAAAAJ', '0019M7101']
|
||||
# ['@msgid=SKUeuVzOrTShRDduq8VerX;time=2024-08-23T19:37:04.266Z', ':001', 'SJOIN', '1723993047', '#welcome', '+lnrt', '13',
|
||||
# ':001T6VU3F', '001JGWB2K', '@11ZAAAAAB',
|
||||
# '001F16WGR', '001X9YMGQ', '*+001DYPFGP', '@00BAAAAAJ', '001AAGOG9', '001FMFVG8', '001DAEEG7',
|
||||
# '&~G:unknown-users', '"~G:websocket-users', '"~G:known-users', '"~G:webirc-users']
|
||||
cmd.pop(0)
|
||||
channel = str(cmd[3]).lower()
|
||||
mode = cmd[4]
|
||||
len_cmd = len(cmd)
|
||||
list_users:list = []
|
||||
|
||||
occurence = 0
|
||||
start_boucle = 0
|
||||
|
||||
|
||||
# Trouver le premier user
|
||||
for i in range(len_cmd):
|
||||
s: list = re.findall(fr':', cmd[i])
|
||||
if s:
|
||||
start_boucle = i
|
||||
occurence += 1
|
||||
if occurence == 2:
|
||||
start_boucle = i
|
||||
|
||||
# Boucle qui va ajouter l'ensemble des users (UID)
|
||||
for i in range(start_boucle, len(cmd)):
|
||||
parsed_UID = str(cmd[i])
|
||||
pattern = fr'[:|@|%|\+|~|\*]*'
|
||||
# pattern = fr'[:|@|%|\+|~|\*]*'
|
||||
pattern = fr':'
|
||||
parsed_UID = re.sub(pattern, '', parsed_UID)
|
||||
list_users.append(parsed_UID)
|
||||
clean_uid = self.Base.clean_uid(parsed_UID)
|
||||
if len(clean_uid) == 9:
|
||||
list_users.append(parsed_UID)
|
||||
|
||||
self.Channel.insert(
|
||||
self.Channel.ChannelModel(
|
||||
name=channel,
|
||||
mode=mode,
|
||||
uids=list_users
|
||||
)
|
||||
)
|
||||
@@ -756,7 +770,7 @@ class Irc:
|
||||
# ['@unrealircd.org/geoip=FR;unrealircd.org/userhost=50d6492c@80.214.73.44;unrealircd.org/userip=50d6492c@80.214.73.44;msgid=YSIPB9q4PcRu0EVfC9ci7y-/mZT0+Gj5FLiDSZshH5NCw;time=2024-08-15T15:35:53.772Z',
|
||||
# ':001EPFBRD', 'PART', '#welcome', ':WEB', 'IRC', 'Paris']
|
||||
uid = str(cmd[1]).replace(':','')
|
||||
channel = str(cmd[3])
|
||||
channel = str(cmd[3]).lower()
|
||||
self.Channel.delete_user_from_channel(channel, uid)
|
||||
|
||||
pass
|
||||
@@ -808,10 +822,10 @@ class Irc:
|
||||
|
||||
get_uid_or_nickname = str(cmd[0].replace(':',''))
|
||||
if len(cmd) == 6:
|
||||
if cmd[1] == 'PRIVMSG' and cmd[3] == ':auth':
|
||||
if cmd[1] == 'PRIVMSG' and str(cmd[3]).replace('.','') == ':auth':
|
||||
cmd_copy = cmd.copy()
|
||||
cmd_copy[5] = '**********'
|
||||
self.Base.logs.debug(cmd_copy)
|
||||
self.Base.logs.info(cmd_copy)
|
||||
else:
|
||||
self.Base.logs.info(cmd)
|
||||
else:
|
||||
@@ -892,8 +906,8 @@ class Irc:
|
||||
|
||||
def _hcmds(self, user: str, cmd:list, fullcmd: list = []) -> None:
|
||||
|
||||
fromuser = self.User.get_nickname(user) # Nickname qui a lancé la commande
|
||||
uid = self.User.get_uid(fromuser) # Récuperer le uid de l'utilisateur
|
||||
fromuser = self.User.get_nickname(user) # Nickname qui a lancé la commande
|
||||
uid = self.User.get_uid(fromuser) # Récuperer le uid de l'utilisateur
|
||||
|
||||
# Defender information
|
||||
dnickname = self.Config.SERVICE_NICKNAME # Defender nickname
|
||||
@@ -936,6 +950,11 @@ class Irc:
|
||||
user_to_log = self.User.get_nickname(cmd[1])
|
||||
password = cmd[2]
|
||||
|
||||
if fromuser != user_to_log:
|
||||
# If the current nickname is different from the nickname you want to log in with
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} NOTICE {fromuser} :Your current nickname is different from the nickname you want to log in with")
|
||||
return False
|
||||
|
||||
if not user_to_log is None:
|
||||
mes_donnees = {'user': user_to_log, 'password': self.Base.crypt_password(password)}
|
||||
query = f"SELECT id, level FROM {self.Config.table_admin} WHERE user = :user AND password = :password"
|
||||
@@ -1139,11 +1158,12 @@ class Irc:
|
||||
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
|
||||
@@ -1163,8 +1183,23 @@ class Irc:
|
||||
return False
|
||||
else:
|
||||
self.send2socket(f":{self.Config.SERVICE_NICKNAME} PRIVMSG {self.Config.SERVICE_CHANLOG} :Module {module_name} n'est pas chargé !")
|
||||
except:
|
||||
self.Base.logs.error(f"Something went wrong with a module you want to reload")
|
||||
|
||||
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)
|
||||
|
||||
case 'quit':
|
||||
try:
|
||||
@@ -1213,16 +1248,31 @@ class Irc:
|
||||
case 'show_modules':
|
||||
|
||||
self.Base.logs.debug(self.loaded_classes)
|
||||
all_modules = self.Base.get_all_modules()
|
||||
|
||||
results = self.Base.db_execute_query(f'SELECT module FROM {self.Config.table_module}')
|
||||
results = results.fetchall()
|
||||
|
||||
if len(results) == 0:
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :Aucun module chargé")
|
||||
return False
|
||||
# if len(results) == 0:
|
||||
# self.send2socket(f":{dnickname} NOTICE {fromuser} :There is no module loaded")
|
||||
# return False
|
||||
|
||||
for r in results:
|
||||
self.send2socket(f":{dnickname} PRIVMSG {dchanlog} :Le module {r[0]} chargé")
|
||||
found = False
|
||||
|
||||
for module in all_modules:
|
||||
for loaded_mod in results:
|
||||
if module == loaded_mod[0]:
|
||||
found = True
|
||||
|
||||
if found:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :{module} - {self.Config.CONFIG_COLOR['verte']}Loaded{self.Config.CONFIG_COLOR['nogc']}")
|
||||
else:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :{module} - {self.Config.CONFIG_COLOR['rouge']}Not Loaded{self.Config.CONFIG_COLOR['nogc']}")
|
||||
|
||||
found = False
|
||||
|
||||
# for r in results:
|
||||
# self.send2socket(f":{dnickname} NOTICE {fromuser} :{r[0]} - {self.Config.CONFIG_COLOR['verte']}Loaded{self.Config.CONFIG_COLOR['nogc']}")
|
||||
|
||||
case 'show_timers':
|
||||
|
||||
@@ -1250,6 +1300,14 @@ class Irc:
|
||||
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} : Channel: {chan.name} - Users: {list_nicknames}")
|
||||
|
||||
case 'show_users':
|
||||
for db_user in self.User.UID_DB:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :UID : {db_user.uid} - isWebirc: {db_user.isWebirc} - Nickname: {db_user.nickname} - Connection: {db_user.connexion_datetime}")
|
||||
|
||||
case 'show_admins':
|
||||
for db_admin in self.Admin.UID_ADMIN_DB:
|
||||
self.send2socket(f":{dnickname} NOTICE {fromuser} :UID : {db_admin.uid} - Nickname: {db_admin.nickname} - Level: {db_admin.level} - Connection: {db_admin.connexion_datetime}")
|
||||
|
||||
case 'uptime':
|
||||
uptime = self.get_defender_uptime()
|
||||
self.send2socket(f':{dnickname} NOTICE {fromuser} : {uptime}')
|
||||
|
||||
275
install.py
Normal file
275
install.py
Normal file
@@ -0,0 +1,275 @@
|
||||
from subprocess import check_call, run, CalledProcessError, PIPE
|
||||
from platform import python_version, python_version_tuple, system
|
||||
from sys import exit
|
||||
import os, logging, shutil
|
||||
|
||||
try:
|
||||
import pwd
|
||||
except ModuleNotFoundError as err:
|
||||
print(err)
|
||||
|
||||
class Install:
|
||||
|
||||
def __init__(self) -> None:
|
||||
|
||||
# Python required version
|
||||
self.python_min_version = '3.10'
|
||||
self.log_file = 'install.log'
|
||||
self.ServiceName = 'Defender'
|
||||
self.venv_name = '.pyenv'
|
||||
self.venv_dependencies: list[str] = ['sqlalchemy','psutil','requests']
|
||||
self.install_folder = os.getcwd()
|
||||
self.osname = os.name
|
||||
self.system_name = system()
|
||||
self.cmd_linux_requirements: list[str] = ['apt', 'install', '-y', 'python3', 'python3-pip', 'python3-venv']
|
||||
self.venv_pip_full_path = os.path.join(self.venv_name, f'bin{os.sep}pip')
|
||||
self.venv_python_full_path = os.path.join(self.venv_name, f'bin{os.sep}python')
|
||||
self.systemd_folder = '/etc/systemd/system/'
|
||||
|
||||
# Init log system
|
||||
self.init_log_system()
|
||||
|
||||
# Exclude Windows OS
|
||||
if self.osname == 'nt':
|
||||
print('/!\\ Windows OS is not supported by this automatic installation /!\\')
|
||||
self.Logs.critical('/!\\ Windows OS is not supported by this automatic install /!\\')
|
||||
print(self.system_name)
|
||||
exit(5)
|
||||
|
||||
if not self.is_root():
|
||||
exit(5)
|
||||
|
||||
# Get the current user
|
||||
self.system_username: str = input(f'What is the user ro run defender with ? [{os.getlogin()}] : ')
|
||||
if str(self.system_username).strip() == '':
|
||||
self.system_username = os.getlogin()
|
||||
|
||||
self.get_user_information(self.system_username)
|
||||
|
||||
self.Logs.debug(f'The user selected is: {self.system_username}')
|
||||
self.Logs.debug(f'Operating system: {self.osname}')
|
||||
|
||||
# Install linux dependencies
|
||||
self.install_linux_dependencies()
|
||||
|
||||
# Check python version
|
||||
self.check_python_version()
|
||||
|
||||
# Create systemd service file
|
||||
self.create_service_file()
|
||||
|
||||
# Check if Env Exist | install environment | Install python dependencies
|
||||
self.check_venv()
|
||||
|
||||
# Create and start service
|
||||
if self.osname != 'nt':
|
||||
self.run_subprocess(['systemctl','daemon-reload'])
|
||||
self.run_subprocess(['systemctl','start', self.ServiceName])
|
||||
self.run_subprocess(['systemctl','status', self.ServiceName])
|
||||
|
||||
# Clean the Installation
|
||||
self.clean_installation()
|
||||
|
||||
return None
|
||||
|
||||
def is_installed(self) -> bool:
|
||||
|
||||
is_installed = False
|
||||
|
||||
# Check logs folder
|
||||
if os.path.exists('logs'):
|
||||
is_installed = True
|
||||
|
||||
# Check db folder
|
||||
if os.path.exists('db'):
|
||||
is_installed = True
|
||||
|
||||
return is_installed
|
||||
|
||||
def is_root(self) -> bool:
|
||||
|
||||
if os.geteuid() != 0:
|
||||
print('/!\\ user must run install.py as root /!\\')
|
||||
self.Logs.critical('/!\\ user must run install.py as root /!\\')
|
||||
return False
|
||||
elif os.geteuid() == 0:
|
||||
return True
|
||||
|
||||
def get_user_information(self, system_user: str) -> None:
|
||||
|
||||
try:
|
||||
username: tuple = pwd.getpwnam(system_user)
|
||||
self.system_uid = username.pw_uid
|
||||
self.system_gid = username.pw_gid
|
||||
return None
|
||||
|
||||
except KeyError as ke:
|
||||
self.Logs.critical(f"This user [{system_user}] doesn't exist: {ke}")
|
||||
print(f"This user [{system_user}] doesn't exist: {ke}")
|
||||
exit(5)
|
||||
|
||||
def init_log_system(self) -> None:
|
||||
|
||||
# Init logs object
|
||||
self.Logs = logging
|
||||
self.Logs.basicConfig(level=logging.DEBUG,
|
||||
filename=self.log_file,
|
||||
encoding='UTF-8',
|
||||
format='%(asctime)s - %(levelname)s - %(filename)s - %(lineno)d - %(funcName)s - %(message)s')
|
||||
|
||||
self.Logs.debug('#################### STARTING INSTALLATION ####################')
|
||||
|
||||
return None
|
||||
|
||||
def clean_installation(self) -> None:
|
||||
|
||||
# Chown the Python Env to non user privilege
|
||||
self.run_subprocess(['chown','-R', f'{self.system_username}:{self.system_username}',
|
||||
f'{os.path.join(self.install_folder, self.venv_name)}'
|
||||
]
|
||||
)
|
||||
|
||||
# Chown the installation log file
|
||||
self.run_subprocess(['chown','-R', f'{self.system_username}:{self.system_username}',
|
||||
f'{os.path.join(self.install_folder, self.log_file)}'
|
||||
]
|
||||
)
|
||||
return None
|
||||
|
||||
def run_subprocess(self, command:list) -> None:
|
||||
|
||||
try:
|
||||
run_command = check_call(command)
|
||||
self.Logs.debug(f'{command} - {run_command}')
|
||||
print(f'{command} - {run_command}')
|
||||
|
||||
except CalledProcessError as e:
|
||||
print(f"Command failed :{e.returncode}")
|
||||
self.Logs.critical(f"Command failed :{e.returncode}")
|
||||
exit(5)
|
||||
|
||||
def check_python_version(self) -> bool:
|
||||
"""Test si la version de python est autorisée ou non
|
||||
|
||||
Returns:
|
||||
bool: True si la version de python est autorisé sinon False
|
||||
"""
|
||||
|
||||
self.Logs.debug(f'The current python version is: {python_version()}')
|
||||
|
||||
# Current system version
|
||||
sys_major, sys_minor, sys_patch = python_version_tuple()
|
||||
|
||||
# min python version required
|
||||
python_required_version = self.PYTHON_MIN_VERSION.split('.')
|
||||
min_major, min_minor = tuple((python_required_version[0], python_required_version[1]))
|
||||
|
||||
if int(sys_major) < int(min_major):
|
||||
print(f"## Your python version must be greather than or equal to {self.PYTHON_MIN_VERSION} ##")
|
||||
self.Logs.critical(f'Your python version must be greather than or equal to {self.python_min_version}')
|
||||
return False
|
||||
|
||||
elif (int(sys_major) <= int(min_major)) and (int(sys_minor) < int(min_minor)):
|
||||
print(f"## Your python version must be greather than or equal to {self.PYTHON_MIN_VERSION} ##")
|
||||
self.Logs.critical(f'Your python version must be greather than or equal to {self.python_min_version}')
|
||||
return False
|
||||
|
||||
print(f"===> Version of python : {python_version()} ==> OK")
|
||||
self.Logs.debug(f'Version of python : {python_version()} ==> OK')
|
||||
|
||||
return True
|
||||
|
||||
def check_packages(self, package_name) -> bool:
|
||||
|
||||
try:
|
||||
# Run a command in the virtual environment's Python to check if the package is installed
|
||||
run([self.venv_python_full_path, '-c', f'import {package_name}'], check=True, stdout=PIPE, stderr=PIPE)
|
||||
return True
|
||||
except CalledProcessError:
|
||||
return False
|
||||
|
||||
def check_venv(self) -> bool:
|
||||
|
||||
if os.path.exists(self.venv_name):
|
||||
|
||||
# Installer les dependances
|
||||
self.install_dependencies()
|
||||
return True
|
||||
else:
|
||||
self.run_subprocess(['python3', '-m', 'venv', self.venv_name])
|
||||
self.Logs.debug(f'Python Virtual env installed {self.venv_name}')
|
||||
print(f'Python Virtual env installed {self.venv_name}')
|
||||
|
||||
self.install_dependencies()
|
||||
return False
|
||||
|
||||
def create_service_file(self) -> None:
|
||||
|
||||
if self.systemd_folder is None:
|
||||
# If Windows, do not install systemd
|
||||
return None
|
||||
|
||||
if os.path.exists(f'{self.systemd_folder}{os.sep}{self.ServiceName}.service'):
|
||||
print(f'/!\\ Service already created in the system /!\\')
|
||||
self.Logs.warning('/!\\ Service already created in the system /!\\')
|
||||
print(f'The service file will be regenerated')
|
||||
self.Logs.warning('The service file will be regenerated')
|
||||
|
||||
|
||||
contain = f'''[Unit]
|
||||
Description={self.ServiceName} IRC Service
|
||||
|
||||
[Service]
|
||||
User={self.system_username}
|
||||
ExecStart={os.path.join(self.install_folder, self.venv_python_full_path)} {os.path.join(self.install_folder, 'main.py')}
|
||||
WorkingDirectory={self.install_folder}
|
||||
SyslogIdentifier={self.ServiceName}
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
'''
|
||||
|
||||
with open(f'{self.ServiceName}.service.generated', 'w+') as servicefile:
|
||||
servicefile.write(contain)
|
||||
servicefile.close()
|
||||
print('Service file generated with current configuration')
|
||||
self.Logs.debug('Service file generated with current configuration')
|
||||
|
||||
source = f'{self.install_folder}{os.sep}{self.ServiceName}.service.generated'
|
||||
self.run_subprocess(['chown','-R', f'{self.system_username}:{self.system_username}', source])
|
||||
destination = f'{self.systemd_folder}'
|
||||
shutil.copy(source, destination)
|
||||
os.rename(f'{self.systemd_folder}{os.sep}{self.ServiceName}.service.generated', f'{self.systemd_folder}{os.sep}{self.ServiceName}.service')
|
||||
print(f'Service file moved to systemd folder {self.systemd_folder}')
|
||||
self.Logs.debug(f'Service file moved to systemd folder {self.systemd_folder}')
|
||||
|
||||
def install_linux_dependencies(self) -> None:
|
||||
|
||||
self.run_subprocess(self.cmd_linux_requirements)
|
||||
|
||||
return None
|
||||
|
||||
def install_dependencies(self) -> None:
|
||||
|
||||
try:
|
||||
self.run_subprocess([self.venv_pip_full_path, 'cache', 'purge'])
|
||||
self.run_subprocess([self.venv_python_full_path, '-m', 'pip', 'install', '--upgrade', 'pip'])
|
||||
|
||||
if self.check_packages('greenlet') is None:
|
||||
self.run_subprocess(
|
||||
[self.venv_pip_full_path, 'install', '--only-binary', ':all:', 'greenlet']
|
||||
)
|
||||
|
||||
for module in self.venv_dependencies:
|
||||
if not self.check_packages(module):
|
||||
### Trying to install missing python packages ###
|
||||
self.run_subprocess([self.venv_pip_full_path, 'install', module])
|
||||
else:
|
||||
self.Logs.debug(f'{module} already installed')
|
||||
print(f"==> {module} already installed")
|
||||
|
||||
except CalledProcessError as cpe:
|
||||
self.Logs.critical(f'{cpe}')
|
||||
|
||||
Install()
|
||||
@@ -23,7 +23,9 @@ class Defender():
|
||||
reputation: int
|
||||
reputation_timer: int
|
||||
reputation_seuil: int
|
||||
reputation_score_after_release: int
|
||||
reputation_ban_all_chan: int
|
||||
reputation_sg: int
|
||||
local_scan: int
|
||||
psutil_scan: int
|
||||
abuseipdb_scan: int
|
||||
@@ -80,8 +82,8 @@ class Defender():
|
||||
self.commands_level = {
|
||||
0: ['code'],
|
||||
1: ['join','part', 'info'],
|
||||
2: ['q', 'dq', 'o', 'do', 'h', 'dh', 'v', 'dv', 'b', 'ub','k', 'kb'],
|
||||
3: ['reputation','proxy_scan', 'flood', 'status', 'timer','show_reputation', 'show_users', 'sentinel']
|
||||
2: ['owner', 'deowner', 'op', 'deop', 'halfop', 'dehalfop', 'voice', 'devoice', 'ban', 'unban','kick', 'kickban'],
|
||||
3: ['reputation','proxy_scan', 'flood', 'status', 'timer','show_reputation', 'sentinel']
|
||||
}
|
||||
self.__set_commands(self.commands_level) # Enrigstrer les nouvelles commandes dans le code
|
||||
|
||||
@@ -173,12 +175,16 @@ class Defender():
|
||||
# Rejoindre les salons
|
||||
self.join_saved_channels()
|
||||
|
||||
# Variable qui va contenir les options de configuration du module Defender
|
||||
self.ModConfig = self.ModConfModel(
|
||||
reputation=0, reputation_timer=0, reputation_seuil=10, reputation_ban_all_chan=0,
|
||||
local_scan=0, psutil_scan=0, abuseipdb_scan=0, freeipapi_scan=0, cloudfilt_scan=0,
|
||||
flood=0, flood_message=5, flood_time=1, flood_timer=20
|
||||
)
|
||||
try:
|
||||
# Variable qui va contenir les options de configuration du module Defender
|
||||
self.ModConfig = self.ModConfModel(
|
||||
reputation=0, reputation_timer=0, reputation_seuil=26, reputation_score_after_release=27,
|
||||
reputation_ban_all_chan=0,reputation_sg=1,
|
||||
local_scan=0, psutil_scan=0, abuseipdb_scan=0, freeipapi_scan=0, cloudfilt_scan=0,
|
||||
flood=0, flood_message=5, flood_time=1, flood_timer=20
|
||||
)
|
||||
except TypeError as te:
|
||||
self.Logs.critical(te)
|
||||
|
||||
# Logger en debug la variable de configuration
|
||||
self.Logs.debug(self.ModConfig)
|
||||
@@ -470,7 +476,7 @@ class Defender():
|
||||
# - Defender devra libérer l'utilisateur et l'envoyer vers un salon défini dans la configuration {welcome_chan}
|
||||
# - Defender devra intégrer une liste d'IDs (pseudo/host) exemptés de 'Reputation security' malgré un score de rép. faible et un pseudo non enregistré.
|
||||
try:
|
||||
|
||||
|
||||
get_reputation = self.reputation_get_Reputation(uid)
|
||||
|
||||
if get_reputation is None:
|
||||
@@ -479,7 +485,7 @@ class Defender():
|
||||
|
||||
salon_logs = self.Config.SERVICE_CHANLOG
|
||||
salon_jail = self.Config.SALON_JAIL
|
||||
|
||||
|
||||
code = get_reputation.secret_code
|
||||
jailed_nickname = get_reputation.nickname
|
||||
jailed_score = get_reputation.score
|
||||
@@ -489,7 +495,7 @@ class Defender():
|
||||
color_bold = self.Config.CONFIG_COLOR['gras']
|
||||
service_id = self.Config.SERVICE_ID
|
||||
service_prefix = self.Config.SERVICE_PREFIX
|
||||
reputation_ban_all_chan = self.Base.int_if_possible(self.ModConfig.reputation_ban_all_chan)
|
||||
reputation_ban_all_chan = self.ModConfig.reputation_ban_all_chan
|
||||
|
||||
if not get_reputation.isWebirc:
|
||||
# Si le user ne vient pas de webIrc
|
||||
@@ -518,7 +524,7 @@ class Defender():
|
||||
reputation_flag = self.ModConfig.reputation
|
||||
reputation_timer = self.ModConfig.reputation_timer
|
||||
reputation_seuil = self.ModConfig.reputation_seuil
|
||||
ban_all_chan = self.Base.int_if_possible(self.ModConfig.reputation_ban_all_chan)
|
||||
ban_all_chan = self.ModConfig.reputation_ban_all_chan
|
||||
service_id = self.Config.SERVICE_ID
|
||||
dchanlog = self.Config.SERVICE_CHANLOG
|
||||
color_red = self.Config.CONFIG_COLOR['rouge']
|
||||
@@ -534,15 +540,11 @@ class Defender():
|
||||
|
||||
for user in self.UID_REPUTATION_DB:
|
||||
if not user.isWebirc: # Si il ne vient pas de WebIRC
|
||||
# self.Irc.debug(f"Nickname: {self.db_reputation[uid]['nickname']} | uptime: {self.get_user_uptime_in_minutes(uid)} | reputation time: {reputation_timer}")
|
||||
if self.get_user_uptime_in_minutes(user.uid) >= reputation_timer and int(user.score) <= int(reputation_seuil):
|
||||
self.Irc.send2socket(f":{service_id} PRIVMSG {dchanlog} :[{color_red} REPUTATION {color_black}] : Action sur {user.nickname} aprés {str(reputation_timer)} minutes d'inactivité")
|
||||
# if not system_reputation_timer_action(cglobal['reputation_timer_action'], uid, self.db_reputation[uid]['nickname']):
|
||||
# return False
|
||||
self.Irc.send2socket(f":{service_id} KILL {user.nickname} After {str(reputation_timer)} minutes of inactivity you should reconnect and type the password code ")
|
||||
|
||||
self.Logs.info(f"Nickname: {user.nickname} KILLED after {str(reputation_timer)} minutes of inactivity")
|
||||
|
||||
uid_to_clean.append(user.uid)
|
||||
|
||||
for uid in uid_to_clean:
|
||||
@@ -553,8 +555,9 @@ class Defender():
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -b {get_user_reputation.nickname}!*@*")
|
||||
|
||||
# Lorsqu'un utilisateur quitte, il doit être supprimé de {UID_DB}.
|
||||
self.User.delete(uid)
|
||||
self.Channel.delete_user_from_all_channel(uid)
|
||||
self.reputation_delete(uid)
|
||||
self.User.delete(uid)
|
||||
|
||||
except AssertionError as ae:
|
||||
self.Logs.error(f'Assertion Error -> {ae}')
|
||||
@@ -1004,6 +1007,9 @@ class Defender():
|
||||
try:
|
||||
self.reputation_first_connexion['ip'] = cmd[2]
|
||||
self.reputation_first_connexion['score'] = cmd[3]
|
||||
if str(cmd[3]).find('*') != -1:
|
||||
# If the reputation changed, we do not need to scan the IP
|
||||
return None
|
||||
|
||||
if not self.Base.is_valid_ip(cmd[2]):
|
||||
return None
|
||||
@@ -1038,71 +1044,39 @@ class Defender():
|
||||
self.flood(find_nickname, channel)
|
||||
|
||||
case 'UID':
|
||||
|
||||
# If Init then do nothing
|
||||
if self.Irc.INIT == 1:
|
||||
return None
|
||||
|
||||
if 'webirc' in cmd[0]:
|
||||
isWebirc = True
|
||||
else:
|
||||
isWebirc = False
|
||||
|
||||
# Supprimer la premiere valeur et finir le code normalement
|
||||
cmd.pop(0)
|
||||
|
||||
uid = str(cmd[7])
|
||||
nickname = str(cmd[2])
|
||||
username = str(cmd[5])
|
||||
hostname = str(cmd[6])
|
||||
umodes = str(cmd[9])
|
||||
vhost = str(cmd[10])
|
||||
# Get User information
|
||||
_User = self.User.get_User(str(cmd[7]))
|
||||
if _User is None:
|
||||
self.Logs.critical(f'This UID: [{cmd[7]}] is not available please check why')
|
||||
return None
|
||||
|
||||
reputation_flag = self.Base.int_if_possible(self.ModConfig.reputation)
|
||||
reputation_seuil = self.Base.int_if_possible(self.ModConfig.reputation_seuil)
|
||||
reputation_flag = self.ModConfig.reputation
|
||||
reputation_seuil = self.ModConfig.reputation_seuil
|
||||
|
||||
if self.Irc.INIT == 0:
|
||||
# A chaque nouvelle connexion chargé les données dans reputation
|
||||
client_ip = ''
|
||||
client_score = 0
|
||||
if 'ip' in self.reputation_first_connexion:
|
||||
client_ip = self.reputation_first_connexion['ip']
|
||||
if 'score' in self.reputation_first_connexion:
|
||||
client_score = self.reputation_first_connexion['score']
|
||||
|
||||
# Si réputation activé lancer un whois sur le nickname connecté
|
||||
# Si le user n'es pas un service ni un IrcOP alors whois
|
||||
if not re.match(fr'^.*[S|o?].*$', umodes):
|
||||
if reputation_flag == 1 and int(client_score) <= int(reputation_seuil):
|
||||
# if not db_isTrusted_user(user_id):
|
||||
|
||||
# get user information
|
||||
get_user = self.User.get_User(uid)
|
||||
if get_user is None:
|
||||
self.Logs.error(f'This UID {uid} does not exisit')
|
||||
|
||||
# self.insert_db_reputation(uid, client_ip, nickname, username, hostname, umodes, vhost, client_score, isWebirc)
|
||||
|
||||
# Si le user n'es pas un service ni un IrcOP
|
||||
if not re.match(fr'^.*[S|o?].*$', _User.umodes):
|
||||
if reputation_flag == 1 and _User.score_connexion <= reputation_seuil:
|
||||
currentDateTime = self.Base.get_datetime()
|
||||
self.reputation_insert(
|
||||
self.ReputationModel(
|
||||
uid=uid,
|
||||
nickname=nickname,
|
||||
username=username,
|
||||
hostname=hostname,
|
||||
umodes=umodes,
|
||||
vhost=vhost,
|
||||
ip=client_ip,
|
||||
score=client_score,
|
||||
secret_code=self.Base.get_random(8),
|
||||
isWebirc=isWebirc,
|
||||
connected_datetime=currentDateTime,
|
||||
uid=_User.uid, nickname=_User.nickname, username=_User.username, hostname=_User.hostname,
|
||||
umodes=_User.umodes, vhost=_User.vhost, ip=_User.remote_ip, score=_User.score_connexion,
|
||||
secret_code=self.Base.get_random(8), isWebirc=_User.isWebirc, connected_datetime=currentDateTime,
|
||||
updated_datetime=currentDateTime
|
||||
)
|
||||
)
|
||||
# self.Irc.send2socket(f":{service_id} WHOIS {nickname}")
|
||||
if self.reputation_check(uid):
|
||||
if reputation_flag == 1 and int(client_score) <= int(reputation_seuil):
|
||||
self.system_reputation(uid)
|
||||
if self.reputation_check(_User.uid):
|
||||
if reputation_flag == 1 and _User.score_connexion <= reputation_seuil:
|
||||
self.system_reputation(_User.uid)
|
||||
self.Logs.info('Démarrer le systeme de reputation')
|
||||
|
||||
case 'SJOIN':
|
||||
@@ -1110,19 +1084,6 @@ class Defender():
|
||||
try:
|
||||
cmd.pop(0)
|
||||
parsed_chan = cmd[3]
|
||||
|
||||
'''
|
||||
mode = ''
|
||||
if len(cmd) > 4:
|
||||
mode = cmd[4]
|
||||
|
||||
self.Channel.insert(
|
||||
self.Channel.ChannelModel(
|
||||
name=parsed_chan,
|
||||
mode=mode
|
||||
)
|
||||
)
|
||||
'''
|
||||
|
||||
if self.ModConfig.reputation == 1:
|
||||
parsed_UID = cmd[4]
|
||||
@@ -1134,6 +1095,10 @@ class Defender():
|
||||
if not get_reputation is None:
|
||||
isWebirc = get_reputation.isWebirc
|
||||
|
||||
if not isWebirc:
|
||||
if parsed_chan != self.Config.SALON_JAIL:
|
||||
self.Irc.send2socket(f":{service_id} SAPART {get_reputation.nickname} {parsed_chan}")
|
||||
|
||||
if self.ModConfig.reputation_ban_all_chan == 1 and not isWebirc:
|
||||
if parsed_chan != self.Config.SALON_JAIL:
|
||||
self.Irc.send2socket(f":{service_id} MODE {parsed_chan} +b {get_reputation.nickname}!*@*")
|
||||
@@ -1172,24 +1137,25 @@ class Defender():
|
||||
cmd.pop(0)
|
||||
uid = str(cmd[0]).replace(':','')
|
||||
get_Reputation = self.reputation_get_Reputation(uid)
|
||||
jail_salon = self.Config.SALON_JAIL
|
||||
service_id = self.Config.SERVICE_ID
|
||||
|
||||
if get_Reputation is None:
|
||||
self.Logs.debug(f'This UID: {uid} is not listed in the reputation dataclass')
|
||||
return None
|
||||
|
||||
# Update the new nickname
|
||||
oldnick = get_Reputation.nickname
|
||||
newnickname = cmd[2]
|
||||
|
||||
jail_salon = self.Config.SALON_JAIL
|
||||
service_id = self.Config.SERVICE_ID
|
||||
|
||||
# self.update_db_reputation(uid, newnickname)
|
||||
get_Reputation.nickname = newnickname
|
||||
|
||||
for chan in self.Channel.UID_CHANNEL_DB:
|
||||
if chan.name != jail_salon:
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -b {oldnick}!*@*")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} +b {newnickname}!*@*")
|
||||
# If ban in all channel is ON then unban old nickname an ban the new nickname
|
||||
if self.ModConfig.reputation_ban_all_chan == 1:
|
||||
for chan in self.Channel.UID_CHANNEL_DB:
|
||||
if chan.name != jail_salon:
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -b {oldnick}!*@*")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} +b {newnickname}!*@*")
|
||||
|
||||
except KeyError as ke:
|
||||
self.Logs.error(f'cmd - NICK - KeyError: {ke}')
|
||||
|
||||
@@ -1224,15 +1190,30 @@ class Defender():
|
||||
jail_chan = self.Config.SALON_JAIL # Salon pot de miel
|
||||
jail_chan_mode = self.Config.SALON_JAIL_MODES # Mode du salon "pot de miel"
|
||||
|
||||
if len(fullcmd) >= 3:
|
||||
fromchannel = str(fullcmd[2]).lower() if self.Base.Is_Channel(str(fullcmd[2]).lower()) else None
|
||||
else:
|
||||
fromchannel = None
|
||||
|
||||
if len(cmd) >= 2:
|
||||
sentchannel = str(cmd[1]).lower() if self.Base.Is_Channel(str(cmd[1]).lower()) else None
|
||||
else:
|
||||
sentchannel = None
|
||||
|
||||
if not fromchannel is None:
|
||||
channel = fromchannel
|
||||
elif not sentchannel is None:
|
||||
channel = sentchannel
|
||||
else:
|
||||
channel = None
|
||||
|
||||
match command:
|
||||
|
||||
case 'timer':
|
||||
try:
|
||||
timer_sent = self.Base.int_if_possible(cmd[1])
|
||||
timer_sent = int(timer_sent)
|
||||
# self.Irc.create_ping_timer(timer_sent, 'Defender', 'run_db_action_timer')
|
||||
self.Base.create_timer(timer_sent, self.run_db_action_timer)
|
||||
# self.Base.create_timer(timer_sent, self.Base.garbage_collector_sockets)
|
||||
|
||||
except TypeError as te:
|
||||
self.Logs.error(f"Type Error -> {te}")
|
||||
@@ -1245,7 +1226,7 @@ class Defender():
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} : No one is suspected')
|
||||
|
||||
for suspect in self.UID_REPUTATION_DB:
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} : Uid: {suspect.uid} | Nickname: {suspect.nickname} | Connected on: {suspect.connected_datetime} | Updated on: {suspect.updated_datetime}')
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} : Uid: {suspect.uid} | Nickname: {suspect.nickname} | Reputation: {suspect.score} | Secret code: {suspect.secret_code} | Connected on: {suspect.connected_datetime}')
|
||||
|
||||
case 'code':
|
||||
try:
|
||||
@@ -1280,21 +1261,20 @@ class Defender():
|
||||
self.Logs.debug(f'{jailed_UID} - {jailed_nickname} removed from REPUTATION_DB')
|
||||
self.Irc.send2socket(f":{service_id} SAPART {jailed_nickname} {jailed_salon}")
|
||||
self.Irc.send2socket(f":{service_id} SAJOIN {jailed_nickname} {welcome_salon}")
|
||||
self.Irc.send2socket(f":{link} REPUTATION {jailed_IP} {int(reputation_seuil) + 1}")
|
||||
self.Irc.send2socket(f":{link} REPUTATION {jailed_IP} {self.ModConfig.reputation_score_after_release}")
|
||||
self.User.get_User(jailed_UID).score_connexion = reputation_seuil + 1
|
||||
self.Irc.send2socket(f":{service_id} PRIVMSG {jailed_nickname} :[{color_green} MOT DE PASS CORRECT {color_black}] : You have now the right to enjoy the network !")
|
||||
|
||||
else:
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {jailed_salon} : Mauvais password')
|
||||
self.Irc.send2socket(f":{service_id} PRIVMSG {jailed_nickname} :[{color_green} MAUVAIS PASSWORD {color_black}]")
|
||||
|
||||
|
||||
except IndexError:
|
||||
self.Logs.error('_hcmd code: out of index')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} code [code]')
|
||||
except KeyError as ke:
|
||||
self.Logs.error(f'_hcmd code: KeyError {ke}')
|
||||
# self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} code [code]')
|
||||
pass
|
||||
|
||||
case 'reputation':
|
||||
# .reputation [on/off] --> activate or deactivate reputation system
|
||||
@@ -1319,6 +1299,15 @@ class Defender():
|
||||
self.Irc.send2socket(f":{service_id} JOIN {jail_chan}")
|
||||
self.Irc.send2socket(f":{service_id} SAMODE {jail_chan} +{dumodes} {dnickname}")
|
||||
self.Irc.send2socket(f":{service_id} MODE {jail_chan} +{jail_chan_mode}")
|
||||
|
||||
if self.ModConfig.reputation_sg == 1:
|
||||
for chan in self.Channel.UID_CHANNEL_DB:
|
||||
if chan.name != jail_chan:
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} +b ~security-group:unknown-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} +e ~security-group:webirc-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} +e ~security-group:known-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} +e ~security-group:websocket-users")
|
||||
|
||||
self.add_defender_channel(jail_chan)
|
||||
|
||||
if activation == 'off':
|
||||
@@ -1332,17 +1321,26 @@ class Defender():
|
||||
self.Irc.send2socket(f":{service_id} SAMODE {jail_chan} -{dumodes} {dnickname}")
|
||||
self.Irc.send2socket(f":{service_id} MODE {jail_chan} -sS")
|
||||
self.Irc.send2socket(f":{service_id} PART {jail_chan}")
|
||||
|
||||
for chan in self.Channel.UID_CHANNEL_DB:
|
||||
if chan.name != jail_chan:
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -b ~security-group:unknown-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -e ~security-group:webirc-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -e ~security-group:known-users")
|
||||
self.Irc.send2socket(f":{service_id} MODE {chan.name} -e ~security-group:websocket-users")
|
||||
|
||||
self.delete_defender_channel(jail_chan)
|
||||
|
||||
if len_cmd == 4:
|
||||
get_set = str(cmd[1]).lower()
|
||||
|
||||
|
||||
if get_set != 'set':
|
||||
return False
|
||||
raise IndexError('Showing help')
|
||||
|
||||
get_options = str(cmd[2]).lower()
|
||||
|
||||
match get_options:
|
||||
|
||||
case 'banallchan':
|
||||
key = 'reputation_ban_all_chan'
|
||||
get_value = str(cmd[3]).lower()
|
||||
@@ -1362,6 +1360,7 @@ class Defender():
|
||||
|
||||
self.update_db_configuration(key, 0)
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR["verte"]}BAN ON ALL CHANS{self.Config.CONFIG_COLOR["noire"]} ] : Deactivated by {fromuser}')
|
||||
|
||||
case 'limit':
|
||||
reputation_seuil = int(cmd[3])
|
||||
key = 'reputation_seuil'
|
||||
@@ -1377,14 +1376,34 @@ class Defender():
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR["verte"]}REPUTATION TIMER{self.Config.CONFIG_COLOR["noire"]} ] : Timer set to {str(reputation_timer)} minute(s) by {fromuser}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Reputation set to {reputation_timer}')
|
||||
|
||||
case 'score_after_release':
|
||||
reputation_score_after_release = int(cmd[3])
|
||||
key = 'reputation_score_after_release'
|
||||
self.update_db_configuration(key, reputation_score_after_release)
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR["verte"]}REPUTATION SCORE AFTER RELEASE{self.Config.CONFIG_COLOR["noire"]} ] : Reputation score after release set to {str(reputation_score_after_release)} by {fromuser}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Reputation score after release set to {reputation_score_after_release}')
|
||||
|
||||
case 'security_group':
|
||||
reputation_sg = int(cmd[3])
|
||||
key = 'reputation_sg'
|
||||
self.update_db_configuration(key, reputation_sg)
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {dchanlog} :[ {self.Config.CONFIG_COLOR["verte"]}REPUTATION SECURITY-GROUP{self.Config.CONFIG_COLOR["noire"]} ] : Reputation Security-group set to {str(reputation_sg)} by {fromuser}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Reputation score after release set to {reputation_sg}')
|
||||
|
||||
case _:
|
||||
pass
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :Right command : /msg {dnickname} reputation [ON/OFF]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :Right command : /msg {dnickname} reputation set banallchan [ON/OFF]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :Right command : /msg {dnickname} reputation set limit [1234]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :Right command : /msg {dnickname} reputation set score_after_release [1234]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :Right command : /msg {dnickname} reputation set timer [1234]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} :Right command : /msg {dnickname} reputation set action [kill|None]')
|
||||
|
||||
except IndexError as ie:
|
||||
self.Logs.warning(f'{ie}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} reputation [ON/OFF]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} reputation set banallchan [ON/OFF]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} reputation set limit [1234]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} reputation set score_after_release [1234]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} reputation set timer [1234]')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} reputation set action [kill|None]')
|
||||
|
||||
@@ -1566,6 +1585,7 @@ class Defender():
|
||||
try:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : [{color_green if self.ModConfig.reputation == 1 else color_red}Reputation{color_black}] ==> {self.ModConfig.reputation}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : reputation_seuil ==> {self.ModConfig.reputation_seuil}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : reputation_after_release ==> {self.ModConfig.reputation_score_after_release}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : reputation_ban_all_chan ==> {self.ModConfig.reputation_ban_all_chan}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : reputation_timer ==> {self.ModConfig.reputation_timer}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : [Proxy_scan]')
|
||||
@@ -1606,97 +1626,209 @@ class Defender():
|
||||
except IndexError as ie:
|
||||
self.Logs.error(f'{ie}')
|
||||
|
||||
case 'op' | 'o':
|
||||
case 'op':
|
||||
# /mode #channel +o user
|
||||
# .op #channel user
|
||||
# /msg dnickname op #channel user
|
||||
# [':adator', 'PRIVMSG', '#services', ':.o', '#services', 'dktmb']
|
||||
try:
|
||||
print(cmd)
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} op [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +o {fromuser}")
|
||||
return True
|
||||
|
||||
# deop nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +o {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +o {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd OP: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} op [#SALON] [NICKNAME]')
|
||||
|
||||
case 'deop' | 'do':
|
||||
case 'deop':
|
||||
# /mode #channel -o user
|
||||
# .deop #channel user
|
||||
try:
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} deop [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -o {fromuser}")
|
||||
return True
|
||||
|
||||
# deop nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -o {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -o {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd DEOP: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} deop [#SALON] [NICKNAME]')
|
||||
|
||||
case 'owner' | 'q':
|
||||
case 'owner':
|
||||
# /mode #channel +q user
|
||||
# .owner #channel user
|
||||
try:
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} owner [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +q {fromuser}")
|
||||
return True
|
||||
|
||||
# owner nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +q {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +q {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd OWNER: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} owner [#SALON] [NICKNAME]')
|
||||
|
||||
case 'deowner' | 'dq':
|
||||
case 'deowner':
|
||||
# /mode #channel -q user
|
||||
# .deowner #channel user
|
||||
try:
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} deowner [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -q {fromuser}")
|
||||
return True
|
||||
|
||||
# deowner nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -q {nickname}")
|
||||
return True
|
||||
channel = cmd[1]
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -q {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd DEOWNER: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} deowner [#SALON] [NICKNAME]')
|
||||
|
||||
case 'halfop' | 'h':
|
||||
case 'halfop':
|
||||
# /mode #channel +h user
|
||||
# .halfop #channel user
|
||||
try:
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} halfop [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +h {fromuser}")
|
||||
return True
|
||||
|
||||
# deop nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +h {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +h {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd halfop: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} halfop [#SALON] [NICKNAME]')
|
||||
|
||||
case 'dehalfop' | 'dh':
|
||||
case 'dehalfop':
|
||||
# /mode #channel -h user
|
||||
# .dehalfop #channel user
|
||||
try:
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} dehalfop [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -h {fromuser}")
|
||||
return True
|
||||
|
||||
# dehalfop nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -h {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -h {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd DEHALFOP: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} dehalfop [#SALON] [NICKNAME]')
|
||||
|
||||
case 'voice' | 'v':
|
||||
case 'voice':
|
||||
# /mode #channel +v user
|
||||
# .voice #channel user
|
||||
try:
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} voice [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +v {fromuser}")
|
||||
return True
|
||||
|
||||
# voice nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +v {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} +v {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd VOICE: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} voice [#SALON] [NICKNAME]')
|
||||
|
||||
case 'devoice' | 'dv':
|
||||
case 'devoice':
|
||||
# /mode #channel -v user
|
||||
# .devoice #channel user
|
||||
try:
|
||||
channel = cmd[1]
|
||||
if channel is None:
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} devoice [#SALON] [NICKNAME]')
|
||||
return False
|
||||
|
||||
if len(cmd) == 1:
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -v {fromuser}")
|
||||
return True
|
||||
|
||||
# dehalfop nickname
|
||||
if len(cmd) == 2:
|
||||
nickname = cmd[1]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -v {nickname}")
|
||||
return True
|
||||
|
||||
nickname = cmd[2]
|
||||
self.Irc.send2socket(f":{service_id} MODE {channel} -v {nickname}")
|
||||
|
||||
except IndexError as e:
|
||||
self.Logs.warning(f'_hcmd DEVOICE: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} devoice [#SALON] [NICKNAME]')
|
||||
|
||||
case 'ban' | 'b':
|
||||
case 'ban':
|
||||
# .ban #channel nickname
|
||||
try:
|
||||
channel = cmd[1]
|
||||
@@ -1708,7 +1840,7 @@ class Defender():
|
||||
self.Logs.warning(f'_hcmd BAN: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} ban [#SALON] [NICKNAME]')
|
||||
|
||||
case 'unban' | 'ub':
|
||||
case 'unban':
|
||||
# .unban #channel nickname
|
||||
try:
|
||||
channel = cmd[1]
|
||||
@@ -1720,7 +1852,7 @@ class Defender():
|
||||
self.Logs.warning(f'_hcmd UNBAN: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} unban [#SALON] [NICKNAME]')
|
||||
|
||||
case 'kick' | 'k':
|
||||
case 'kick':
|
||||
# .kick #channel nickname reason
|
||||
try:
|
||||
channel = cmd[1]
|
||||
@@ -1738,7 +1870,7 @@ class Defender():
|
||||
self.Logs.warning(f'_hcmd KICK: {str(e)}')
|
||||
self.Irc.send2socket(f':{dnickname} NOTICE {fromuser} : Right command : /msg {dnickname} kick [#SALON] [NICKNAME] [REASON]')
|
||||
|
||||
case 'kickban' | 'kb':
|
||||
case 'kickban':
|
||||
# .kickban #channel nickname reason
|
||||
try:
|
||||
channel = cmd[1]
|
||||
@@ -1794,8 +1926,3 @@ class Defender():
|
||||
if not chan.name in channel_to_dont_quit:
|
||||
self.Irc.send2socket(f":{service_id} PART {chan.name}")
|
||||
self.join_saved_channels()
|
||||
|
||||
case 'show_users':
|
||||
|
||||
for db_user in self.User.UID_DB:
|
||||
self.Irc.send2socket(f":{dnickname} NOTICE {fromuser} :UID : {db_user.uid} - isWebirc: {db_user.isWebirc} - Nickname: {db_user.nickname} - Connection: {db_user.connexion_datetime}")
|
||||
|
||||
@@ -157,7 +157,7 @@ class Votekick():
|
||||
mes_donnees = {'channel': channel}
|
||||
|
||||
response = self.Base.db_execute_query("SELECT id FROM votekick_channel WHERE channel = :channel", mes_donnees)
|
||||
|
||||
|
||||
isChannelExist = response.fetchone()
|
||||
|
||||
if isChannelExist is None:
|
||||
@@ -198,7 +198,7 @@ class Votekick():
|
||||
self.Irc.send2socket(f":{self.Config.SERVEUR_ID} SJOIN {unixtime} {chan} + :{self.Config.SERVICE_ID}")
|
||||
self.Irc.send2socket(f":{self.Config.SERVICE_NICKNAME} SAMODE {chan} +o {self.Config.SERVICE_NICKNAME}")
|
||||
|
||||
return None
|
||||
return None
|
||||
|
||||
def is_vote_ongoing(self, channel: str) -> bool:
|
||||
|
||||
@@ -207,7 +207,7 @@ class Votekick():
|
||||
if vote.channel_name == channel:
|
||||
if vote.target_user:
|
||||
response = True
|
||||
|
||||
|
||||
return response
|
||||
|
||||
def timer_vote_verdict(self, channel: str) -> None:
|
||||
@@ -220,6 +220,7 @@ class Votekick():
|
||||
if chan.vote_for > chan.vote_against:
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {channel} :The user {self.Config.CONFIG_COLOR["gras"]}{target_user}{self.Config.CONFIG_COLOR["nogc"]} will be kicked from this channel')
|
||||
self.Irc.send2socket(f":{dnickname} KICK {channel} {target_user} Following the vote, you are not welcome in {channel}")
|
||||
self.Channel.delete_user_from_channel(channel, self.User.get_uid(target_user))
|
||||
elif chan.vote_for <= chan.vote_against:
|
||||
self.Irc.send2socket(f':{dnickname} PRIVMSG {channel} :This user will stay on this channel')
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"version": "5.0.1"
|
||||
"version": "5.0.7"
|
||||
}
|
||||
Reference in New Issue
Block a user