1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
| unit Sentinel.Malware;
interface
uses
System.SysUtils, System.Classes, System.Types, System.IOUtils, System.Hash,
System.Net.HttpClient, System.Net.URLClient, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Forms,
Vcl.Dialogs, System.Threading, System.SyncObjs, System.Generics.Collections;
type
// Définition de la classe TSentinelMalware
TSentinelMalware = class
private
FSignatures: TDictionary<string, Boolean>; // Dictionnaire contenant les empreintes SHA‑256 des fichiers suspects
FStopScan: Boolean; // Indicateur permettant d'arrêter le scan à tout moment
public
constructor Create;
destructor Destroy; override;
/// Télécharge une liste de signatures SHA‑256 depuis une URL et les charge en mémoire.
/// Retourne True si le téléchargement a réussi, sinon False.
function DownloadAndLoadSignatures(const URL: string): Boolean;
/// Vérifie si le fichier donné correspond à une signature malware.
/// Calcule le SHA‑256 du fichier et le compare à la liste chargée.
function CheckFileAgainstSHA256Signatures(const FilePath: string): Boolean;
/// Compte le nombre total de fichiers présents dans un répertoire et ses sous-répertoires.
function CountFiles(const DirectoryPath: string): Integer;
/// Effectue un scan séquentiel des fichiers présents dans un répertoire.
/// Met à jour l'interface utilisateur avec les fichiers scannés et détecte les malwares.
procedure ScanDirectory(const DirectoryPath: string; DisplayLabel: TLabel; LogMemo: TMemo;
ProgressBar: TProgressBar; var ProgressCount: Integer);
/// Effectue un scan parallèle des fichiers pour accélérer l'analyse.
/// Met à jour l'interface utilisateur tout en vérifiant si le scan doit être arrêté.
procedure ScanDirectoryParallel(const DirectoryPath: string; DisplayLabel: TLabel; LogMemo: TMemo;
ProgressBar: TProgressBar);
/// Permet d'arrêter le scan en cours en modifiant l'indicateur FStopScan.
procedure StopScan;
end;
implementation
{ Création d'une instance de TSentinelMalware }
constructor TSentinelMalware.Create;
begin
inherited Create;
FSignatures := TDictionary<string, Boolean>.Create;
FStopScan := False; // Initialise l'indicateur d'arrêt du scan
end;
{ Destruction de l'instance et libération des ressources mémoire }
destructor TSentinelMalware.Destroy;
begin
FSignatures.Free;
inherited;
end;
{ Télécharge une liste de signatures SHA‑256 depuis une URL et charge en mémoire }
function TSentinelMalware.DownloadAndLoadSignatures(const URL: string): Boolean;
var
HttpClient: THTTPClient;
Response: IHTTPResponse;
RawText: string;
TempList: TStringList;
I: Integer;
signature: string;
begin
Result := False;
HttpClient := THTTPClient.Create;
TempList := TStringList.Create;
try
try
Response := HttpClient.Get(URL);
if Response.StatusCode = 200 then
begin
RawText := Response.ContentAsString;
if RawText <> '' then
begin
TempList.Text := RawText;
FSignatures.Clear;
for I := 0 to TempList.Count - 1 do
begin
// Ignore les lignes vides et les commentaires (lignes commençant par #)
if (TempList[I] <> '') and (TempList[I][1] <> '#') then
begin
signature := LowerCase(Trim(TempList[I]));
// Vérifie l'existence avant d'ajouter afin d'éviter les doublons
if not FSignatures.ContainsKey(signature) then
FSignatures.Add(signature, True);
end;
end;
Result := True;
end;
end
else
ShowMessage('Erreur HTTP - Code: ' + IntToStr(Response.StatusCode));
except
on E: Exception do
ShowMessage('Erreur lors du téléchargement des signatures : ' + E.Message);
end;
finally
TempList.Free;
HttpClient.Free;
end;
end;
{ Vérifie si le fichier est répertorié comme malware en comparant son hash SHA‑256 }
function TSentinelMalware.CheckFileAgainstSHA256Signatures(const FilePath: string): Boolean;
var
LStream: TFileStream;
FileHash: string;
begin
Result := False;
if not TFile.Exists(FilePath) then
Exit;
LStream := TFileStream.Create(FilePath, fmOpenRead or fmShareDenyWrite);
try
// Calcule le hash SHA‑256 du fichier pour vérification
FileHash := LowerCase(THashSHA2.GetHashString(LStream));
finally
LStream.Free;
end;
// Vérifie si le hash du fichier est présent dans le dictionnaire des signatures
Result := FSignatures.ContainsKey(FileHash);
end;
{ Compte tous les fichiers présents dans un répertoire, en incluant les sous-dossiers }
function TSentinelMalware.CountFiles(const DirectoryPath: string): Integer;
var
Files: TStringDynArray;
begin
if not TDirectory.Exists(DirectoryPath) then
Exit(0);
Files := TDirectory.GetFiles(DirectoryPath, '*.*', TSearchOption.soAllDirectories);
Result := Length(Files);
end;
{ Scan séquentiel des fichiers avec mise à jour de l'interface utilisateur }
procedure TSentinelMalware.ScanDirectory(const DirectoryPath: string; DisplayLabel: TLabel;
LogMemo: TMemo; ProgressBar: TProgressBar; var ProgressCount: Integer);
var
Files: TStringDynArray;
SubDirs: TStringDynArray;
FileName, Dir: string;
begin
if not TDirectory.Exists(DirectoryPath) or FStopScan then
Exit;
Files := TDirectory.GetFiles(DirectoryPath, '*.*', TSearchOption.soTopDirectoryOnly);
for FileName in Files do
begin
if FStopScan then
Exit;
DisplayLabel.Caption := 'Fichier scanné : ' + FileName;
Application.ProcessMessages;
Inc(ProgressCount);
ProgressBar.Position := ProgressCount;
if CheckFileAgainstSHA256Signatures(FileName) then
LogMemo.Lines.Add('Malware détecté : ' + FileName);
end;
SubDirs := TDirectory.GetDirectories(DirectoryPath, '*', TSearchOption.soTopDirectoryOnly);
for Dir in SubDirs do
ScanDirectory(Dir, DisplayLabel, LogMemo, ProgressBar, ProgressCount);
end;
{ Scan parallèle des fichiers pour une analyse plus rapide }
procedure TSentinelMalware.ScanDirectoryParallel(const DirectoryPath: string; DisplayLabel: TLabel;
LogMemo: TMemo; ProgressBar: TProgressBar);
var
Files: TArray<string>;
TotalFiles, LocalProgress: Integer;
begin
if not TDirectory.Exists(DirectoryPath) then
Exit;
FStopScan := False; // Réinitialise l'indicateur d'arrêt
Files := TDirectory.GetFiles(DirectoryPath, '*.*', TSearchOption.soAllDirectories);
TotalFiles := Length(Files);
ProgressBar.Min := 0;
ProgressBar.Max := TotalFiles;
ProgressBar.Position := 0;
LocalProgress := 0;
TParallel.For(0, TotalFiles - 1,
procedure(Index: Integer; LoopState: TParallel.TLoopState)
var
FileName: string;
IsMalware: Boolean;
CurrentProgress: Integer;
begin
if FStopScan then
begin
LoopState.Stop;
Exit;
end;
FileName := Files[Index];
IsMalware := CheckFileAgainstSHA256Signatures(FileName);
// Sécurise l'incrémentation de la progression
CurrentProgress := TInterlocked.Increment(LocalProgress);
TThread.Queue(nil,
procedure
begin
DisplayLabel.Caption := 'Fichier scanné : ' + FileName;
ProgressBar.Position := CurrentProgress;
if IsMalware then
LogMemo.Lines.Add('Malware détecté : ' + FileName);
end);
end);
end;
{ Permet d'arrêter le scan en cours }
procedure TSentinelMalware.StopScan;
begin
FStopScan := True;
end;
end. |
Partager