diff options
Diffstat (limited to 'src/analysis')
266 files changed, 50252 insertions, 1042 deletions
diff --git a/src/analysis/Makefile.am b/src/analysis/Makefile.am index 1dd83cb..909ced9 100644 --- a/src/analysis/Makefile.am +++ b/src/analysis/Makefile.am @@ -18,24 +18,21 @@ libanalysis_la_SOURCES = \ type.h type.c \ variable.h variable.c +libanalysis_la_CFLAGS = $(TOOLKIT_CFLAGS) $(LIBXML_CFLAGS) + libanalysis_la_LIBADD = \ contents/libanalysiscontents.la \ db/libanalysisdb.la \ disass/libanalysisdisass.la \ human/libanalysishuman.la \ + scan/libanalysisscan.la \ storage/libanalysisstorage.la \ types/libanalysistypes.la -libanalysis_la_LDFLAGS = - devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysis_la_SOURCES:%c=) -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = contents db disass human storage types +SUBDIRS = contents db disass human scan storage types diff --git a/src/analysis/binary.c b/src/analysis/binary.c index ddd2e30..f8b17d2 100644 --- a/src/analysis/binary.c +++ b/src/analysis/binary.c @@ -43,17 +43,21 @@ #include "../common/cpp.h" #include "../common/xdg.h" #include "../core/collections.h" +#include "../core/columns.h" #include "../core/logs.h" #include "../core/params.h" #include "../core/processors.h" #include "../format/known.h" #include "../glibext/gbinarycursor.h" -#include "../glibext/gloadedpanel.h" -#include "../gtkext/easygtk.h" -#include "../gtkext/gtkblockdisplay.h" -#include "../gtkext/gtkdisplaypanel.h" -#include "../gtkext/gtkgraphdisplay.h" -#include "../gtkext/hexdisplay.h" +#ifdef INCLUDE_GTK_SUPPORT +# include "../glibext/gloadedpanel.h" +# include "../gtkext/easygtk.h" +# include "../gtkext/gtkblockdisplay.h" +# include "../gtkext/gtkdisplaypanel.h" +# include "../gtkext/gtkgraphdisplay.h" +# include "../gtkext/gtkstatusstack.h" +# include "../gtkext/hexdisplay.h" +#endif @@ -156,8 +160,8 @@ static bool g_loaded_binary_save(GLoadedBinary *, xmlDoc *, xmlXPathContext *, c /* Fournit le contenu représenté de l'élément chargé. */ static GBinContent *g_loaded_binary_get_content(const GLoadedBinary *); -/* Fournit le contenu représenté de l'élément chargé. */ -static char *g_loaded_binary_get_format_name(const GLoadedBinary *); +/* Décrit la nature du contenu reconnu pour l'élément chargé. */ +static char *g_loaded_binary_get_content_class(const GLoadedBinary *, bool); /* Assure le désassemblage en différé. */ static bool g_loaded_binary_analyze(GLoadedBinary *, bool, bool, wgroup_id_t, GtkStatusStack *); @@ -168,6 +172,8 @@ static void on_binary_processor_changed(GArchProcessor *, GArchInstruction *, gb /* Fournit le désignation associée à l'élément chargé. */ static char *g_loaded_binary_describe(const GLoadedBinary *, bool); +#ifdef INCLUDE_GTK_SUPPORT + /* Détermine le nombre de vues disponibles pour un contenu. */ static unsigned int g_loaded_binary_count_views(const GLoadedBinary *); @@ -186,6 +192,8 @@ static unsigned int g_loaded_binary_get_view_index(GLoadedBinary *, GtkWidget *) /* Fournit toutes les options d'affichage pour un contenu. */ static GDisplayOptions *g_loaded_binary_get_display_options(const GLoadedBinary *, unsigned int); +#endif + /* ---------------------------------------------------------------------------------- */ @@ -225,12 +233,14 @@ static void g_loaded_binary_class_init(GLoadedBinaryClass *klass) loaded->save = (save_content_fc)g_loaded_binary_save; loaded->get_content = (get_content_fc)g_loaded_binary_get_content; - loaded->get_format_name = (get_format_name_fc)g_loaded_binary_get_format_name; + loaded->get_content_class = (get_content_class_fc)g_loaded_binary_get_content_class; loaded->analyze = (analyze_loaded_fc)g_loaded_binary_analyze; loaded->describe = (describe_loaded_fc)g_loaded_binary_describe; +#ifdef INCLUDE_GTK_SUPPORT + loaded->count_views = (count_loaded_views_fc)g_loaded_binary_count_views; loaded->get_view_name = (get_loaded_view_name_fc)g_loaded_binary_get_view_name; loaded->build_def_view = (build_loaded_def_view_fc)g_loaded_binary_build_default_view; @@ -239,6 +249,8 @@ static void g_loaded_binary_class_init(GLoadedBinaryClass *klass) loaded->get_options = (get_loaded_options_fc)g_loaded_binary_get_display_options; +#endif + } @@ -356,11 +368,39 @@ static void g_loaded_binary_finalize(GLoadedBinary *binary) GLoadedContent *g_loaded_binary_new(GExeFormat *format) { GLoadedBinary *result; /* Adresse à retourner */ + const char *arch; /* Architecture d'exécution */ + GArchProcessor *proc; /* Architecture du binaire */ + + result = NULL; + + /* Architecture visée */ + + arch = g_exe_format_get_target_machine(format); + + if (arch == NULL) + { + log_simple_message(LMT_INFO, _("Unknown architecture")); + goto exit; + } + + proc = get_arch_processor_for_key(arch); + + if (proc == NULL) + { + log_variadic_message(LMT_ERROR, _("Unable to load the required processor (%s)"), arch); + goto exit; + } + + /* Mise en place complète */ result = g_object_new(G_TYPE_LOADED_BINARY, NULL); result->format = format; + result->proc = proc; + + exit: + return G_LOADED_CONTENT(result); } @@ -609,7 +649,7 @@ static bool g_loaded_binary_connect_internal(GLoadedBinary *binary) /* Tentative de connexion */ - binary->client = g_analyst_client_new(checksum, binary->collections); + binary->client = g_analyst_client_new(checksum, "NULL", binary->collections, NULL); result = g_hub_client_start_internal(G_HUB_CLIENT(binary->client)); @@ -646,7 +686,7 @@ static bool g_loaded_binary_connect_remote(GLoadedBinary *binary) /* Tentative de connexion */ - binary->client = g_analyst_client_new(checksum, binary->collections); + binary->client = g_analyst_client_new(checksum, "NULL", binary->collections, NULL); result = g_hub_client_start_remote(G_HUB_CLIENT(binary->client), binary->remote_host, binary->remote_port, true); @@ -1310,9 +1350,10 @@ static bool g_loaded_binary_save(GLoadedBinary *binary, xmlDoc *xdoc, xmlXPathCo } + /* if (result) { - key = g_loaded_content_get_format_name(G_LOADED_CONTENT(binary)); + key = g_loaded_content_get_content_class(G_LOADED_CONTENT(binary)); result = add_string_attribute_to_node(xdoc, context, path, "format", key); free(key); } @@ -1323,6 +1364,7 @@ static bool g_loaded_binary_save(GLoadedBinary *binary, xmlDoc *xdoc, xmlXPathCo result = add_string_attribute_to_node(xdoc, context, path, "arch", key); free(key); } + */ if (result) result = g_loaded_binary_save_storage(binary, xdoc, context, path); @@ -1366,20 +1408,47 @@ static GBinContent *g_loaded_binary_get_content(const GLoadedBinary *binary) /****************************************************************************** * * * Paramètres : binary = élément chargé à manipuler. * +* human = description humaine attendue ? * * * -* Description : Fournit le contenu représenté de l'élément chargé. * +* Description : Décrit la nature du contenu reconnu pour l'élément chargé. * * * -* Retour : Contenu représenté. * +* Retour : Classe de contenu associée à l'élément chargé. * * * * Remarques : - * * * ******************************************************************************/ -static char *g_loaded_binary_get_format_name(const GLoadedBinary *binary) +static char *g_loaded_binary_get_content_class(const GLoadedBinary *binary, bool human) { char *result; /* Désignation à retourner */ + char *part; /* Partie à intégrer */ + + if (human) + { + result = g_known_format_get_description(G_KNOWN_FORMAT(binary->format)); - result = g_known_format_get_key(G_KNOWN_FORMAT(binary->format)); + result = stradd(result, ", "); + + part = g_arch_processor_get_desc(binary->proc); + + result = stradd(result, part); + + free(part); + + } + else + { + result = g_known_format_get_key(G_KNOWN_FORMAT(binary->format)); + + result = stradd(result, "-"); + + part = g_arch_processor_get_key(binary->proc); + + result = stradd(result, part); + + free(part); + + } return result; @@ -1406,49 +1475,31 @@ static bool g_loaded_binary_analyze(GLoadedBinary *binary, bool connect, bool ca { bool result; /* Bilan à retourner */ GBinFormat *format; /* Format lié au binaire */ - const char *arch; /* Architecture d'exécution */ char *desc; /* Description humaine associée*/ bool has_virt; /* Présence de virtuel ? */ GProcContext *context; /* Contexte de suivi dédié */ +#ifdef INCLUDE_GTK_SUPPORT GWidthTracker *tracker; /* Gestionnaire de largeur */ +#endif /* Interprétation du format associé */ format = G_BIN_FORMAT(binary->format); desc = g_known_format_get_description(G_KNOWN_FORMAT(format)); + assert(desc != NULL); - if (desc == NULL) - log_simple_message(LMT_WARNING, _("Unnamed format")); - else - log_variadic_message(LMT_INFO, _("Selected format: %s"), desc); + log_variadic_message(LMT_INFO, _("Selected format: %s"), desc); free(desc); result = g_known_format_analyze(G_KNOWN_FORMAT(format), gid, status); if (!result) goto glba_exit; - /* Architecture visée */ - - arch = g_exe_format_get_target_machine(binary->format); - - if (arch == NULL) - { - log_simple_message(LMT_INFO, _("Unknown architecture")); - result = false; - goto glba_exit; - } - - binary->proc = get_arch_processor_for_key(arch); - - if (binary->proc == NULL) - { - log_variadic_message(LMT_ERROR, _("Unable to load the required processor (%s)"), arch); - result = false; - goto glba_exit; - } + /* Interprétation de l'architecture associée */ desc = g_arch_processor_get_desc(binary->proc); + assert(desc != NULL); log_variadic_message(LMT_INFO, _("Detected architecture: %s"), desc); @@ -1475,12 +1526,16 @@ static bool g_loaded_binary_analyze(GLoadedBinary *binary, bool connect, bool ca { output_disassembly(binary, context, status, &binary->disass_cache); +#ifdef INCLUDE_GTK_SUPPORT + tracker = g_buffer_cache_get_width_tracker(binary->disass_cache); g_width_tracker_build_initial_cache(tracker, gid, status); g_object_unref(G_OBJECT(tracker)); +#endif + } g_object_unref(G_OBJECT(context)); @@ -1624,6 +1679,9 @@ static char *g_loaded_binary_describe(const GLoadedBinary *binary, bool full) } +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : binary = contenu chargé à consulter. * @@ -1835,3 +1893,6 @@ static GDisplayOptions *g_loaded_binary_get_display_options(const GLoadedBinary return result; } + + +#endif diff --git a/src/analysis/block-int.h b/src/analysis/block-int.h index faa0e1f..80fa6ea 100644 --- a/src/analysis/block-int.h +++ b/src/analysis/block-int.h @@ -44,12 +44,16 @@ typedef int (* block_compare_links_fc) (const block_link_t *, const block_link_t /* Fournit les détails des origines d'un bloc de code donné. */ typedef block_link_t * (* block_get_links_fc) (const GCodeBlock *, const GBlockList *, size_t *); +#ifdef INCLUDE_GTK_SUPPORT + /* Fournit la représentation graphique d'un bloc de code. */ typedef GBufferView * (* block_build_view_fc) (const GCodeBlock *, segcnt_list *); /* Construit un ensemble d'indications pour bloc. */ typedef char *(* block_build_tooltip_fc) (const GCodeBlock *); +#endif + /* Description d'un bloc de code (instance) */ struct _GCodeBlock @@ -64,7 +68,9 @@ struct _GCodeBlock size_t index; /* Indice dans une liste */ size_t rank; /* Rang dans l'exécution */ +#ifdef INCLUDE_GTK_SUPPORT GBufferView *view; /* Représentation construite */ +#endif }; @@ -77,8 +83,10 @@ struct _GCodeBlockClass block_compare_links_fc cmp_links; /* Comparaison de liens */ block_get_links_fc get_src; /* Obtention des origines */ block_get_links_fc get_dest; /* Obtention des destinations */ +#ifdef INCLUDE_GTK_SUPPORT block_build_view_fc build; /* Construction d'une vue */ block_build_tooltip_fc build_tooltip; /* Construction d'une bulle */ +#endif }; diff --git a/src/analysis/block.c b/src/analysis/block.c index 119dc86..f93a772 100644 --- a/src/analysis/block.c +++ b/src/analysis/block.c @@ -139,7 +139,9 @@ static void g_code_block_init(GCodeBlock *block) block->index = (size_t)-1; block->rank = (size_t)-1; +#ifdef INCLUDE_GTK_SUPPORT block->view = NULL; +#endif } @@ -158,7 +160,9 @@ static void g_code_block_init(GCodeBlock *block) static void g_code_block_dispose(GCodeBlock *block) { +#ifdef INCLUDE_GTK_SUPPORT g_clear_object(&block->view); +#endif G_OBJECT_CLASS(g_code_block_parent_class)->dispose(G_OBJECT(block)); @@ -322,6 +326,9 @@ void g_code_block_set_rank(GCodeBlock *block, size_t rank) } +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : block = bloc de code à manipuler. * @@ -383,6 +390,9 @@ char *g_code_block_build_tooltip(const GCodeBlock *block) } +#endif + + /* ---------------------------------------------------------------------------------- */ /* DEFINITION DE LIAISONS ENTRE BLOCS DE CODE */ diff --git a/src/analysis/block.h b/src/analysis/block.h index 63f0be0..401b520 100644 --- a/src/analysis/block.h +++ b/src/analysis/block.h @@ -33,7 +33,9 @@ #include "../arch/instruction.h" #include "../arch/vmpa.h" #include "../common/bits.h" -#include "../glibext/bufferview.h" +#ifdef INCLUDE_GTK_SUPPORT +# include "../glibext/bufferview.h" +#endif #include "../glibext/linesegment.h" @@ -74,12 +76,16 @@ size_t g_code_block_get_rank(const GCodeBlock *); /* Définit le rang du bloc de code dans le flot d'exécution. */ void g_code_block_set_rank(GCodeBlock *, size_t); +#ifdef INCLUDE_GTK_SUPPORT + /* Fournit la représentation graphique d'un bloc de code. */ GBufferView *g_code_block_get_view(GCodeBlock *, segcnt_list *); /* Construit un ensemble d'indications pour bloc. */ char *g_code_block_build_tooltip(const GCodeBlock *); +#endif + /* ------------------- DEFINITION DE LIAISONS ENTRE BLOCS DE CODE ------------------- */ diff --git a/src/analysis/cattribs.c b/src/analysis/cattribs.c index 704e665..1299991 100644 --- a/src/analysis/cattribs.c +++ b/src/analysis/cattribs.c @@ -37,8 +37,6 @@ struct _GContentAttributes { GObject parent; /* A laisser en premier */ - char *filename; /* Fichier de base du chemin */ - GGenConfig **configs; /* Paramètres par niveaux */ size_t count; /* Quantité de ces niveaux */ @@ -108,8 +106,6 @@ static void g_content_attributes_class_init(GContentAttributesClass *klass) static void g_content_attributes_init(GContentAttributes *attribs) { - attribs->filename = NULL; - attribs->configs = malloc(sizeof(GGenConfig *)); attribs->count = 1; @@ -165,7 +161,8 @@ static void g_content_attributes_finalize(GContentAttributes *attribs) /****************************************************************************** * * -* Paramètres : path = chemin d'accès à un contenu à charger. * +* Paramètres : path = chemin d'accès à un contenu à charger. * +* filename = nom de fichier embarqué. * * * * Description : Construit un ensemble d'attribut pour contenu binaire. * * * @@ -175,7 +172,7 @@ static void g_content_attributes_finalize(GContentAttributes *attribs) * * ******************************************************************************/ -GContentAttributes *g_content_attributes_new(const char *path) +GContentAttributes *g_content_attributes_new(const char *path, char **filename) { GContentAttributes *result; /* Adresse à retourner */ GGenConfig *config; /* Niveau de config. courant */ @@ -184,17 +181,26 @@ GContentAttributes *g_content_attributes_new(const char *path) char *part; /* Clef et sa valeur */ char *eq; /* Signe '=' rencontré */ + if (filename != NULL) + *filename = NULL; + result = g_object_new(G_TYPE_CONTENT_ATTRIBUTES, NULL); iter = strchr(path, '&'); if (iter == NULL) - result->filename = strdup(path); + { + if (strlen(path) && filename != NULL) + *filename = strdup(path); + } else { if (iter != path) - result->filename = strndup(path, iter - path); + { + if (filename != NULL) + *filename = strndup(path, iter - path); + } config = result->configs[0]; @@ -253,29 +259,6 @@ GContentAttributes *g_content_attributes_new(const char *path) /****************************************************************************** * * * Paramètres : attribs = ensemble d'attributs de contenu à consulter. * -* * -* Description : Fournit le fichier de base compris dans le chemin initial. * -* * -* Retour : Nom de fichier renvoyant vers un contenu à charger ou NULL. * -* * -* Remarques : - * -* * -******************************************************************************/ - -const char *g_content_attributes_get_filename(const GContentAttributes *attribs) -{ - char *result; /* Nom de fichier à retourner */ - - result = attribs->filename; - - return result; - -} - - -/****************************************************************************** -* * -* Paramètres : attribs = ensemble d'attributs de contenu à consulter. * * count = taille de la liste de clefs renvoyées. [OUT] * * * * Description : Fournit l'ensemble des clefs d'un ensemble d'attributs. * diff --git a/src/analysis/cattribs.h b/src/analysis/cattribs.h index c2e8a2e..2745fde 100644 --- a/src/analysis/cattribs.h +++ b/src/analysis/cattribs.h @@ -47,10 +47,7 @@ typedef struct _GContentAttributesClass GContentAttributesClass; GType g_content_attributes_get_type(void); /* Construit un ensemble d'attribut pour contenu binaire. */ -GContentAttributes *g_content_attributes_new(const char *); - -/* Fournit le fichier de base compris dans le chemin initial. */ -const char *g_content_attributes_get_filename(const GContentAttributes *); +GContentAttributes *g_content_attributes_new(const char *, char **); /* Fournit l'ensemble des clefs d'un ensemble d'attributs. */ const char **g_content_attributes_get_keys(const GContentAttributes *, size_t *); diff --git a/src/analysis/content-int.h b/src/analysis/content-int.h index 4ef64f9..3475b3f 100644 --- a/src/analysis/content-int.h +++ b/src/analysis/content-int.h @@ -2,7 +2,7 @@ /* Chrysalide - Outil d'analyse de fichiers binaires * content-int.h - définitions internes propres aux contenus binaires * - * Copyright (C) 2015-2019 Cyrille Bagard + * Copyright (C) 2015-2023 Cyrille Bagard * * This file is part of Chrysalide. * @@ -26,6 +26,7 @@ #include "content.h" +#include "storage/serialize-int.h" @@ -83,11 +84,24 @@ typedef bool (* read_uleb128_fc) (const GBinContent *, vmpa2t *, uleb128_t *); /* Lit un nombre signé encodé au format LEB128. */ typedef bool (* read_leb128_fc) (const GBinContent *, vmpa2t *, leb128_t *); +/* Charge un objet depuis une mémoire tampon. */ +typedef bool (* load_content_cb) (GBinContent *, GObjectStorage *, packed_buffer_t *); -/* Accès à un contenu binaire quelconque (interface) */ -struct _GBinContentIface +/* Sauvegarde un objet dans une mémoire tampon. */ +typedef bool (* store_content_cb) (const GBinContent *, GObjectStorage *, packed_buffer_t *); + + +/* Accès à un contenu binaire quelconque (instance) */ +struct _GBinContent { - GTypeInterface base_iface; /* A laisser en premier */ + GObject parent; /* A laisser en premier */ + +}; + +/* Accès à un contenu binaire quelconque (classe) */ +struct _GBinContentClass +{ + GObjectClass parent; /* A laisser en premier */ set_content_attributes set_attribs; /* Enregistrement d'attributs */ get_content_attributes get_attribs; /* Fourniture d'attributs */ @@ -116,11 +130,10 @@ struct _GBinContentIface read_uleb128_fc read_uleb128; /* Lecture d'un LEB non signé */ read_leb128_fc read_leb128; /* Lecture d'un LEB signé */ -}; - + load_content_cb load; /* Chargement */ + store_content_cb store; /* Enregistrement */ -/* Redéfinition */ -typedef GBinContentIface GBinContentInterface; +}; diff --git a/src/analysis/content.c b/src/analysis/content.c index 626497e..e12237f 100644 --- a/src/analysis/content.c +++ b/src/analysis/content.c @@ -35,20 +35,94 @@ -/* Procède à l'initialisation de l'interface de rassemblement. */ -static void g_binary_content_default_init(GBinContentInterface *); +/* -------------------------- ENSEMBLE DE DONNEES BINAIRES -------------------------- */ +/* Initialise la classe des contenus binaires à parcourir. */ +static void g_binary_content_class_init(GBinContentClass *); -/* Détermine le type d'une interface pour la lecture de binaire. */ -G_DEFINE_INTERFACE(GBinContent, g_binary_content, G_TYPE_OBJECT); +/* Initialise l'instance de contenu binaire à parcourir. */ +static void g_binary_content_init(GBinContent *); + +/* Procède à l'initialisation de l'interface de sérialisation. */ +static void g_binary_content_serializable_interface_init(GSerializableObjectIface *); + +/* Supprime toutes les références externes. */ +static void g_binary_content_dispose(GBinContent *); + +/* Procède à la libération totale de la mémoire. */ +static void g_binary_content_finalize(GBinContent *); + + + +/* -------------------- CONSERVATION ET RECHARGEMENT DES DONNEES -------------------- */ + + +/* Charge un contenu depuis une mémoire tampon. */ +static bool g_binary_content_load(GBinContent *, GObjectStorage *, packed_buffer_t *); + +/* Sauvegarde un contenu dans une mémoire tampon. */ +static bool g_binary_content_store(const GBinContent *, GObjectStorage *, packed_buffer_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* ENSEMBLE DE DONNEES BINAIRES */ +/* ---------------------------------------------------------------------------------- */ + + +/* Détermine le type d'un contenu binaire à parcourir. */ +G_DEFINE_TYPE_WITH_CODE(GBinContent, g_binary_content, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_binary_content_serializable_interface_init)); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des contenus binaires à parcourir. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_binary_content_class_init(GBinContentClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_binary_content_dispose; + object->finalize = (GObjectFinalizeFunc)g_binary_content_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : content = instance à initialiser. * +* * +* Description : Initialise l'instance de contenu binaire à parcourir. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_binary_content_init(GBinContent *content) +{ + +} /****************************************************************************** * * * Paramètres : iface = interface GLib à initialiser. * * * -* Description : Procède à l'initialisation de l'interface de rassemblement. * +* Description : Procède à l'initialisation de l'interface de sérialisation. * * * * Retour : - * * * @@ -56,8 +130,48 @@ G_DEFINE_INTERFACE(GBinContent, g_binary_content, G_TYPE_OBJECT); * * ******************************************************************************/ -static void g_binary_content_default_init(GBinContentInterface *iface) +static void g_binary_content_serializable_interface_init(GSerializableObjectIface *iface) { + iface->load = (load_serializable_object_cb)g_binary_content_load; + iface->store = (store_serializable_object_cb)g_binary_content_store; + +} + + +/****************************************************************************** +* * +* Paramètres : content = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_binary_content_dispose(GBinContent *content) +{ + G_OBJECT_CLASS(g_binary_content_parent_class)->dispose(G_OBJECT(content)); + +} + + +/****************************************************************************** +* * +* Paramètres : content = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_binary_content_finalize(GBinContent *content) +{ + G_OBJECT_CLASS(g_binary_content_parent_class)->finalize(G_OBJECT(content)); } @@ -77,19 +191,11 @@ static void g_binary_content_default_init(GBinContentInterface *iface) void g_binary_content_set_attributes(GBinContent *content, GContentAttributes *attribs) { - GContentAttributes *old; /* Ancien jeu d'attributs */ - GBinContentIface *iface; /* Interface utilisée */ - - iface = G_BIN_CONTENT_GET_IFACE(content); - - old = iface->get_attribs(content); + GBinContentClass *class; /* Classe de l'instance */ - if (old != NULL) - g_object_unref(G_OBJECT(old)); + class = G_BIN_CONTENT_GET_CLASS(content); - iface->set_attribs(content, attribs); - - g_object_ref_sink(G_OBJECT(attribs)); + class->set_attribs(content, attribs); } @@ -109,13 +215,11 @@ void g_binary_content_set_attributes(GBinContent *content, GContentAttributes *a GContentAttributes *g_binary_content_get_attributes(const GBinContent *content) { GContentAttributes *result; /* Instance à retourner */ - GBinContentIface *iface; /* Interface utilisée */ - - iface = G_BIN_CONTENT_GET_IFACE(content); + GBinContentClass *class; /* Classe de l'instance */ - result = iface->get_attribs(content); + class = G_BIN_CONTENT_GET_CLASS(content); - g_object_ref(G_OBJECT(result)); + result = class->get_attribs(content); return result; @@ -137,13 +241,11 @@ GContentAttributes *g_binary_content_get_attributes(const GBinContent *content) GBinContent *g_binary_content_get_root(GBinContent *content) { GBinContent *result; /* Contenu en place à renvoyer */ - GBinContentIface *iface; /* Interface utilisée */ - - iface = G_BIN_CONTENT_GET_IFACE(content); + GBinContentClass *class; /* Classe de l'instance */ - result = iface->get_root(content); + class = G_BIN_CONTENT_GET_CLASS(content); - g_object_ref(G_OBJECT(result)); + result = class->get_root(content); return result; @@ -166,11 +268,11 @@ GBinContent *g_binary_content_get_root(GBinContent *content) char *g_binary_content_describe(const GBinContent *content, bool full) { char *result; /* Description à retourner */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->describe(content, full); + result = class->describe(content, full); return result; @@ -193,7 +295,7 @@ const gchar *g_binary_content_get_checksum(GBinContent *content) { const gchar *result; /* Empreinte à retourner */ GChecksum *checksum; /* Calcul de l'empreinte */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ checksum = g_object_get_data(G_OBJECT(content), "checksum"); @@ -204,9 +306,9 @@ const gchar *g_binary_content_get_checksum(GBinContent *content) g_checksum_reset(checksum); - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - iface->compute_checksum(content, checksum); + class->compute_checksum(content, checksum); g_object_set_data_full(G_OBJECT(content), "checksum", checksum, (GDestroyNotify)g_checksum_free); @@ -233,11 +335,11 @@ const gchar *g_binary_content_get_checksum(GBinContent *content) phys_t g_binary_content_compute_size(const GBinContent *content) { - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - return iface->compute_size(content); + return class->compute_size(content); } @@ -257,11 +359,11 @@ phys_t g_binary_content_compute_size(const GBinContent *content) void g_binary_content_compute_start_pos(const GBinContent *content, vmpa2t *pos) { - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - return iface->compute_start_pos(content, pos); + return class->compute_start_pos(content, pos); } @@ -281,11 +383,11 @@ void g_binary_content_compute_start_pos(const GBinContent *content, vmpa2t *pos) void g_binary_content_compute_end_pos(const GBinContent *content, vmpa2t *pos) { - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - return iface->compute_end_pos(content, pos); + return class->compute_end_pos(content, pos); } @@ -306,11 +408,11 @@ void g_binary_content_compute_end_pos(const GBinContent *content, vmpa2t *pos) bool g_binary_content_seek(const GBinContent *content, vmpa2t *addr, phys_t length) { - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - return iface->seek(content, addr, length); + return class->seek(content, addr, length); } @@ -331,11 +433,11 @@ bool g_binary_content_seek(const GBinContent *content, vmpa2t *addr, phys_t leng const bin_t *g_binary_content_get_raw_access(const GBinContent *content, vmpa2t *addr, phys_t length) { - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - return iface->get_raw_access(content, addr, length); + return class->get_raw_access(content, addr, length); } @@ -358,11 +460,99 @@ const bin_t *g_binary_content_get_raw_access(const GBinContent *content, vmpa2t bool g_binary_content_read_raw(const GBinContent *content, vmpa2t *addr, phys_t length, bin_t *out) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ + + class = G_BIN_CONTENT_GET_CLASS(content); + + result = class->read_raw(content, addr, length, out); - iface = G_BIN_CONTENT_GET_IFACE(content); + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à venir lire. * +* addr = position de la tête de lecture complète. * +* size = quantité de bits à lire. * +* endian = ordre des bits dans la source. * +* val = lieu d'enregistrement de la lecture. [OUT] * +* * +* Description : Lit un nombre non signé sur deux octets. * +* * +* Retour : Bilan de l'opération : true en cas de succès, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_binary_content_read_bits(const GBinContent *content, ext_vmpa_t *addr, uint8_t size, SourceEndian endian, uint64_t *val) +{ + bool result; /* Bilan de lecture à renvoyer */ + vmpa2t pos; /* Tête de lecture courante */ + uint8_t data; /* Données à parcourir */ + uint8_t i; /* Boucle de parcours */ + uint8_t remaining; /* Nombre de bits disponibles */ + uint64_t bit; /* Nouveau bit à intégrer */ + + assert(addr->consumed_extra_bits < 8); + assert(size <= 64); + + if (addr->consumed_extra_bits >= 8 || size > 64) + return false; + + copy_vmpa(&pos, &addr->base); + + result = g_binary_content_read_u8(content, &pos, &data); + if (!result) goto exit; + + remaining = 8 - addr->consumed_extra_bits; + + *val = 0; + + for (i = 0; i < size; i++) + { + if (remaining == 0) + { + result = g_binary_content_read_u8(content, &pos, &data); + if (!result) goto exit; + + remaining = 8; + + } + + bit = (data >> (remaining - 1)) & 0x1; + + remaining--; + + switch (endian) + { + case SRE_LITTLE: + *val |= (bit << i); + break; + + case SRE_BIG: + *val |= (bit << (size - i - 1)); + break; + + default: + assert(false); + result = false; + break; + + } + + } + + if (result) + { + advance_vmpa(&addr->base, get_phy_addr(&pos) - get_phy_addr(&addr->base) - 1); + addr->consumed_extra_bits = 8 - remaining; + + } - result = iface->read_raw(content, addr, length, out); + exit: return result; @@ -387,11 +577,11 @@ bool g_binary_content_read_raw(const GBinContent *content, vmpa2t *addr, phys_t bool g_binary_content_read_u4(const GBinContent *content, vmpa2t *addr, bool *low, uint8_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_u4(content, addr, low, val); + result = class->read_u4(content, addr, low, val); return result; @@ -416,11 +606,11 @@ bool g_binary_content_read_u4(const GBinContent *content, vmpa2t *addr, bool *lo bool g_binary_content_read_u8(const GBinContent *content, vmpa2t *addr, uint8_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_u8(content, addr, val); + result = class->read_u8(content, addr, val); return result; @@ -445,11 +635,11 @@ bool g_binary_content_read_u8(const GBinContent *content, vmpa2t *addr, uint8_t bool g_binary_content_read_u16(const GBinContent *content, vmpa2t *addr, SourceEndian endian, uint16_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_u16(content, addr, endian, val); + result = class->read_u16(content, addr, endian, val); return result; @@ -474,11 +664,11 @@ bool g_binary_content_read_u16(const GBinContent *content, vmpa2t *addr, SourceE bool g_binary_content_read_u32(const GBinContent *content, vmpa2t *addr, SourceEndian endian, uint32_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_u32(content, addr, endian, val); + result = class->read_u32(content, addr, endian, val); return result; @@ -503,11 +693,11 @@ bool g_binary_content_read_u32(const GBinContent *content, vmpa2t *addr, SourceE bool g_binary_content_read_u64(const GBinContent *content, vmpa2t *addr, SourceEndian endian, uint64_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_u64(content, addr, endian, val); + result = class->read_u64(content, addr, endian, val); return result; @@ -531,11 +721,11 @@ bool g_binary_content_read_u64(const GBinContent *content, vmpa2t *addr, SourceE bool g_binary_content_read_uleb128(const GBinContent *content, vmpa2t *addr, uleb128_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_uleb128(content, addr, val); + result = class->read_uleb128(content, addr, val); return result; @@ -559,11 +749,73 @@ bool g_binary_content_read_uleb128(const GBinContent *content, vmpa2t *addr, ule bool g_binary_content_read_leb128(const GBinContent *content, vmpa2t *addr, leb128_t *val) { bool result; /* Bilan à remonter */ - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ + + class = G_BIN_CONTENT_GET_CLASS(content); + + result = class->read_leb128(content, addr, val); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* CONSERVATION ET RECHARGEMENT DES DONNEES */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : content = élément GLib à constuire. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à lire. * +* * +* Description : Charge un contenu depuis une mémoire tampon. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_binary_content_load(GBinContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +{ + bool result; /* Bilan à retourner */ + GBinContentClass *class; /* Classe de l'instance */ + + class = G_BIN_CONTENT_GET_CLASS(content); + + result = class->load(content, storage, pbuf); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : content = élément GLib à consulter. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à remplir. * +* * +* Description : Sauvegarde un contenu dans une mémoire tampon. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_binary_content_store(const GBinContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +{ + bool result; /* Bilan à retourner */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content); + class = G_BIN_CONTENT_GET_CLASS(content); - result = iface->read_leb128(content, addr, val); + result = class->store(content, storage, pbuf); return result; diff --git a/src/analysis/content.h b/src/analysis/content.h index afb721e..ee79a9c 100644 --- a/src/analysis/content.h +++ b/src/analysis/content.h @@ -36,22 +36,22 @@ -#define G_TYPE_BIN_CONTENT (g_binary_content_get_type()) -#define G_BIN_CONTENT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_BIN_CONTENT, GBinContent)) -#define G_BIN_CONTENT_CLASS(vtable) (G_TYPE_CHECK_CLASS_CAST((vtable), G_TYPE_BIN_CONTENT, GBinContentIface)) -#define G_IS_BIN_CONTENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_BIN_CONTENT)) -#define G_IS_BIN_CONTENT_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE((vtable), G_TYPE_BIN_CONTENT)) -#define G_BIN_CONTENT_GET_IFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE((inst), G_TYPE_BIN_CONTENT, GBinContentIface)) +#define G_TYPE_BIN_CONTENT g_binary_content_get_type() +#define G_BIN_CONTENT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_BIN_CONTENT, GBinContent)) +#define G_IS_BIN_CONTENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_BIN_CONTENT)) +#define G_BIN_CONTENT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_BIN_CONTENT, GBinContentClass)) +#define G_IS_BIN_CONTENT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_BIN_CONTENT)) +#define G_BIN_CONTENT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_BIN_CONTENT, GBinContentClass)) -/* Accès à un contenu binaire quelconque (coquille vide) */ +/* Accès à un contenu binaire quelconque (instance) */ typedef struct _GBinContent GBinContent; -/* Accès à un contenu binaire quelconque (interface) */ -typedef struct _GBinContentIface GBinContentIface; +/* Accès à un contenu binaire quelconque (classe) */ +typedef struct _GBinContentClass GBinContentClass; -/* Détermine le type d'une interface pour la lecture de binaire. */ +/* Détermine le type d'un contenu binaire à parcourir. */ GType g_binary_content_get_type(void) G_GNUC_CONST; /* Associe un ensemble d'attributs au contenu binaire. */ @@ -87,6 +87,9 @@ const bin_t *g_binary_content_get_raw_access(const GBinContent *, vmpa2t *, phys /* Fournit une portion des données représentées. */ bool g_binary_content_read_raw(const GBinContent *, vmpa2t *, phys_t, bin_t *); +/* Lit un nombre non signé sur deux octets. */ +bool g_binary_content_read_bits(const GBinContent *, ext_vmpa_t *, uint8_t, SourceEndian, uint64_t *); + /* Lit un nombre non signé sur quatre bits. */ bool g_binary_content_read_u4(const GBinContent *, vmpa2t *, bool *, uint8_t *); diff --git a/src/analysis/contents/Makefile.am b/src/analysis/contents/Makefile.am index 66e3cac..e1cf04f 100644 --- a/src/analysis/contents/Makefile.am +++ b/src/analysis/contents/Makefile.am @@ -2,24 +2,18 @@ noinst_LTLIBRARIES = libanalysiscontents.la libanalysiscontents_la_SOURCES = \ + encapsulated-int.h \ encapsulated.h encapsulated.c \ + file-int.h \ file.h file.c \ memory-int.h \ memory.h memory.c \ + restricted-int.h \ restricted.h restricted.c -libanalysiscontents_la_LIBADD = - -libanalysiscontents_la_LDFLAGS = +libanalysiscontents_la_CFLAGS = $(TOOLKIT_CFLAGS) devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysiscontents_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = diff --git a/src/analysis/contents/encapsulated-int.h b/src/analysis/contents/encapsulated-int.h new file mode 100644 index 0000000..5ccd318 --- /dev/null +++ b/src/analysis/contents/encapsulated-int.h @@ -0,0 +1,62 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * encapsulated-int.h - prototypes internes pour le chargement de données binaires à partir d'un contenu restreint + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Chrysalide. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_CONTENTS_ENCAPSULATED_INT_H +#define _ANALYSIS_CONTENTS_ENCAPSULATED_INT_H + + +#include "encapsulated.h" + + +#include "../content-int.h" + + + +/* Contenu de données binaires issues d'un contenu restreint (instance) */ +struct _GEncapsContent +{ + GBinContent parent; /* A laisser en premier */ + + GBinContent *base; /* Base offrant une extraction */ + char *path; /* Chemin vers le contenu ciblé*/ + GBinContent *endpoint; /* Contenu ciblé */ + + char *full_desc; /* Description de l'ensemble */ + char *desc; /* Description de l'ensemble */ + +}; + +/* Contenu de données binaires issues d'un contenu restreint (classe) */ +struct _GEncapsContentClass +{ + GBinContentClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un contenu de données brutes encapsulées. */ +bool g_encaps_content_create(GEncapsContent *, GBinContent *, const char *, GBinContent *); + + + +#endif /* _ANALYSIS_CONTENTS_ENCAPSULATED_INT_H */ diff --git a/src/analysis/contents/encapsulated.c b/src/analysis/contents/encapsulated.c index 7fb7e0c..e0e6ed1 100644 --- a/src/analysis/contents/encapsulated.c +++ b/src/analysis/contents/encapsulated.c @@ -28,33 +28,14 @@ #include <string.h> -#include "../content-int.h" +#include "encapsulated-int.h" #include "../db/misc/rlestr.h" #include "../storage/serialize-int.h" #include "../../common/extstr.h" -/* Contenu de issu d'un contenu plus global (instance) */ -struct _GEncapsContent -{ - GObject parent; /* A laisser en premier */ - - GBinContent *base; /* Base offrant une extraction */ - char *path; /* Chemin vers le contenu ciblé*/ - GBinContent *endpoint; /* Contenu ciblé */ - - char *full_desc; /* Description de l'ensemble */ - char *desc; /* Description de l'ensemble */ - -}; - -/* Contenu de issu d'un contenu plus global (classe) */ -struct _GEncapsContentClass -{ - GObjectClass parent; /* A laisser en premier */ - -}; +/* -------------------------- ENSEMBLE DE DONNEES BINAIRES -------------------------- */ /* Initialise la classe des contenus de données encapsulés. */ @@ -63,23 +44,22 @@ static void g_encaps_content_class_init(GEncapsContentClass *); /* Initialise une instance de contenu de données encapsulé. */ static void g_encaps_content_init(GEncapsContent *); -/* Procède à l'initialisation de l'interface de sérialisation. */ -static void g_encaps_content_serializable_init(GSerializableObjectInterface *); - -/* Procède à l'initialisation de l'interface de lecture. */ -static void g_encaps_content_interface_init(GBinContentInterface *); - /* Supprime toutes les références externes. */ static void g_encaps_content_dispose(GEncapsContent *); /* Procède à la libération totale de la mémoire. */ static void g_encaps_content_finalize(GEncapsContent *); -/* Charge un contenu depuis une mémoire tampon. */ -static bool g_encaps_content_load(GEncapsContent *, GObjectStorage *, packed_buffer_t *); -/* Sauvegarde un contenu dans une mémoire tampon. */ -static bool g_encaps_content_store(const GEncapsContent *, GObjectStorage *, packed_buffer_t *); + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Associe un ensemble d'attributs au contenu binaire. */ +static void g_encaps_content_set_attributes(GEncapsContent *, GContentAttributes *); + +/* Fournit l'ensemble des attributs associés à un contenu. */ +static GContentAttributes *g_encaps_content_get_attributes(const GEncapsContent *); /* Donne l'origine d'un contenu binaire. */ static GBinContent *g_encaps_content_get_root(GEncapsContent *); @@ -129,12 +109,21 @@ static bool g_encaps_content_read_uleb128(const GEncapsContent *, vmpa2t *, uleb /* Lit un nombre signé encodé au format LEB128. */ static bool g_encaps_content_read_leb128(const GEncapsContent *, vmpa2t *, leb128_t *); +/* Charge un contenu depuis une mémoire tampon. */ +static bool g_encaps_content_load(GEncapsContent *, GObjectStorage *, packed_buffer_t *); + +/* Sauvegarde un contenu dans une mémoire tampon. */ +static bool g_encaps_content_store(const GEncapsContent *, GObjectStorage *, packed_buffer_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* ENSEMBLE DE DONNEES BINAIRES */ +/* ---------------------------------------------------------------------------------- */ /* Indique le type défini par la GLib pour les contenus encapsulés. */ -G_DEFINE_TYPE_WITH_CODE(GEncapsContent, g_encaps_content, G_TYPE_OBJECT, - G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_encaps_content_serializable_init) - G_IMPLEMENT_INTERFACE(G_TYPE_BIN_CONTENT, g_encaps_content_interface_init)); +G_DEFINE_TYPE(GEncapsContent, g_encaps_content, G_TYPE_BIN_CONTENT); /****************************************************************************** @@ -152,64 +141,53 @@ G_DEFINE_TYPE_WITH_CODE(GEncapsContent, g_encaps_content, G_TYPE_OBJECT, static void g_encaps_content_class_init(GEncapsContentClass *klass) { GObjectClass *object; /* Autre version de la classe */ + GBinContentClass *content; /* Version parente de la classe*/ object = G_OBJECT_CLASS(klass); object->dispose = (GObjectFinalizeFunc/* ! */)g_encaps_content_dispose; object->finalize = (GObjectFinalizeFunc)g_encaps_content_finalize; -} + content = G_BIN_CONTENT_CLASS(klass); + content->set_attribs = (set_content_attributes)g_encaps_content_set_attributes; + content->get_attribs = (get_content_attributes)g_encaps_content_get_attributes; -/****************************************************************************** -* * -* Paramètres : content = instance à initialiser. * -* * -* Description : Initialise une instance de contenu de données encapsulé. * -* * -* Retour : - * -* * -* Remarques : - * -* * -******************************************************************************/ + content->get_root = (get_content_root_fc)g_encaps_content_get_root; -static void g_encaps_content_init(GEncapsContent *content) -{ - content->base = NULL; - content->path = NULL; - content->endpoint = NULL; + content->describe = (describe_content_fc)g_encaps_content_describe; - content->full_desc = NULL; - content->desc = NULL; + content->compute_checksum = (compute_checksum_fc)g_encaps_content_compute_checksum; -} + content->compute_size = (compute_size_fc)g_encaps_content_compute_size; + content->compute_start_pos = (compute_start_pos_fc)g_encaps_content_compute_start_pos; + content->compute_end_pos = (compute_end_pos_fc)g_encaps_content_compute_end_pos; + content->seek = (seek_fc)g_encaps_content_seek; -/****************************************************************************** -* * -* Paramètres : iface = interface GLib à initialiser. * -* * -* Description : Procède à l'initialisation de l'interface de sérialisation. * -* * -* Retour : - * -* * -* Remarques : - * -* * -******************************************************************************/ + content->get_raw_access = (get_raw_access_fc)g_encaps_content_get_raw_access; -static void g_encaps_content_serializable_init(GSerializableObjectInterface *iface) -{ - iface->load = (load_serializable_object_cb)g_encaps_content_load; - iface->store = (store_serializable_object_cb)g_encaps_content_store; + content->read_raw = (read_raw_fc)g_encaps_content_read_raw; + content->read_u4 = (read_u4_fc)g_encaps_content_read_u4; + content->read_u8 = (read_u8_fc)g_encaps_content_read_u8; + content->read_u16 = (read_u16_fc)g_encaps_content_read_u16; + content->read_u32 = (read_u32_fc)g_encaps_content_read_u32; + content->read_u64 = (read_u64_fc)g_encaps_content_read_u64; + + content->read_uleb128 = (read_uleb128_fc)g_encaps_content_read_uleb128; + content->read_leb128 = (read_leb128_fc)g_encaps_content_read_leb128; + + content->load = (load_content_cb)g_encaps_content_load; + content->store = (store_content_cb)g_encaps_content_store; } /****************************************************************************** * * -* Paramètres : iface = interface GLib à initialiser. * +* Paramètres : content = instance à initialiser. * * * -* Description : Procède à l'initialisation de l'interface de lecture. * +* Description : Initialise une instance de contenu de données encapsulé. * * * * Retour : - * * * @@ -217,31 +195,14 @@ static void g_encaps_content_serializable_init(GSerializableObjectInterface *ifa * * ******************************************************************************/ -static void g_encaps_content_interface_init(GBinContentInterface *iface) +static void g_encaps_content_init(GEncapsContent *content) { - iface->get_root = (get_content_root_fc)g_encaps_content_get_root; - - iface->describe = (describe_content_fc)g_encaps_content_describe; - - iface->compute_checksum = (compute_checksum_fc)g_encaps_content_compute_checksum; - - iface->compute_size = (compute_size_fc)g_encaps_content_compute_size; - iface->compute_start_pos = (compute_start_pos_fc)g_encaps_content_compute_start_pos; - iface->compute_end_pos = (compute_end_pos_fc)g_encaps_content_compute_end_pos; - - iface->seek = (seek_fc)g_encaps_content_seek; - - iface->get_raw_access = (get_raw_access_fc)g_encaps_content_get_raw_access; - - iface->read_raw = (read_raw_fc)g_encaps_content_read_raw; - iface->read_u4 = (read_u4_fc)g_encaps_content_read_u4; - iface->read_u8 = (read_u8_fc)g_encaps_content_read_u8; - iface->read_u16 = (read_u16_fc)g_encaps_content_read_u16; - iface->read_u32 = (read_u32_fc)g_encaps_content_read_u32; - iface->read_u64 = (read_u64_fc)g_encaps_content_read_u64; + content->base = NULL; + content->path = NULL; + content->endpoint = NULL; - iface->read_uleb128 = (read_uleb128_fc)g_encaps_content_read_uleb128; - iface->read_leb128 = (read_leb128_fc)g_encaps_content_read_leb128; + content->full_desc = NULL; + content->desc = NULL; } @@ -310,41 +271,26 @@ static void g_encaps_content_finalize(GEncapsContent *content) GBinContent *g_encaps_content_new(GBinContent *base, const char *path, GBinContent *endpoint) { - GEncapsContent *result; /* Structure à retourner */ + GBinContent *result; /* Structure à retourner */ result = g_object_new(G_TYPE_ENCAPS_CONTENT, NULL); - g_object_ref(base); - g_object_ref(endpoint); - - result->base = base; - result->path = strdup(path); - result->endpoint = endpoint; - - /* Description complète */ - - result->full_desc = g_binary_content_describe(result->base, true); - - result->full_desc = stradd(result->full_desc, G_DIR_SEPARATOR_S); - - result->full_desc = stradd(result->full_desc, path); + if (!g_encaps_content_create(G_ENCAPS_CONTENT(result), base, path, endpoint)) + g_clear_object(&result); - /* Description partielle */ - - result->desc = strdup(path); - - return G_BIN_CONTENT(result); + return result; } /****************************************************************************** * * -* Paramètres : content = élément GLib à constuire. * -* storage = conservateur de données à manipuler ou NULL. * -* pbuf = zone tampon à lire. * +* Paramètres : content = instance à initialiser pleinement. * +* base = contenu binaire d'où réaliser une extraction. * +* path = chemin vers le contenu finalement ciblé. * +* endpoint = contenu final rendu accessible. * * * -* Description : Charge un contenu depuis une mémoire tampon. * +* Description : Met en place un contenu de données brutes encapsulées. * * * * Retour : Bilan de l'opération. * * * @@ -352,63 +298,79 @@ GBinContent *g_encaps_content_new(GBinContent *base, const char *path, GBinConte * * ******************************************************************************/ -static bool g_encaps_content_load(GEncapsContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +bool g_encaps_content_create(GEncapsContent *content, GBinContent *base, const char *path, GBinContent *endpoint) { bool result; /* Bilan à retourner */ - rle_string str; /* Chaîne à charger */ - content->base = G_BIN_CONTENT(g_object_storage_unpack_object(storage, "contents", pbuf)); - result = (content->base != NULL); + g_object_ref(base); + g_object_ref(endpoint); - setup_empty_rle_string(&str); + content->base = base; + content->path = strdup(path); + content->endpoint = endpoint; - if (result) - result = unpack_rle_string(&str, pbuf); + /* Description complète */ - if (result) - { - result = (get_rle_string(&str) != NULL); + content->full_desc = g_binary_content_describe(content->base, true); - if (result) - content->path = strdup(get_rle_string(&str)); + content->full_desc = stradd(content->full_desc, G_DIR_SEPARATOR_S); - exit_rle_string(&str); + content->full_desc = stradd(content->full_desc, path); - } + /* Description partielle */ - if (result) - { - content->endpoint = G_BIN_CONTENT(g_object_storage_unpack_object(storage, "contents", pbuf)); - result = (content->endpoint != NULL); - } + content->desc = strdup(path); - if (result) - result = unpack_rle_string(&str, pbuf); + result = true; - if (result) - { - result = (get_rle_string(&str) != NULL); + return result; - if (result) - content->full_desc = strdup(get_rle_string(&str)); +} - exit_rle_string(&str); - } +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à venir consulter. * +* * +* Description : Indique la base d'un contenu binaire encapsulé. * +* * +* Retour : Instance de contenu binaire ou NULL si aucune. * +* * +* Remarques : - * +* * +******************************************************************************/ - if (result) - result = unpack_rle_string(&str, pbuf); +GBinContent *g_encaps_content_get_base(const GEncapsContent *content) +{ + GBinContent *result; /* Contenu binaire à renvoyer */ - if (result) - { - result = (get_rle_string(&str) != NULL); + result = content->base; - if (result) - content->desc = strdup(get_rle_string(&str)); + if (result != NULL) + g_object_ref(G_OBJECT(result)); - exit_rle_string(&str); + return result; - } +} + + +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à venir consulter. * +* * +* Description : Fournit le chemin vers le contenu interne représenté. * +* * +* Retour : Chemin d'accès au contenu binaire. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char *g_encaps_content_get_path(const GEncapsContent *content) +{ + char *result; /* Chemin d'accès à retourner */ + + result = content->path; return result; @@ -417,57 +379,73 @@ static bool g_encaps_content_load(GEncapsContent *content, GObjectStorage *stora /****************************************************************************** * * -* Paramètres : content = élément GLib à consulter. * -* storage = conservateur de données à manipuler ou NULL. * -* pbuf = zone tampon à remplir. * +* Paramètres : content = contenu binaire à venir consulter. * * * -* Description : Sauvegarde un contenu dans une mémoire tampon. * +* Description : Indique le contenu binaire embarqué dans une encapsulation. * * * -* Retour : Bilan de l'opération. * +* Retour : Instance de contenu binaire ou NULL si aucune. * * * * Remarques : - * * * ******************************************************************************/ -static bool g_encaps_content_store(const GEncapsContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +GBinContent *g_encaps_content_get_endpoint(const GEncapsContent *content) { - bool result; /* Bilan à retourner */ - rle_string str; /* Chaîne à conserver */ + GBinContent *result; /* Contenu binaire à renvoyer */ - result = g_object_storage_pack_object(storage, "contents", G_SERIALIZABLE_OBJECT(content->base), pbuf); + result = content->endpoint; - if (result) - { - init_static_rle_string(&str, content->path); + if (result != NULL) + g_object_ref(G_OBJECT(result)); - result = pack_rle_string(&str, pbuf); + return result; - exit_rle_string(&str); +} - } - if (result) - result = g_object_storage_pack_object(storage, "contents", G_SERIALIZABLE_OBJECT(content->endpoint), pbuf); - if (result) - { - init_static_rle_string(&str, content->full_desc); +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ - result = pack_rle_string(&str, pbuf); - exit_rle_string(&str); +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à actualiser. * +* attribs = jeu d'attributs à lier au contenu courant. * +* * +* Description : Associe un ensemble d'attributs au contenu binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ - } +static void g_encaps_content_set_attributes(GEncapsContent *content, GContentAttributes *attribs) +{ + g_binary_content_set_attributes(content->endpoint, attribs); - if (result) - { - init_static_rle_string(&str, content->desc); +} - result = pack_rle_string(&str, pbuf); - exit_rle_string(&str); +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à consulter. * +* * +* Description : Fournit l'ensemble des attributs associés à un contenu. * +* * +* Retour : Jeu d'attributs liés au contenu courant. * +* * +* Remarques : - * +* * +******************************************************************************/ - } +static GContentAttributes *g_encaps_content_get_attributes(const GEncapsContent *content) +{ + GContentAttributes *result; /* Instance à retourner */ + + result = g_binary_content_get_attributes(content->endpoint); return result; @@ -539,11 +517,11 @@ static char *g_encaps_content_describe(const GEncapsContent *content, bool full) static void g_encaps_content_compute_checksum(GEncapsContent *content, GChecksum *checksum) { - GBinContentIface *iface; /* Interface utilisée */ + GBinContentClass *class; /* Classe de l'instance */ - iface = G_BIN_CONTENT_GET_IFACE(content->endpoint); + class = G_BIN_CONTENT_GET_CLASS(content); - iface->compute_checksum(content->endpoint, checksum); + class->compute_checksum(content->endpoint, checksum); } @@ -869,47 +847,75 @@ static bool g_encaps_content_read_leb128(const GEncapsContent *content, vmpa2t * /****************************************************************************** * * -* Paramètres : content = contenu binaire à venir consulter. * +* Paramètres : content = élément GLib à constuire. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à lire. * * * -* Description : Indique la base d'un contenu binaire encapsulé. * +* Description : Charge un contenu depuis une mémoire tampon. * * * -* Retour : Instance de contenu binaire ou NULL si aucune. * +* Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ -GBinContent *g_encaps_content_get_base(const GEncapsContent *content) +static bool g_encaps_content_load(GEncapsContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) { - GBinContent *result; /* Contenu binaire à renvoyer */ + bool result; /* Bilan à retourner */ + rle_string str; /* Chaîne à charger */ - result = content->base; + content->base = G_BIN_CONTENT(g_object_storage_unpack_object(storage, "contents", pbuf)); + result = (content->base != NULL); - if (result != NULL) - g_object_ref(G_OBJECT(result)); + setup_empty_rle_string(&str); - return result; + if (result) + result = unpack_rle_string(&str, pbuf); -} + if (result) + { + result = (get_rle_string(&str) != NULL); + if (result) + content->path = strdup(get_rle_string(&str)); -/****************************************************************************** -* * -* Paramètres : content = contenu binaire à venir consulter. * -* * -* Description : Fournit le chemin vers le contenu interne représenté. * -* * -* Retour : Chemin d'accès au contenu binaire. * -* * -* Remarques : - * -* * -******************************************************************************/ + exit_rle_string(&str); -const char *g_encaps_content_get_path(const GEncapsContent *content) -{ - char *result; /* Chemin d'accès à retourner */ + } - result = content->path; + if (result) + { + content->endpoint = G_BIN_CONTENT(g_object_storage_unpack_object(storage, "contents", pbuf)); + result = (content->endpoint != NULL); + } + + if (result) + result = unpack_rle_string(&str, pbuf); + + if (result) + { + result = (get_rle_string(&str) != NULL); + + if (result) + content->full_desc = strdup(get_rle_string(&str)); + + exit_rle_string(&str); + + } + + if (result) + result = unpack_rle_string(&str, pbuf); + + if (result) + { + result = (get_rle_string(&str) != NULL); + + if (result) + content->desc = strdup(get_rle_string(&str)); + + exit_rle_string(&str); + + } return result; @@ -918,24 +924,57 @@ const char *g_encaps_content_get_path(const GEncapsContent *content) /****************************************************************************** * * -* Paramètres : content = contenu binaire à venir consulter. * +* Paramètres : content = élément GLib à consulter. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à remplir. * * * -* Description : Indique le contenu binaire embarqué dans une encapsulation. * +* Description : Sauvegarde un contenu dans une mémoire tampon. * * * -* Retour : Instance de contenu binaire ou NULL si aucune. * +* Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ -GBinContent *g_encaps_content_get_endpoint(const GEncapsContent *content) +static bool g_encaps_content_store(const GEncapsContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) { - GBinContent *result; /* Contenu binaire à renvoyer */ + bool result; /* Bilan à retourner */ + rle_string str; /* Chaîne à conserver */ - result = content->endpoint; + result = g_object_storage_pack_object(storage, "contents", G_SERIALIZABLE_OBJECT(content->base), pbuf); - if (result != NULL) - g_object_ref(G_OBJECT(result)); + if (result) + { + init_static_rle_string(&str, content->path); + + result = pack_rle_string(&str, pbuf); + + exit_rle_string(&str); + + } + + if (result) + result = g_object_storage_pack_object(storage, "contents", G_SERIALIZABLE_OBJECT(content->endpoint), pbuf); + + if (result) + { + init_static_rle_string(&str, content->full_desc); + + result = pack_rle_string(&str, pbuf); + + exit_rle_string(&str); + + } + + if (result) + { + init_static_rle_string(&str, content->desc); + + result = pack_rle_string(&str, pbuf); + + exit_rle_string(&str); + + } return result; diff --git a/src/analysis/contents/file-int.h b/src/analysis/contents/file-int.h new file mode 100644 index 0000000..dc61bdc --- /dev/null +++ b/src/analysis/contents/file-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * file-int.h - prototypes internes pour le chargement de données binaires à partir d'un fichier + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Chrysalide. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_CONTENTS_FILE_INT_H +#define _ANALYSIS_CONTENTS_FILE_INT_H + + +#include "file.h" + + +#include "memory-int.h" + + + +/* Contenu de données binaires issues d'un fichier (instance) */ +struct _GFileContent +{ + GMemoryContent parent; /* A laisser en premier */ + + char *filename; /* Fichier chargé en mémoire */ + int fd; /* Flux ouvert en lectureu */ + +}; + +/* Contenu de données binaires issues d'un fichier (classe) */ +struct _GFileContentClass +{ + GMemoryContentClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un contenu d'un fichier donné. */ +bool g_file_content_create(GFileContent *, const char *); + + + +#endif /* _ANALYSIS_CONTENTS_FILE_INT_H */ diff --git a/src/analysis/contents/file.c b/src/analysis/contents/file.c index 78bd981..545d869 100644 --- a/src/analysis/contents/file.c +++ b/src/analysis/contents/file.c @@ -25,6 +25,7 @@ #include <fcntl.h> +#include <libgen.h> #include <malloc.h> #include <string.h> #include <unistd.h> @@ -32,29 +33,14 @@ #include <sys/stat.h> -#include "memory-int.h" -#include "../content-int.h" +#include "file-int.h" #include "../db/misc/rlestr.h" #include "../storage/serialize-int.h" #include "../../core/logs.h" -/* Contenu de données binaires issues d'un fichier (instance) */ -struct _GFileContent -{ - GMemoryContent parent; /* A laisser en premier */ - - char *filename; /* Fichier chargé en mémoire */ - -}; - -/* Contenu de données binaires issues d'un fichier (classe) */ -struct _GFileContentClass -{ - GMemoryContentClass parent; /* A laisser en premier */ - -}; +/* -------------------------- ENSEMBLE DE DONNEES BINAIRES -------------------------- */ /* Initialise la classe des contenus de données binaires. */ @@ -63,15 +49,20 @@ static void g_file_content_class_init(GFileContentClass *); /* Initialise une instance de contenu de données binaires. */ static void g_file_content_init(GFileContent *); -/* Procède à l'initialisation de l'interface de sérialisation. */ -static void g_file_content_serializable_init(GSerializableObjectInterface *); - /* Supprime toutes les références externes. */ static void g_file_content_dispose(GFileContent *); /* Procède à la libération totale de la mémoire. */ static void g_file_content_finalize(GFileContent *); + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom associé au contenu binaire. */ +static char *g_file_content_describe(const GFileContent *, bool); + /* Charge un contenu depuis une mémoire tampon. */ static bool g_file_content_load(GFileContent *, GObjectStorage *, packed_buffer_t *); @@ -80,9 +71,13 @@ static bool g_file_content_store(const GFileContent *, GObjectStorage *, packed_ +/* ---------------------------------------------------------------------------------- */ +/* ENSEMBLE DE DONNEES BINAIRES */ +/* ---------------------------------------------------------------------------------- */ + + /* Indique le type défini par la GLib pour les contenus de données. */ -G_DEFINE_TYPE_WITH_CODE(GFileContent, g_file_content, G_TYPE_MEMORY_CONTENT, - G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_file_content_serializable_init)); +G_DEFINE_TYPE(GFileContent, g_file_content, G_TYPE_MEMORY_CONTENT); /****************************************************************************** @@ -100,12 +95,20 @@ G_DEFINE_TYPE_WITH_CODE(GFileContent, g_file_content, G_TYPE_MEMORY_CONTENT, static void g_file_content_class_init(GFileContentClass *klass) { GObjectClass *object; /* Autre version de la classe */ + GBinContentClass *content; /* Version parente de la classe*/ object = G_OBJECT_CLASS(klass); object->dispose = (GObjectFinalizeFunc/* ! */)g_file_content_dispose; object->finalize = (GObjectFinalizeFunc)g_file_content_finalize; + content = G_BIN_CONTENT_CLASS(klass); + + content->describe = (describe_content_fc)g_file_content_describe; + + content->load = (load_content_cb)g_file_content_load; + content->store = (store_content_cb)g_file_content_store; + } @@ -124,15 +127,16 @@ static void g_file_content_class_init(GFileContentClass *klass) static void g_file_content_init(GFileContent *content) { content->filename = NULL; + content->fd = -1; } /****************************************************************************** * * -* Paramètres : iface = interface GLib à initialiser. * +* Paramètres : content = instance d'objet GLib à traiter. * * * -* Description : Procède à l'initialisation de l'interface de sérialisation. * +* Description : Supprime toutes les références externes. * * * * Retour : - * * * @@ -140,10 +144,9 @@ static void g_file_content_init(GFileContent *content) * * ******************************************************************************/ -static void g_file_content_serializable_init(GSerializableObjectInterface *iface) +static void g_file_content_dispose(GFileContent *content) { - iface->load = (load_serializable_object_cb)g_file_content_load; - iface->store = (store_serializable_object_cb)g_file_content_store; + G_OBJECT_CLASS(g_file_content_parent_class)->dispose(G_OBJECT(content)); } @@ -152,7 +155,7 @@ static void g_file_content_serializable_init(GSerializableObjectInterface *iface * * * Paramètres : content = instance d'objet GLib à traiter. * * * -* Description : Supprime toutes les références externes. * +* Description : Procède à la libération totale de la mémoire. * * * * Retour : - * * * @@ -160,55 +163,78 @@ static void g_file_content_serializable_init(GSerializableObjectInterface *iface * * ******************************************************************************/ -static void g_file_content_dispose(GFileContent *content) +static void g_file_content_finalize(GFileContent *content) { - G_OBJECT_CLASS(g_file_content_parent_class)->dispose(G_OBJECT(content)); + GMemoryContent *base; /* Structure parente */ + + free(content->filename); + + if (content->fd != -1) + { + base = G_MEMORY_CONTENT(content); + munmap(base->data, base->length); + + close(content->fd); + + } + + G_OBJECT_CLASS(g_file_content_parent_class)->finalize(G_OBJECT(content)); } + + /****************************************************************************** * * -* Paramètres : content = instance d'objet GLib à traiter. * +* Paramètres : filename = chemin d'accès au fichier à charger. * * * -* Description : Procède à la libération totale de la mémoire. * +* Description : Charge en mémoire le contenu d'un fichier donné. * * * -* Retour : - * +* Retour : Représentation de contenu à manipuler ou NULL en cas d'échec.* * * * Remarques : - * * * ******************************************************************************/ -static void g_file_content_finalize(GFileContent *content) +GBinContent *g_file_content_new(const char *filename) { - free(content->filename); + GBinContent *result; /* Structure à retourner */ - G_OBJECT_CLASS(g_file_content_parent_class)->finalize(G_OBJECT(content)); + result = g_object_new(G_TYPE_FILE_CONTENT, NULL); + + if (!g_file_content_create(G_FILE_CONTENT(result), filename)) + g_clear_object(&result); + + return result; } /****************************************************************************** * * -* Paramètres : filename = chemin d'accès au fichier à charger. * +* Paramètres : content = instance à initialiser pleinement. * +* filename = chemin d'accès au fichier à charger. * * * -* Description : Charge en mémoire le contenu d'un fichier donné. * +* Description : Met en place un contenu d'un fichier donné. * * * -* Retour : Représentation de contenu à manipuler ou NULL en cas d'échec.* +* Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ -GBinContent *g_file_content_new(const char *filename) +bool g_file_content_create(GFileContent *content, const char *filename) { - GFileContent *result; /* Structure à retourner */ + bool result; /* Bilan à retourner */ int fd; /* Descripteur du fichier */ struct stat info; /* Informations sur le fichier */ int ret; /* Bilan d'un appel */ - void *content; /* Contenu brut du fichier */ + void *data; /* Contenu brut du fichier */ GMemoryContent *base; /* Structure parente */ + result = false; + /* Récupération des données */ fd = open(filename, O_RDONLY); @@ -226,8 +252,8 @@ GBinContent *g_file_content_new(const char *filename) goto file_error; } - content = mmap(NULL, info.st_size, PROT_READ, MAP_PRIVATE, fd, 0); - if (content == MAP_FAILED) + data = mmap(NULL, info.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (data == MAP_FAILED) { close(fd); LOG_ERROR_N("mmap"); @@ -236,25 +262,86 @@ GBinContent *g_file_content_new(const char *filename) /* Constitution du contenu officiel */ - result = g_object_new(G_TYPE_FILE_CONTENT, NULL); + content->filename = strdup(filename); - result->filename = strdup(filename); + base = G_MEMORY_CONTENT(content); - base = G_MEMORY_CONTENT(result); + base->data = data; + base->length = info.st_size; - base->data = malloc(info.st_size); - memcpy(base->data, content, info.st_size); + result = true; - base->length = info.st_size; + file_error: - munmap(content, info.st_size); - close(fd); + return result; - return G_BIN_CONTENT(result); +} - file_error: - return NULL; +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à venir consulter. * +* * +* Description : Fournit le nom de fichier associé au contenu binaire. * +* * +* Retour : Chemin d'accès au contenu binaire. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char *g_file_content_get_filename(const GFileContent *content) +{ + char *result; /* Chemin d'accès à retourner */ + + result = content->filename; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : content = contenu binaire à consulter. * +* full = précise s'il s'agit d'une version longue ou non. * +* * +* Description : Fournit le nom associé au contenu binaire. * +* * +* Retour : Nom de fichier avec chemin absolu au besoin. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_file_content_describe(const GFileContent *content, bool full) +{ + char *result; /* Description à retourner */ + char *tmp; /* Copie modifiable */ + char *base; /* Description à recopier */ + + if (full) + result = strdup(content->filename); + + else + { + tmp = strdup(content->filename); + + base = basename(tmp); + + result = strdup(base); + + free(tmp); + + } + + return result; } @@ -341,26 +428,3 @@ static bool g_file_content_store(const GFileContent *content, GObjectStorage *st return result; } - - -/****************************************************************************** -* * -* Paramètres : content = contenu binaire à venir consulter. * -* * -* Description : Fournit le nom de fichier associé au contenu binaire. * -* * -* Retour : Chemin d'accès au contenu binaire. * -* * -* Remarques : - * -* * -******************************************************************************/ - -const char *g_file_content_get_filename(const GFileContent *content) -{ - char *result; /* Chemin d'accès à retourner */ - - result = content->filename; - - return result; - -} diff --git a/src/analysis/contents/memory-int.h b/src/analysis/contents/memory-int.h index 621e4a6..d3012c7 100644 --- a/src/analysis/contents/memory-int.h +++ b/src/analysis/contents/memory-int.h @@ -28,16 +28,20 @@ #include "memory.h" +#include "../content-int.h" + + /* Contenu de données binaires résidant en mémoire (instance) */ struct _GMemoryContent { - GObject parent; /* A laisser en premier */ + GBinContent parent; /* A laisser en premier */ GContentAttributes *attribs; /* Attributs liés au contenu */ bin_t *data; /* Contenu binaire représenté */ phys_t length; /* Taille totale du contenu */ + bool allocated; /* Nature de la zone de données*/ char *full_desc; /* Description de l'ensemble */ char *desc; /* Description de l'ensemble */ @@ -47,10 +51,14 @@ struct _GMemoryContent /* Contenu de données binaires résidant en mémoire (classe) */ struct _GMemoryContentClass { - GObjectClass parent; /* A laisser en premier */ + GBinContentClass parent; /* A laisser en premier */ }; +/* Met en place un contenu de données brutes depuis la mémoire. */ +bool g_memory_content_create(GMemoryContent *, const bin_t *, phys_t); + + #endif /* _ANALYSIS_CONTENTS_MEMORY_INT_H */ diff --git a/src/analysis/contents/memory.c b/src/analysis/contents/memory.c index 6a020e8..f8ff863 100644 --- a/src/analysis/contents/memory.c +++ b/src/analysis/contents/memory.c @@ -42,29 +42,25 @@ +/* -------------------------- ENSEMBLE DE DONNEES BINAIRES -------------------------- */ + + /* Initialise la classe des contenus de données en mémoire. */ static void g_memory_content_class_init(GMemoryContentClass *); /* Initialise une instance de contenu de données en mémoire. */ static void g_memory_content_init(GMemoryContent *); -/* Procède à l'initialisation de l'interface de sérialisation. */ -static void g_memory_content_serializable_init(GSerializableObjectInterface *); - -/* Procède à l'initialisation de l'interface de lecture. */ -static void g_memory_content_interface_init(GBinContentInterface *); - /* Supprime toutes les références externes. */ static void g_memory_content_dispose(GMemoryContent *); /* Procède à la libération totale de la mémoire. */ static void g_memory_content_finalize(GMemoryContent *); -/* Charge un contenu depuis une mémoire tampon. */ -static bool g_memory_content_load(GMemoryContent *, GObjectStorage *, packed_buffer_t *); -/* Sauvegarde un contenu dans une mémoire tampon. */ -static bool g_memory_content_store(const GMemoryContent *, GObjectStorage *, packed_buffer_t *); + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + /* Associe un ensemble d'attributs au contenu binaire. */ static void g_memory_content_set_attributes(GMemoryContent *, GContentAttributes *); @@ -120,12 +116,21 @@ static bool g_memory_content_read_uleb128(const GMemoryContent *, vmpa2t *, uleb /* Lit un nombre signé encodé au format LEB128. */ static bool g_memory_content_read_leb128(const GMemoryContent *, vmpa2t *, leb128_t *); +/* Charge un contenu depuis une mémoire tampon. */ +static bool g_memory_content_load(GMemoryContent *, GObjectStorage *, packed_buffer_t *); + +/* Sauvegarde un contenu dans une mémoire tampon. */ +static bool g_memory_content_store(const GMemoryContent *, GObjectStorage *, packed_buffer_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* ENSEMBLE DE DONNEES BINAIRES */ +/* ---------------------------------------------------------------------------------- */ /* Indique le type défini par la GLib pour les contenus de données en mémoire. */ -G_DEFINE_TYPE_WITH_CODE(GMemoryContent, g_memory_content, G_TYPE_OBJECT, - G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_memory_content_serializable_init) - G_IMPLEMENT_INTERFACE(G_TYPE_BIN_CONTENT, g_memory_content_interface_init)); +G_DEFINE_TYPE(GMemoryContent, g_memory_content, G_TYPE_BIN_CONTENT); /****************************************************************************** @@ -143,71 +148,53 @@ G_DEFINE_TYPE_WITH_CODE(GMemoryContent, g_memory_content, G_TYPE_OBJECT, static void g_memory_content_class_init(GMemoryContentClass *klass) { GObjectClass *object; /* Autre version de la classe */ + GBinContentClass *content; /* Version parente de la classe*/ object = G_OBJECT_CLASS(klass); object->dispose = (GObjectFinalizeFunc/* ! */)g_memory_content_dispose; object->finalize = (GObjectFinalizeFunc)g_memory_content_finalize; -} + content = G_BIN_CONTENT_CLASS(klass); + content->set_attribs = (set_content_attributes)g_memory_content_set_attributes; + content->get_attribs = (get_content_attributes)g_memory_content_get_attributes; -/****************************************************************************** -* * -* Paramètres : content = instance à initialiser. * -* * -* Description : Initialise une instance de contenu de données en mémoire. * -* * -* Retour : - * -* * -* Remarques : - * -* * -******************************************************************************/ + content->get_root = (get_content_root_fc)g_memory_content_get_root; -static void g_memory_content_init(GMemoryContent *content) -{ - GContentAttributes *empty; /* Jeu d'attributs vide */ + content->describe = (describe_content_fc)g_memory_content_describe; - content->attribs = NULL; + content->compute_checksum = (compute_checksum_fc)g_memory_content_compute_checksum; - empty = g_content_attributes_new(""); + content->compute_size = (compute_size_fc)g_memory_content_compute_size; + content->compute_start_pos = (compute_start_pos_fc)g_memory_content_compute_start_pos; + content->compute_end_pos = (compute_end_pos_fc)g_memory_content_compute_end_pos; - g_binary_content_set_attributes(G_BIN_CONTENT(content), empty); + content->seek = (seek_fc)g_memory_content_seek; - content->data = NULL; - content->length = 0; + content->get_raw_access = (get_raw_access_fc)g_memory_content_get_raw_access; - content->full_desc = strdup("In-memory content"); - content->desc = strdup("In-memory content"); + content->read_raw = (read_raw_fc)g_memory_content_read_raw; + content->read_u4 = (read_u4_fc)g_memory_content_read_u4; + content->read_u8 = (read_u8_fc)g_memory_content_read_u8; + content->read_u16 = (read_u16_fc)g_memory_content_read_u16; + content->read_u32 = (read_u32_fc)g_memory_content_read_u32; + content->read_u64 = (read_u64_fc)g_memory_content_read_u64; -} + content->read_uleb128 = (read_uleb128_fc)g_memory_content_read_uleb128; + content->read_leb128 = (read_leb128_fc)g_memory_content_read_leb128; - -/****************************************************************************** -* * -* Paramètres : iface = interface GLib à initialiser. * -* * -* Description : Procède à l'initialisation de l'interface de sérialisation. * -* * -* Retour : - * -* * -* Remarques : - * -* * -******************************************************************************/ - -static void g_memory_content_serializable_init(GSerializableObjectInterface *iface) -{ - iface->load = (load_serializable_object_cb)g_memory_content_load; - iface->store = (store_serializable_object_cb)g_memory_content_store; + content->load = (load_content_cb)g_memory_content_load; + content->store = (store_content_cb)g_memory_content_store; } /****************************************************************************** * * -* Paramètres : iface = interface GLib à initialiser. * +* Paramètres : content = instance à initialiser. * * * -* Description : Procède à l'initialisation de l'interface de lecture. * +* Description : Initialise une instance de contenu de données en mémoire. * * * * Retour : - * * * @@ -215,34 +202,24 @@ static void g_memory_content_serializable_init(GSerializableObjectInterface *ifa * * ******************************************************************************/ -static void g_memory_content_interface_init(GBinContentInterface *iface) +static void g_memory_content_init(GMemoryContent *content) { - iface->set_attribs = (set_content_attributes)g_memory_content_set_attributes; - iface->get_attribs = (get_content_attributes)g_memory_content_get_attributes; - - iface->get_root = (get_content_root_fc)g_memory_content_get_root; - - iface->describe = (describe_content_fc)g_memory_content_describe; + GContentAttributes *empty; /* Jeu d'attributs vide */ - iface->compute_checksum = (compute_checksum_fc)g_memory_content_compute_checksum; + content->attribs = NULL; - iface->compute_size = (compute_size_fc)g_memory_content_compute_size; - iface->compute_start_pos = (compute_start_pos_fc)g_memory_content_compute_start_pos; - iface->compute_end_pos = (compute_end_pos_fc)g_memory_content_compute_end_pos; + empty = g_content_attributes_new("", NULL); - iface->seek = (seek_fc)g_memory_content_seek; + g_binary_content_set_attributes(G_BIN_CONTENT(content), empty); - iface->get_raw_access = (get_raw_access_fc)g_memory_content_get_raw_access; + g_object_unref(G_OBJECT(empty)); - iface->read_raw = (read_raw_fc)g_memory_content_read_raw; - iface->read_u4 = (read_u4_fc)g_memory_content_read_u4; - iface->read_u8 = (read_u8_fc)g_memory_content_read_u8; - iface->read_u16 = (read_u16_fc)g_memory_content_read_u16; - iface->read_u32 = (read_u32_fc)g_memory_content_read_u32; - iface->read_u64 = (read_u64_fc)g_memory_content_read_u64; + content->data = NULL; + content->length = 0; + content->allocated = false; - iface->read_uleb128 = (read_uleb128_fc)g_memory_content_read_uleb128; - iface->read_leb128 = (read_leb128_fc)g_memory_content_read_leb128; + content->full_desc = strdup("In-memory content"); + content->desc = strdup("In-memory content"); } @@ -282,8 +259,11 @@ static void g_memory_content_dispose(GMemoryContent *content) static void g_memory_content_finalize(GMemoryContent *content) { - if (content->data != NULL) - free(content->data); + if (content->allocated) + { + if (content->data != NULL) + free(content->data); + } if (content->desc != NULL) free(content->desc); @@ -311,35 +291,25 @@ static void g_memory_content_finalize(GMemoryContent *content) GBinContent *g_memory_content_new(const bin_t *data, phys_t size) { - GMemoryContent *result; /* Structure à retourner */ - bin_t *allocated; /* Zone de réception */ - - allocated = malloc(size); - if (allocated == NULL) - { - LOG_ERROR_N("malloc"); - return NULL; - } - - memcpy(allocated, data, size); + GBinContent *result; /* Structure à retourner */ result = g_object_new(G_TYPE_MEMORY_CONTENT, NULL); - result->data = allocated; - result->length = size; + if (!g_memory_content_create(G_MEMORY_CONTENT(result), data, size)) + g_clear_object(&result); - return G_BIN_CONTENT(result); + return result; } /****************************************************************************** * * -* Paramètres : content = élément GLib à constuire. * -* storage = conservateur de données à manipuler ou NULL. * -* pbuf = zone tampon à lire. * +* Paramètres : content = instance à initialiser pleinement. * +* data = données du contenu volatile. * +* size = quantité de ces données. * * * -* Description : Charge un contenu depuis une mémoire tampon. * +* Description : Met en place un contenu de données brutes depuis la mémoire. * * * * Retour : Bilan de l'opération. * * * @@ -347,108 +317,37 @@ GBinContent *g_memory_content_new(const bin_t *data, phys_t size) * * ******************************************************************************/ -static bool g_memory_content_load(GMemoryContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +bool g_memory_content_create(GMemoryContent *content, const bin_t *data, phys_t size) { bool result; /* Bilan à retourner */ - uleb128_t length; /* Quantité de données à suivre*/ - rle_string str; /* Chaîne à charger */ - - result = unpack_uleb128(&length, pbuf); - - if (result) - { - content->data = malloc(length); - result = (content->data != NULL); - } - - if (result) - { - content->length = length; - result = extract_packed_buffer(pbuf, content->data, length, false); - } - - setup_empty_rle_string(&str); - - if (result) - result = unpack_rle_string(&str, pbuf); + bin_t *allocated; /* Zone de réception */ - if (result) + allocated = malloc(size); + if (allocated == NULL) { - result = (get_rle_string(&str) != NULL); - - if (result) - content->full_desc = strdup(get_rle_string(&str)); - - exit_rle_string(&str); - + LOG_ERROR_N("malloc"); + goto exit; } - if (result) - result = unpack_rle_string(&str, pbuf); + memcpy(allocated, data, size); - if (result) - { - result = (get_rle_string(&str) != NULL); + content->data = allocated; + content->length = size; + content->allocated = true; - if (result) - content->desc = strdup(get_rle_string(&str)); + result = true; - exit_rle_string(&str); - - } + exit: return result; } -/****************************************************************************** -* * -* Paramètres : content = élément GLib à consulter. * -* storage = conservateur de données à manipuler ou NULL. * -* pbuf = zone tampon à remplir. * -* * -* Description : Sauvegarde un contenu dans une mémoire tampon. * -* * -* Retour : Bilan de l'opération. * -* * -* Remarques : - * -* * -******************************************************************************/ - -static bool g_memory_content_store(const GMemoryContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) -{ - bool result; /* Bilan à retourner */ - rle_string str; /* Chaîne à conserver */ - - result = pack_uleb128((uleb128_t []){ content->length }, pbuf); - - if (result) - result = extend_packed_buffer(pbuf, content->data, content->length, false); - - if (result) - { - init_static_rle_string(&str, content->full_desc); - - result = pack_rle_string(&str, pbuf); - - exit_rle_string(&str); - - } - - if (result) - { - init_static_rle_string(&str, content->desc); - - result = pack_rle_string(&str, pbuf); - - exit_rle_string(&str); - - } - - return result; -} +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ /****************************************************************************** @@ -466,7 +365,10 @@ static bool g_memory_content_store(const GMemoryContent *content, GObjectStorage static void g_memory_content_set_attributes(GMemoryContent *content, GContentAttributes *attribs) { + g_clear_object(&content->attribs); + content->attribs = attribs; + g_object_ref(G_OBJECT(attribs)); } @@ -489,6 +391,9 @@ static GContentAttributes *g_memory_content_get_attributes(const GMemoryContent result = content->attribs; + if (result != NULL) + g_object_ref(G_OBJECT(result)); + return result; } @@ -512,6 +417,8 @@ static GBinContent *g_memory_content_get_root(GMemoryContent *content) result = G_BIN_CONTENT(content); + g_object_ref(G_OBJECT(result)); + return result; } @@ -789,15 +696,12 @@ static bool g_memory_content_read_u8(const GMemoryContent *content, vmpa2t *addr { bool result; /* Bilan de lecture à renvoyer */ phys_t pos; /* Tête de lecture courante */ - phys_t length; /* Taille de la surface dispo. */ pos = get_phy_addr(addr); if (pos == VMPA_NO_PHYSICAL) return false; - length = length; - result = read_u8(val, content->data, &pos, content->length); if (result) @@ -979,3 +883,124 @@ static bool g_memory_content_read_leb128(const GMemoryContent *content, vmpa2t * return result; } + + +/****************************************************************************** +* * +* Paramètres : content = élément GLib à constuire. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à lire. * +* * +* Description : Charge un contenu depuis une mémoire tampon. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_memory_content_load(GMemoryContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +{ + bool result; /* Bilan à retourner */ + uleb128_t length; /* Quantité de données à suivre*/ + rle_string str; /* Chaîne à charger */ + + result = unpack_uleb128(&length, pbuf); + + if (result) + { + content->data = malloc(length); + result = (content->data != NULL); + + content->allocated = true; + + } + + if (result) + { + content->length = length; + result = extract_packed_buffer(pbuf, content->data, length, false); + } + + setup_empty_rle_string(&str); + + if (result) + result = unpack_rle_string(&str, pbuf); + + if (result) + { + result = (get_rle_string(&str) != NULL); + + if (result) + content->full_desc = strdup(get_rle_string(&str)); + + exit_rle_string(&str); + + } + + if (result) + result = unpack_rle_string(&str, pbuf); + + if (result) + { + result = (get_rle_string(&str) != NULL); + + if (result) + content->desc = strdup(get_rle_string(&str)); + + exit_rle_string(&str); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : content = élément GLib à consulter. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à remplir. * +* * +* Description : Sauvegarde un contenu dans une mémoire tampon. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_memory_content_store(const GMemoryContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +{ + bool result; /* Bilan à retourner */ + rle_string str; /* Chaîne à conserver */ + + result = pack_uleb128((uleb128_t []){ content->length }, pbuf); + + if (result) + result = extend_packed_buffer(pbuf, content->data, content->length, false); + + if (result) + { + init_static_rle_string(&str, content->full_desc); + + result = pack_rle_string(&str, pbuf); + + exit_rle_string(&str); + + } + + if (result) + { + init_static_rle_string(&str, content->desc); + + result = pack_rle_string(&str, pbuf); + + exit_rle_string(&str); + + } + + return result; + +} diff --git a/src/analysis/contents/restricted-int.h b/src/analysis/contents/restricted-int.h new file mode 100644 index 0000000..ab86359 --- /dev/null +++ b/src/analysis/contents/restricted-int.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * restricted-int.h - prototypes internes pour le chargement de données binaires à partir d'un contenu restreint + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Chrysalide. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_CONTENTS_RESTRICTED_INT_H +#define _ANALYSIS_CONTENTS_RESTRICTED_INT_H + + +#include "restricted.h" + + +#include "../content-int.h" + + + +/* Contenu de données binaires issues d'un contenu restreint (instance) */ +struct _GRestrictedContent +{ + GBinContent parent; /* A laisser en premier */ + + GBinContent *internal; /* Contenu de sous-traitance */ + + mrange_t range; /* Restriction de couverture */ + +}; + +/* Contenu de données binaires issues d'un contenu restreint (classe) */ +struct _GRestrictedContentClass +{ + GBinContentClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un contenu restreint de données brutes. */ +bool g_restricted_content_create(GRestrictedContent *, GBinContent *, const mrange_t *); + + + +#endif /* _ANALYSIS_CONTENTS_RESTRICTED_INT_H */ diff --git a/src/analysis/contents/restricted.c b/src/analysis/contents/restricted.c index 3e9cbbb..9b4e1c8 100644 --- a/src/analysis/contents/restricted.c +++ b/src/analysis/contents/restricted.c @@ -28,29 +28,15 @@ #include <string.h> -#include "../content-int.h" +#include "restricted-int.h" #include "../db/misc/rlestr.h" #include "../storage/serialize-int.h" +#include "../../common/extstr.h" +#include "../../core/logs.h" -/* Contenu de données binaires issues d'un contenu restreint (instance) */ -struct _GRestrictedContent -{ - GObject parent; /* A laisser en premier */ - - GBinContent *internal; /* Contenu de sous-traitance */ - - mrange_t range; /* Restriction de couverture */ - -}; - -/* Contenu de données binaires issues d'un contenu restreint (classe) */ -struct _GRestrictedContentClass -{ - GObjectClass parent; /* A laisser en premier */ - -}; +/* -------------------------- ENSEMBLE DE DONNEES BINAIRES -------------------------- */ /* Initialise la classe des contenus de données binaires. */ @@ -59,27 +45,29 @@ static void g_restricted_content_class_init(GRestrictedContentClass *); /* Initialise une instance de contenu de données binaires. */ static void g_restricted_content_init(GRestrictedContent *); -/* Procède à l'initialisation de l'interface de sérialisation. */ -static void g_restricted_content_serializable_init(GSerializableObjectInterface *); - -/* Procède à l'initialisation de l'interface de lecture. */ -static void g_restricted_content_interface_init(GBinContentInterface *); - /* Supprime toutes les références externes. */ static void g_restricted_content_dispose(GRestrictedContent *); /* Procède à la libération totale de la mémoire. */ static void g_restricted_content_finalize(GRestrictedContent *); -/* Charge un contenu depuis une mémoire tampon. */ -static bool g_restricted_content_load(GRestrictedContent *, GObjectStorage *, packed_buffer_t *); -/* Sauvegarde un contenu dans une mémoire tampon. */ -static bool g_restricted_content_store(const GRestrictedContent *, GObjectStorage *, packed_buffer_t *); + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Associe un ensemble d'attributs au contenu binaire. */ +static void g_restricted_content_set_attributes(GRestrictedContent *, GContentAttributes *); + +/* Fournit l'ensemble des attributs associés à un contenu. */ +static GContentAttributes *g_restricted_content_get_attributes(const GRestrictedContent *); /* Donne l'origine d'un contenu binaire. */ static GBinContent *g_restricted_content_get_root(GRestrictedContent *); +/* Fournit le nom associé au contenu binaire. */ +static char *g_restricted_content_describe(const GRestrictedContent *, bool); + /* Calcule une empreinte unique (SHA256) pour les données. */ static void g_restricted_content_compute_checksum(GRestrictedContent *, GChecksum *); @@ -122,12 +110,21 @@ static bool g_restricted_content_read_uleb128(const GRestrictedContent *, vmpa2t /* Lit un nombre signé encodé au format LEB128. */ static bool g_restricted_content_read_leb128(const GRestrictedContent *, vmpa2t *, leb128_t *); +/* Charge un contenu depuis une mémoire tampon. */ +static bool g_restricted_content_load(GRestrictedContent *, GObjectStorage *, packed_buffer_t *); + +/* Sauvegarde un contenu dans une mémoire tampon. */ +static bool g_restricted_content_store(const GRestrictedContent *, GObjectStorage *, packed_buffer_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* ENSEMBLE DE DONNEES BINAIRES */ +/* ---------------------------------------------------------------------------------- */ /* Indique le type défini par la GLib pour les contenus de données. */ -G_DEFINE_TYPE_WITH_CODE(GRestrictedContent, g_restricted_content, G_TYPE_OBJECT, - G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_restricted_content_serializable_init) - G_IMPLEMENT_INTERFACE(G_TYPE_BIN_CONTENT, g_restricted_content_interface_init)); +G_DEFINE_TYPE(GRestrictedContent, g_restricted_content, G_TYPE_BIN_CONTENT); /****************************************************************************** @@ -145,12 +142,45 @@ G_DEFINE_TYPE_WITH_CODE(GRestrictedContent, g_restricted_content, G_TYPE_OBJECT, static void g_restricted_content_class_init(GRestrictedContentClass *klass) { GObjectClass *object; /* Autre version de la classe */ + GBinContentClass *content; /* Version parente de la classe*/ object = G_OBJECT_CLASS(klass); object->dispose = (GObjectFinalizeFunc/* ! */)g_restricted_content_dispose; object->finalize = (GObjectFinalizeFunc)g_restricted_content_finalize; + content = G_BIN_CONTENT_CLASS(klass); + + content->set_attribs = (set_content_attributes)g_restricted_content_set_attributes; + content->get_attribs = (get_content_attributes)g_restricted_content_get_attributes; + + content->get_root = (get_content_root_fc)g_restricted_content_get_root; + + content->describe = (describe_content_fc)g_restricted_content_describe; + + content->compute_checksum = (compute_checksum_fc)g_restricted_content_compute_checksum; + + content->compute_size = (compute_size_fc)g_restricted_content_compute_size; + content->compute_start_pos = (compute_start_pos_fc)g_restricted_content_compute_start_pos; + content->compute_end_pos = (compute_end_pos_fc)g_restricted_content_compute_end_pos; + + content->seek = (seek_fc)g_restricted_content_seek; + + content->get_raw_access = (get_raw_access_fc)g_restricted_content_get_raw_access; + + content->read_raw = (read_raw_fc)g_restricted_content_read_raw; + content->read_u4 = (read_u4_fc)g_restricted_content_read_u4; + content->read_u8 = (read_u8_fc)g_restricted_content_read_u8; + content->read_u16 = (read_u16_fc)g_restricted_content_read_u16; + content->read_u32 = (read_u32_fc)g_restricted_content_read_u32; + content->read_u64 = (read_u64_fc)g_restricted_content_read_u64; + + content->read_uleb128 = (read_uleb128_fc)g_restricted_content_read_uleb128; + content->read_leb128 = (read_leb128_fc)g_restricted_content_read_leb128; + + content->load = (load_content_cb)g_restricted_content_load; + content->store = (store_content_cb)g_restricted_content_store; + } @@ -180,9 +210,9 @@ static void g_restricted_content_init(GRestrictedContent *content) /****************************************************************************** * * -* Paramètres : iface = interface GLib à initialiser. * +* Paramètres : content = instance d'objet GLib à traiter. * * * -* Description : Procède à l'initialisation de l'interface de sérialisation. * +* Description : Supprime toutes les références externes. * * * * Retour : - * * * @@ -190,19 +220,20 @@ static void g_restricted_content_init(GRestrictedContent *content) * * ******************************************************************************/ -static void g_restricted_content_serializable_init(GSerializableObjectInterface *iface) +static void g_restricted_content_dispose(GRestrictedContent *content) { - iface->load = (load_serializable_object_cb)g_restricted_content_load; - iface->store = (store_serializable_object_cb)g_restricted_content_store; + g_clear_object(&content->internal); + + G_OBJECT_CLASS(g_restricted_content_parent_class)->dispose(G_OBJECT(content)); } /****************************************************************************** * * -* Paramètres : iface = interface GLib à initialiser. * +* Paramètres : content = instance d'objet GLib à traiter. * * * -* Description : Procède à l'initialisation de l'interface de lecture. * +* Description : Procède à la libération totale de la mémoire. * * * * Retour : - * * * @@ -210,154 +241,134 @@ static void g_restricted_content_serializable_init(GSerializableObjectInterface * * ******************************************************************************/ -static void g_restricted_content_interface_init(GBinContentInterface *iface) +static void g_restricted_content_finalize(GRestrictedContent *content) { - iface->get_root = (get_content_root_fc)g_restricted_content_get_root; - - iface->compute_checksum = (compute_checksum_fc)g_restricted_content_compute_checksum; - - iface->compute_size = (compute_size_fc)g_restricted_content_compute_size; - iface->compute_start_pos = (compute_start_pos_fc)g_restricted_content_compute_start_pos; - iface->compute_end_pos = (compute_end_pos_fc)g_restricted_content_compute_end_pos; - - iface->seek = (seek_fc)g_restricted_content_seek; - - iface->get_raw_access = (get_raw_access_fc)g_restricted_content_get_raw_access; - - iface->read_raw = (read_raw_fc)g_restricted_content_read_raw; - iface->read_u4 = (read_u4_fc)g_restricted_content_read_u4; - iface->read_u8 = (read_u8_fc)g_restricted_content_read_u8; - iface->read_u16 = (read_u16_fc)g_restricted_content_read_u16; - iface->read_u32 = (read_u32_fc)g_restricted_content_read_u32; - iface->read_u64 = (read_u64_fc)g_restricted_content_read_u64; - - iface->read_uleb128 = (read_uleb128_fc)g_restricted_content_read_uleb128; - iface->read_leb128 = (read_leb128_fc)g_restricted_content_read_leb128; + G_OBJECT_CLASS(g_restricted_content_parent_class)->finalize(G_OBJECT(content)); } /****************************************************************************** * * -* Paramètres : content = instance d'objet GLib à traiter. * +* Paramètres : internal = contenu binaire où puiser les données à fournir. * +* range = espace de restrictions pour les accès. * * * -* Description : Supprime toutes les références externes. * +* Description : Charge en mémoire le contenu d'un contenu restreint. * * * -* Retour : - * +* Retour : Représentation de contenu à manipuler ou NULL en cas d'échec.* * * * Remarques : - * * * ******************************************************************************/ -static void g_restricted_content_dispose(GRestrictedContent *content) +GBinContent *g_restricted_content_new(GBinContent *internal, const mrange_t *range) { - g_clear_object(&content->internal); + GBinContent *result; /* Structure à retourner */ - G_OBJECT_CLASS(g_restricted_content_parent_class)->dispose(G_OBJECT(content)); + result = g_object_new(G_TYPE_RESTRICTED_CONTENT, NULL); + + if (!g_restricted_content_create(G_RESTRICTED_CONTENT(result), internal, range)) + g_clear_object(&result); + + return result; } /****************************************************************************** * * -* Paramètres : content = instance d'objet GLib à traiter. * +* Paramètres : content = instance à initialiser pleinement. * +* base = contenu binaire d'où réaliser une extraction. * +* path = chemin vers le contenu finalement ciblé. * +* endpoint = contenu final rendu accessible. * * * -* Description : Procède à la libération totale de la mémoire. * +* Description : Met en place un contenu restreint de données brutes. * * * -* Retour : - * +* Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ -static void g_restricted_content_finalize(GRestrictedContent *content) +bool g_restricted_content_create(GRestrictedContent *content, GBinContent *internal, const mrange_t *range) { - G_OBJECT_CLASS(g_restricted_content_parent_class)->finalize(G_OBJECT(content)); + bool result; /* Bilan à retourner */ + + content->internal = internal; + g_object_ref(G_OBJECT(content->internal)); + + copy_mrange(&content->range, range); + + result = true; + + return result; } /****************************************************************************** * * -* Paramètres : content = contenu binaire où puiser les données à fournir. * -* range = espace de restrictions pour les accès. * +* Paramètres : content = contenu binaire à venir lire. * +* range = espace de restrictions pour les accès. [OUT] * * * -* Description : Charge en mémoire le contenu d'un contenu restreint. * +* Description : Indique l'espace de restriction appliqué à un contenu. * * * -* Retour : Représentation de contenu à manipuler ou NULL en cas d'échec.* +* Retour : - * * * * Remarques : - * * * ******************************************************************************/ -GBinContent *g_restricted_content_new(GBinContent *content, const mrange_t *range) +void g_restricted_content_get_range(const GRestrictedContent *content, mrange_t *range) { - GRestrictedContent *result; /* Structure à retourner */ - - result = g_object_new(G_TYPE_RESTRICTED_CONTENT, NULL); + copy_mrange(range, &content->range); - result->internal = content; - g_object_ref(G_OBJECT(result->internal)); +} - copy_mrange(&result->range, range); - return G_BIN_CONTENT(result); -} +/* ---------------------------------------------------------------------------------- */ +/* INTERACTIONS AVEC UN CONTENU BINAIRE */ +/* ---------------------------------------------------------------------------------- */ /****************************************************************************** * * -* Paramètres : content = contenu binaire où puiser les données à fournir. * -* range = espace de restrictions pour les accès. * +* Paramètres : content = contenu binaire à actualiser. * +* attribs = jeu d'attributs à lier au contenu courant. * * * -* Description : Charge en mémoire le contenu d'un contenu restreint. * +* Description : Associe un ensemble d'attributs au contenu binaire. * * * -* Retour : Représentation de contenu à manipuler ou NULL en cas d'échec.* +* Retour : - * * * * Remarques : - * * * ******************************************************************************/ -GBinContent *g_restricted_content_new_ro(const GBinContent *content, const mrange_t *range) +static void g_restricted_content_set_attributes(GRestrictedContent *content, GContentAttributes *attribs) { - GRestrictedContent *result; /* Structure à retourner */ - - result = g_object_new(G_TYPE_RESTRICTED_CONTENT, NULL); - - result->internal = (GBinContent *)content; - g_object_ref(G_OBJECT(result->internal)); - - copy_mrange(&result->range, range); - - return G_BIN_CONTENT(result); + g_binary_content_set_attributes(content->internal, attribs); } /****************************************************************************** * * -* Paramètres : content = élément GLib à constuire. * -* storage = conservateur de données à manipuler ou NULL. * -* pbuf = zone tampon à lire. * +* Paramètres : content = contenu binaire à consulter. * * * -* Description : Charge un contenu depuis une mémoire tampon. * +* Description : Fournit l'ensemble des attributs associés à un contenu. * * * -* Retour : Bilan de l'opération. * +* Retour : Jeu d'attributs liés au contenu courant. * * * * Remarques : - * * * ******************************************************************************/ -static bool g_restricted_content_load(GRestrictedContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +static GContentAttributes *g_restricted_content_get_attributes(const GRestrictedContent *content) { - bool result; /* Bilan à retourner */ - - content->internal = G_BIN_CONTENT(g_object_storage_unpack_object(storage, "contents", pbuf)); - result = (content->internal != NULL); + GContentAttributes *result; /* Instance à retourner */ - if (result) - result = unpack_mrange(&content->range, pbuf); + result = g_binary_content_get_attributes(content->internal); return result; @@ -366,26 +377,21 @@ static bool g_restricted_content_load(GRestrictedContent *content, GObjectStorag /****************************************************************************** * * -* Paramètres : content = élément GLib à consulter. * -* storage = conservateur de données à manipuler ou NULL. * -* pbuf = zone tampon à remplir. * +* Paramètres : content = contenu binaire à consulter. * * * -* Description : Sauvegarde un contenu dans une mémoire tampon. * +* Description : Donne l'origine d'un contenu binaire. * * * -* Retour : Bilan de l'opération. * +* Retour : Contenu à l'origine du contenu courant. * * * * Remarques : - * * * ******************************************************************************/ -static bool g_restricted_content_store(const GRestrictedContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +static GBinContent *g_restricted_content_get_root(GRestrictedContent *content) { - bool result; /* Bilan à retourner */ - - result = g_object_storage_pack_object(storage, "contents", G_SERIALIZABLE_OBJECT(content->internal), pbuf); + GBinContent *result; /* Contenu en place à renvoyer */ - if (result) - result = pack_mrange(&content->range, pbuf); + result = g_binary_content_get_root(content->internal); return result; @@ -395,20 +401,48 @@ static bool g_restricted_content_store(const GRestrictedContent *content, GObjec /****************************************************************************** * * * Paramètres : content = contenu binaire à consulter. * +* full = précise s'il s'agit d'une version longue ou non. * * * -* Description : Donne l'origine d'un contenu binaire. * +* Description : Fournit le nom associé au contenu binaire. * * * -* Retour : Contenu à l'origine du contenu courant. * +* Retour : Nom de fichier avec chemin absolu au besoin. * * * * Remarques : - * * * ******************************************************************************/ -static GBinContent *g_restricted_content_get_root(GRestrictedContent *content) +static char *g_restricted_content_describe(const GRestrictedContent *content, bool full) { - GBinContent *result; /* Contenu en place à renvoyer */ + char *result; /* Description à retourner */ + VMPA_BUFFER(start_str); /* Zone de départ en texte */ + vmpa2t end; /* Position de fin */ + VMPA_BUFFER(end_str); /* Zone de départ en texte */ + char *suffix; /* Construction d'un appendice */ + int ret; /* Bilan de construction */ - result = g_binary_content_get_root(content->internal); + result = g_binary_content_describe(content->internal, full); + + vmpa2_to_string(get_mrange_addr(&content->range), MDS_UNDEFINED, start_str, NULL); + + compute_mrange_end_addr(&content->range, &end); + + vmpa2_to_string(&end, MDS_UNDEFINED, end_str, NULL); + + ret = asprintf(&suffix, "[%s:%s]", start_str, end_str); + + if (ret == -1) + LOG_ERROR_N("asprintf"); + + else + { + if (result != NULL) + result = stradd(result, " "); + + result = stradd(result, suffix); + + free(suffix); + + } return result; @@ -932,19 +966,56 @@ static bool g_restricted_content_read_leb128(const GRestrictedContent *content, /****************************************************************************** * * -* Paramètres : content = contenu binaire à venir lire. * -* range = espace de restrictions pour les accès. [OUT] * +* Paramètres : content = élément GLib à constuire. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à lire. * * * -* Description : Indique l'espace de restriction appliqué à un contenu. * +* Description : Charge un contenu depuis une mémoire tampon. * * * -* Retour : - * +* Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ -void g_restricted_content_get_range(const GRestrictedContent *content, mrange_t *range) +static bool g_restricted_content_load(GRestrictedContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) { - copy_mrange(range, &content->range); + bool result; /* Bilan à retourner */ + + content->internal = G_BIN_CONTENT(g_object_storage_unpack_object(storage, "contents", pbuf)); + result = (content->internal != NULL); + + if (result) + result = unpack_mrange(&content->range, pbuf); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : content = élément GLib à consulter. * +* storage = conservateur de données à manipuler ou NULL. * +* pbuf = zone tampon à remplir. * +* * +* Description : Sauvegarde un contenu dans une mémoire tampon. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_restricted_content_store(const GRestrictedContent *content, GObjectStorage *storage, packed_buffer_t *pbuf) +{ + bool result; /* Bilan à retourner */ + + result = g_object_storage_pack_object(storage, "contents", G_SERIALIZABLE_OBJECT(content->internal), pbuf); + + if (result) + result = pack_mrange(&content->range, pbuf); + + return result; } diff --git a/src/analysis/contents/restricted.h b/src/analysis/contents/restricted.h index 402282a..1cea390 100644 --- a/src/analysis/contents/restricted.h +++ b/src/analysis/contents/restricted.h @@ -53,9 +53,6 @@ GType g_restricted_content_get_type(void); /* Charge en mémoire le contenu d'un contenu restreint. */ GBinContent *g_restricted_content_new(GBinContent *, const mrange_t *); -/* Charge en mémoire le contenu d'un contenu restreint. */ -GBinContent *g_restricted_content_new_ro(const GBinContent *, const mrange_t *); - /* Indique l'espace de restriction appliqué à un contenu. */ void g_restricted_content_get_range(const GRestrictedContent *, mrange_t *); diff --git a/src/analysis/db/Makefile.am b/src/analysis/db/Makefile.am index 8f8242c..b9325e0 100644 --- a/src/analysis/db/Makefile.am +++ b/src/analysis/db/Makefile.am @@ -21,20 +21,16 @@ libanalysisdb_la_SOURCES = \ server.h server.c \ snapshot.h snapshot.c +libanalysisdb_la_CFLAGS = $(TOOLKIT_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) $(LIBSSL_CFLAGS) + libanalysisdb_la_LIBADD = \ items/libanalysisdbitems.la \ misc/libanalysisdbmisc.la -libanalysisdb_la_LDFLAGS = $(LIBSSL_LIBS) - devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysisdb_la_SOURCES:%c=) -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) $(LIBSSL_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - SUBDIRS = items misc diff --git a/src/analysis/db/analyst-int.h b/src/analysis/db/analyst-int.h new file mode 100644 index 0000000..4f76eff --- /dev/null +++ b/src/analysis/db/analyst-int.h @@ -0,0 +1,76 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * analyst-int.h - prototypes pour la définition interne des connexions en analyste à un serveur Chrysalide + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Chrysalide. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_DB_ANALYST_INT_H +#define _ANALYSIS_DB_ANALYST_INT_H + + +#include "analyst.h" +#include "client-int.h" + + + +/* Description de client à l'écoute (instance) */ +struct _GAnalystClient +{ + GHubClient parent; /* A laisser en premier */ + + char *cnt_hash; /* Empreinte du binaire lié */ + char *cnt_class; /* Interprétation du contenu */ + + GLoadedContent *loaded; /* Contenu chargé */ + GList *collections; /* Collections d'un binaire */ + + bool can_get_updates; /* Réception de maj possibles ?*/ + + snapshot_info_t *snapshots; /* Liste des instantanés */ + size_t snap_count; /* Taille de cette liste */ + GMutex snap_lock; /* Concurrence des accès */ + + snapshot_id_t current; /* Instantané courant */ + bool has_current; /* Validité de l'identifiant */ + GMutex cur_lock; /* Concurrence des accès */ + +}; + +/* Description de client à l'écoute (classe) */ +struct _GAnalystClientClass +{ + GHubClientClass parent; /* A laisser en premier */ + + /* Signaux */ + + void (* ready) (GAnalystClient *); + void (* server_status_changed) (GAnalystClient *, LoadingStatusHint); + void (* snapshots_updated) (GAnalystClient *); + void (* snapshot_changed) (GAnalystClient *); + +}; + + +/* Prépare un client pour une connexion à une BD. */ +bool g_analyst_client_setup(GAnalystClient *, const char *, const char *, GList *, GLoadedContent *); + + + +#endif /* _ANALYSIS_DB_ANALYST_INT_H */ diff --git a/src/analysis/db/analyst.c b/src/analysis/db/analyst.c index 49585c2..43fb840 100644 --- a/src/analysis/db/analyst.c +++ b/src/analysis/db/analyst.c @@ -29,43 +29,13 @@ #include <string.h> -#include "client-int.h" +#include "analyst-int.h" #include "../storage/storage.h" #include "../../core/logs.h" -/* Description de client à l'écoute (instance) */ -struct _GAnalystClient -{ - GHubClient parent; /* A laisser en premier */ - - char *hash; /* Empreinte du binaire lié */ - GList *collections; /* Collections d'un binaire */ - - bool can_get_updates; /* Réception de maj possibles ?*/ - - snapshot_info_t *snapshots; /* Liste des instantanés */ - size_t snap_count; /* Taille de cette liste */ - GMutex snap_lock; /* Concurrence des accès */ - - snapshot_id_t current; /* Instantané courant */ - bool has_current; /* Validité de l'identifiant */ - GMutex cur_lock; /* Concurrence des accès */ - -}; - -/* Description de client à l'écoute (classe) */ -struct _GAnalystClientClass -{ - GHubClientClass parent; /* A laisser en premier */ - - /* Signaux */ - - void (* snapshots_updated) (GAnalystClient *); - void (* snapshot_changed) (GAnalystClient *); - -}; +/* ----------------------- DEFINITION D'ANALYSTE COMME CLIENT ----------------------- */ /* Initialise la classe des descriptions de fichier binaire. */ @@ -94,6 +64,58 @@ static bool g_analyst_client_update_current_snapshot(GAnalystClient *, packed_bu +/* ------------------------- PRISES EN COMPTE DES COMMANDES ------------------------- */ + + +/* Prend en compte une évolution du statut côté serveur. */ +static bool g_analyst_client_handle_loading_hints(GAnalystClient *, packed_buffer_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* GLUES POUR LA GLIB */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Définit un type GLib pour l'énumération "LoadingStatusHint". * +* * +* Retour : Type GLib enregistré. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GType g_loading_status_hint_type(void) +{ + static GType result = 0; + + static const GEnumValue values[] = { + { LSH_READY, "LSH_READY", "ready" }, + { LSH_ON_WAIT_LIST, "LSH_ON_WAIT_LIST", "on_wait_list" }, + { LSH_NEED_CONTENT, "LSH_NEED_CONTENT", "need_content" }, + { LSH_NEED_FORMAT, "LSH_NEED_FORMAT", "need_format" }, + { LSH_NEED_ARCH, "LSH_NEED_ARCH", "need_arch" }, + { 0, NULL, NULL } + }; + + if (result == 0) + result = g_enum_register_static(g_intern_static_string("LoadingStatusHint"), values); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* DEFINITION D'ANALYSTE COMME CLIENT */ +/* ---------------------------------------------------------------------------------- */ + + /* Indique le type défini pour une description de client à l'écoute. */ G_DEFINE_TYPE(GAnalystClient, g_analyst_client, G_TYPE_HUB_CLIENT); @@ -126,6 +148,22 @@ static void g_analyst_client_class_init(GAnalystClientClass *klass) client->complete_hello = (complete_client_hello_fc)g_analyst_client_complete_hello; client->recv_func = (GThreadFunc)g_analyst_client_update; + g_signal_new("ready", + G_TYPE_ANALYST_CLIENT, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(GAnalystClientClass, ready), + NULL, NULL, + g_cclosure_marshal_VOID__VOID, + G_TYPE_NONE, 0); + + g_signal_new("server-status-changed", + G_TYPE_ANALYST_CLIENT, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(GAnalystClientClass, server_status_changed), + NULL, NULL, + g_cclosure_marshal_VOID__ENUM, + G_TYPE_NONE, 1, G_TYPE_LOADING_STATUS_HINT); + g_signal_new("snapshots-updated", G_TYPE_ANALYST_CLIENT, G_SIGNAL_RUN_LAST, @@ -159,7 +197,10 @@ static void g_analyst_client_class_init(GAnalystClientClass *klass) static void g_analyst_client_init(GAnalystClient *client) { - client->hash = NULL; + client->cnt_hash = NULL; + client->cnt_class = NULL; + + client->loaded = NULL; client->collections = NULL; client->can_get_updates = false; @@ -195,6 +236,8 @@ static void g_analyst_client_dispose(GAnalystClient *client) g_mutex_clear(&client->snap_lock); + g_clear_object(&client->loaded); + G_OBJECT_CLASS(g_analyst_client_parent_class)->dispose(G_OBJECT(client)); } @@ -216,8 +259,11 @@ static void g_analyst_client_finalize(GAnalystClient *client) { size_t i; /* Boucle de parcours */ - if (client->hash != NULL) - free(client->hash); + if (client->cnt_hash != NULL) + free(client->cnt_hash); + + if (client->cnt_class != NULL) + free(client->cnt_class); if (client->snapshots != NULL) { @@ -236,9 +282,11 @@ static void g_analyst_client_finalize(GAnalystClient *client) /****************************************************************************** * * * Paramètres : hash = empreinte d'un binaire en cours d'analyse. * +* class = nature de l'interprétation de ce contenu. * * collections = ensemble de collections existantes. * +* loaded = éventuel élément local préchargé. * * * -* Description : Prépare un client pour une connexion à une BD. * +* Description : Met en place un client pour une connexion à une BD. * * * * Retour : Structure mise en place ou NULL en cas d'échec. * * * @@ -246,14 +294,54 @@ static void g_analyst_client_finalize(GAnalystClient *client) * * ******************************************************************************/ -GAnalystClient *g_analyst_client_new(const char *hash, GList *collections) +GAnalystClient *g_analyst_client_new(const char *hash, const char *class, GList *collections, GLoadedContent *loaded) { GAnalystClient *result; /* Adresse à retourner */ + bool status; /* Bilan de l'initialisation */ result = g_object_new(G_TYPE_ANALYST_CLIENT, NULL); - result->hash = strdup(hash); - result->collections = collections; + status = g_analyst_client_setup(result, hash, class, collections, loaded); + + assert(status); + + if (!status) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : client = client pour les accès distants à initialiser. * +* hash = empreinte d'un binaire en cours d'analyse. * +* class = nature de l'interprétation de ce contenu. * +* collections = ensemble de collections existantes. * +* loaded = éventuel élément local préchargé. * +* * +* Description : Prépare un client pour une connexion à une BD. * +* * +* Retour : Structure mise en place ou NULL en cas d'échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_analyst_client_setup(GAnalystClient *client, const char *hash, const char *class, GList *collections, GLoadedContent *loaded) +{ + bool result; /* Bilan à retourner */ + + result = true; + + client->cnt_hash = strdup(hash); + client->cnt_class = strdup(class); + + client->loaded = loaded; + if (loaded != NULL) g_object_ref(G_OBJECT(loaded)); + + client->collections = collections; return result; @@ -278,7 +366,13 @@ static bool g_analyst_client_complete_hello(GAnalystClient *client, packed_buffe bool result; /* Bilan à retourner */ rle_string str; /* Chaîne à communiquer */ - init_static_rle_string(&str, client->hash); + init_static_rle_string(&str, client->cnt_hash); + + result = pack_rle_string(&str, pbuf); + + exit_rle_string(&str); + + init_static_rle_string(&str, client->cnt_class); result = pack_rle_string(&str, pbuf); @@ -406,6 +500,11 @@ static void *g_analyst_client_update(GAnalystClient *client) switch (command) { + case DBC_LOADING_STATUS: + status = g_analyst_client_handle_loading_hints(client, &in_pbuf); + if (!status) goto gdcu_bad_exchange; + break; + case DBC_SAVE: status = extract_packed_buffer(&in_pbuf, &tmp32, sizeof(uint32_t), true); @@ -414,10 +513,10 @@ static void *g_analyst_client_update(GAnalystClient *client) error = tmp32; if (error == DBE_NONE) - log_variadic_message(LMT_INFO, _("Archive saved for binary '%s'"), client->hash); + log_variadic_message(LMT_INFO, _("Archive saved for binary '%s'"), client->cnt_hash); else log_variadic_message(LMT_ERROR, _("Failed to save the archive for binary '%s'"), - client->hash); + client->cnt_hash); break; @@ -669,10 +768,10 @@ bool g_analyst_client_send_content(GAnalystClient *client, GBinContent *content) hash = g_binary_content_get_checksum(content); - if (strcmp(hash, client->hash) != 0) + if (strcmp(hash, client->cnt_hash) != 0) { log_variadic_message(LMT_ERROR, _("Provided ontent does not match client content (hash: '%s')"), - client->hash); + client->cnt_hash); goto exit; } @@ -680,7 +779,7 @@ bool g_analyst_client_send_content(GAnalystClient *client, GBinContent *content) init_packed_buffer(&cnt_pbuf); - storage = g_object_storage_new(client->hash); + storage = g_object_storage_new(client->cnt_hash); result = g_object_storage_store_object(storage, "contents", G_SERIALIZABLE_OBJECT(content), &pos); if (!result) goto exit_with_failure; @@ -1261,3 +1360,59 @@ bool g_analyst_client_remove_snapshot(GAnalystClient *client, const snapshot_id_ return result; } + + + +/* ---------------------------------------------------------------------------------- */ +/* PRISES EN COMPTE DES COMMANDES */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : archive = archive à connecter avec un utilisateur. * +* in_pbuf = paquet à consulter. * +* * +* Description : Prend en compte une évolution du statut côté serveur. * +* * +* Retour : Indication pour le maintien de la communication. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_analyst_client_handle_loading_hints(GAnalystClient *client, packed_buffer_t *in_pbuf) +{ + bool result; /* Bilan à retourner */ + uleb128_t hint; /* Indication du serveur */ + + result = unpack_uleb128(&hint, in_pbuf); + + switch (hint) + { + case LSH_READY: + g_signal_emit_by_name(client, "ready"); + break; + + case LSH_ON_WAIT_LIST: + log_simple_message(LMT_INFO, _("Waiting for content from server...")); + break; + + case LSH_NEED_CONTENT: + case LSH_NEED_FORMAT: + case LSH_NEED_ARCH: + g_signal_emit_by_name(client, "server-status-changed", hint); + break; + + default: + log_variadic_message(LMT_ERROR, + _("Unknown loaded hint received (%x); unsupported newer protocol?"), + hint); + result = false; + break; + + } + + return result; + +} diff --git a/src/analysis/db/analyst.h b/src/analysis/db/analyst.h index 7b11f53..ff189ba 100644 --- a/src/analysis/db/analyst.h +++ b/src/analysis/db/analyst.h @@ -34,9 +34,25 @@ #include "collection.h" #include "misc/snapshot.h" #include "../content.h" +#include "../loaded.h" + +/* ------------------------------- GLUES POUR LA GLIB ------------------------------- */ + + +#define G_TYPE_LOADING_STATUS_HINT g_loading_status_hint_type() + + +/* Définit un type GLib pour l'énumération "LoadingStatusHint". */ +GType g_loading_status_hint_type(void); + + + +/* ----------------------- DEFINITION D'ANALYSTE COMME CLIENT ----------------------- */ + + #define G_TYPE_ANALYST_CLIENT g_analyst_client_get_type() #define G_ANALYST_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_ANALYST_CLIENT, GAnalystClient)) #define G_IS_ANALYST_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_ANALYST_CLIENT)) @@ -55,8 +71,8 @@ typedef struct _GAnalystClientClass GAnalystClientClass; /* Indique le type défini pour une description de client à l'écoute. */ GType g_analyst_client_get_type(void); -/* Prépare un client pour une connexion à une BD. */ -GAnalystClient *g_analyst_client_new(const char *, GList *); +/* Met en place un client pour une connexion à une BD. */ +GAnalystClient *g_analyst_client_new(const char *, const char *, GList *, GLoadedContent *); /* Envoie un contenu binaire pour conservation côté serveur. */ bool g_analyst_client_send_content(GAnalystClient *, GBinContent *); diff --git a/src/analysis/db/cdb.c b/src/analysis/db/cdb.c index 62de6a7..6d4b84d 100644 --- a/src/analysis/db/cdb.c +++ b/src/analysis/db/cdb.c @@ -38,8 +38,8 @@ #include <sys/stat.h> -#include <i18n.h> #include <config.h> +#include <i18n.h> #include "backend-int.h" @@ -59,7 +59,7 @@ -/* ------------------------- COEUR DE LA GESTION D'ARCHIVES ------------------------- */ +/* -------------------------- LIEN VERS UN CLIENT CONNECTE -------------------------- */ /* Informations relatives à un client */ @@ -69,29 +69,51 @@ typedef struct _cdb_client char *peer_name; /* Désignation du correspondant*/ char *user; /* Utilisateur à l'autre bout */ - uint64_t last_time; /* Date de dernier envoi */ + gint ref_count; /* Décompte d'utilisation */ } cdb_client; +/* Met en place le suivi d'une connexion de client. */ +static cdb_client *create_cdb_client(SSL *, const char *, const char *); + +/* Supprime le suivi d'une connexion de client. */ +static void delete_cdb_client(cdb_client *); + +/* Augmente le décompte d'utilisation d'un suivi de connexion. */ +static void ref_cdb_client(cdb_client *); + +/* Diminue le décompte d'utilisation d'un suivi de connexion. */ +static void unref_cdb_client(cdb_client *); + + + +/* ------------------------- COEUR DE LA GESTION D'ARCHIVES ------------------------- */ + + /* Description d'une archive d'éléments utilisateur (instance) */ struct _GCdbArchive { GServerBackend parent; /* A laisser en premier */ rle_string hash; /* Empreinte cryptographique */ + rle_string class; /* Nature du contenu analysé */ char *filename; /* Chemin d'accès à l'archive */ char *tmpdir; /* Répertoire de travail */ - char *cnt_file; /* Fichier de contenu binaire */ char *xml_desc; /* Fichier de description */ + char *cnt_file; /* Fichier de contenu binaire */ + + GMutex loading_access; /* Verrou pour l'accès */ + + GList *collections; /* Ensemble de modifications */ GDbSnapshot *snapshot; /* Instantanés de bases SQL */ sqlite3 *db; /* Base de données à manipuler */ - cdb_client *clients; /* Connexions en place */ + cdb_client **clients; /* Connexions en place */ size_t count; /* Quantité de clients */ GMutex clients_access; /* Verrou pour l'accès */ @@ -171,14 +193,115 @@ static bool g_cdb_archive_send_snapshot_change(GCdbArchive *, packed_buffer_t *) /* ------------------------- PRISES EN COMPTE DES COMMANDES ------------------------- */ -/* Prépare la réponse à envoyer à un client connecté. */ -static bool setup_server_answer(DBCommand, DBError, packed_buffer_t *); +/* Prépare une courte réponse à envoyer à un client connecté. */ +static bool craft_server_short_answer(DBCommand, uleb128_t, packed_buffer_t *); /* Enregistre le contenu binaire lié à une analyse. */ static bool g_cdb_archive_set_content(GCdbArchive *, packed_buffer_t *, packed_buffer_t *); +/* -------------------------- LIEN VERS UN CLIENT CONNECTE -------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : fd = canal de communication réseau ouvert. * +* peer_name = désignation de la connexion. * +* user = désignation de l'utilisateur de la connexion. * +* * +* Description : Met en place le suivi d'une connexion de client. * +* * +* Retour : Structure dédiée construite. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static cdb_client *create_cdb_client(SSL *fd, const char *peer_name, const char *user) +{ + cdb_client *result; /* Fiche d'entité à retourner */ + + result = malloc(sizeof(cdb_client)); + + result->tls_fd = fd; + + result->peer_name = strdup(peer_name); + result->user = strdup(user); + + g_atomic_int_set(&result->ref_count, 1); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : client = informations de suivi à libérer de la mémoire. * +* * +* Description : Supprime le suivi d'une connexion de client. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void delete_cdb_client(cdb_client *client) +{ + assert(g_atomic_int_get(&client->ref_count) == 0); + + SSL_free(client->tls_fd); + + free(client->peer_name); + free(client->user); + + free(client); + +} + + +/****************************************************************************** +* * +* Paramètres : client = informations de suivi à libérer de la mémoire. * +* * +* Description : Augmente le décompte d'utilisation d'un suivi de connexion. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void ref_cdb_client(cdb_client *client) +{ + g_atomic_int_inc(&client->ref_count); + +} + + +/****************************************************************************** +* * +* Paramètres : client = informations de suivi à libérer de la mémoire. * +* * +* Description : Diminue le décompte d'utilisation d'un suivi de connexion. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void unref_cdb_client(cdb_client *client) +{ + if (g_atomic_int_dec_and_test(&client->ref_count)) + delete_cdb_client(client); + +} + + + /* ---------------------------------------------------------------------------------- */ /* COEUR DE LA GESTION D'ARCHIVES */ /* ---------------------------------------------------------------------------------- */ @@ -235,15 +358,19 @@ static void g_cdb_archive_class_init(GCdbArchiveClass *klass) static void g_cdb_archive_init(GCdbArchive *archive) { setup_empty_rle_string(&archive->hash); + setup_empty_rle_string(&archive->class); archive->filename = NULL; archive->tmpdir = NULL; - archive->cnt_file = NULL; archive->xml_desc = NULL; + archive->cnt_file = NULL; + g_mutex_init(&archive->loading_access); + archive->collections = create_collections_list(); archive->snapshot = NULL; + archive->db = NULL; g_mutex_init(&archive->clients_access); @@ -266,9 +393,11 @@ static void g_cdb_archive_dispose(GCdbArchive *archive) { g_server_backend_stop(G_SERVER_BACKEND(archive)); + g_mutex_clear(&archive->clients_access); + g_clear_object(&archive->snapshot); - g_mutex_clear(&archive->clients_access); + g_mutex_clear(&archive->loading_access); G_OBJECT_CLASS(g_cdb_archive_parent_class)->dispose(G_OBJECT(archive)); @@ -315,6 +444,7 @@ static void g_cdb_archive_finalize(GCdbArchive *archive) if (archive->filename != NULL) free(archive->filename); + exit_rle_string(&archive->class); exit_rle_string(&archive->hash); G_OBJECT_CLASS(g_cdb_archive_parent_class)->finalize(G_OBJECT(archive)); @@ -327,6 +457,7 @@ static void g_cdb_archive_finalize(GCdbArchive *archive) * Paramètres : basedir = répertoire de stockage des enregistrements. * * tmpdir = répertoire de travail temporaire. * * hash = empreinte du binaire à représenter. * +* class = nature du contenu analysé associé. * * error = indication éventuelle en cas d'échec. [OUT] * * * * Description : Définit ou ouvre une archive d'éléments utilisateur. * @@ -338,7 +469,7 @@ static void g_cdb_archive_finalize(GCdbArchive *archive) * * ******************************************************************************/ -GCdbArchive *g_cdb_archive_new(const char *basedir, const char *tmpdir, const rle_string *hash, DBError *error) +GCdbArchive *g_cdb_archive_new(const char *basedir, const char *tmpdir, const rle_string *hash, const rle_string *class, DBError *error) { GCdbArchive *result; /* Adresse à retourner */ int ret; /* Retour d'un appel */ @@ -347,13 +478,16 @@ GCdbArchive *g_cdb_archive_new(const char *basedir, const char *tmpdir, const rl result = g_object_new(G_TYPE_CDB_ARCHIVE, NULL); dup_into_rle_string(&result->hash, get_rle_string(hash)); + dup_into_rle_string(&result->class, get_rle_string(class)); *error = DBE_SYS_ERROR; /* Chemin de l'archive */ result->filename = strdup(basedir); - result->filename = stradd(result->filename, hash->data); + result->filename = stradd(result->filename, get_rle_string(hash)); + result->filename = stradd(result->filename, "-"); + result->filename = stradd(result->filename, get_rle_string(class)); result->filename = stradd(result->filename, ".cdb.tar.xz"); if (!mkpath(result->filename)) @@ -679,18 +813,26 @@ DBError g_cdb_archive_write(const GCdbArchive *archive) * * * Paramètres : archive = informations quant à l'archive à consulter. * * hash = empreinte extérieure à comparer. * +* class = nature du contenu analysé. * * * -* Description : Détermine si une empreinte correspond à celle d'une archive. * +* Description : Détermine l'archive correspond à une cible recherchée. * * * -* Retour : Résultat de la comparaison : -1, 0 ou 1. * +* Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ -int g_cdb_archive_compare_hash(const GCdbArchive *archive, const rle_string *hash) +bool g_cdb_archive_compare_is_suitable_for(const GCdbArchive *archive, const rle_string *hash, const rle_string *class) { - return cmp_rle_string(&archive->hash, hash); + bool result; /* Bilan à retourner */ + + result = (cmp_rle_string(&archive->hash, hash) == 0); + + if (result) + result = (cmp_rle_string(&archive->class, class) == 0); + + return result; } @@ -867,7 +1009,7 @@ static void on_collection_extended(GDbCollection *collec, GDbItem *item, GCdbArc for (i = 0; i < archive->count && status; i++) { - status = ssl_send_packed_buffer(&pbuf, archive->clients[i].tls_fd); + status = ssl_send_packed_buffer(&pbuf, archive->clients[i]->tls_fd); if (!status) LOG_ERROR(LMT_ERROR, _("Failed to send some DB update")); @@ -896,6 +1038,8 @@ static void on_collection_extended(GDbCollection *collec, GDbItem *item, GCdbArc static void *g_cdb_archive_process(GCdbArchive *archive) { GServerBackend *base; /* Base de l'instance */ + cdb_client **clients; /* Clients surveillés */ + size_t last_count; /* Quantité de ces clients */ struct pollfd *fds; /* Surveillance des flux */ nfds_t nfds; /* Quantité de ces flux */ nfds_t i; /* Boucle de parcours */ @@ -912,20 +1056,38 @@ static void *g_cdb_archive_process(GCdbArchive *archive) base = G_SERVER_BACKEND(archive); + clients = NULL; + last_count = 0; + fds = NULL; while (1) { + /* Réinitialisation ? */ + + for (i = 0; i < last_count; i++) + unref_cdb_client(clients[i]); + /* Reconstitution d'une liste à jour */ g_mutex_lock(&archive->clients_access); - nfds = archive->count + 2; + last_count = archive->count; + + clients = realloc(clients, last_count * sizeof(cdb_client)); + + for (i = 0; i < last_count; i++) + { + clients[i] = archive->clients[i]; + ref_cdb_client(clients[i]); + } + + nfds = last_count + 2; fds = realloc(fds, nfds * sizeof(struct pollfd)); for (i = 0; i < (nfds - 2); i++) { - fds[i].fd = SSL_get_fd(archive->clients[i].tls_fd); + fds[i].fd = SSL_get_fd(clients[i]->tls_fd); fds[i].events = POLLIN | POLLPRI; } @@ -978,7 +1140,7 @@ static void *g_cdb_archive_process(GCdbArchive *archive) { init_packed_buffer(&in_pbuf); - status = ssl_recv_packed_buffer(&in_pbuf, archive->clients[i].tls_fd); + status = ssl_recv_packed_buffer(&in_pbuf, clients[i]->tls_fd); if (!status) goto gcap_bad_exchange; next_command: @@ -988,17 +1150,12 @@ static void *g_cdb_archive_process(GCdbArchive *archive) command = tmp32; + init_packed_buffer(&out_pbuf); + switch (command) { case DBC_SET_CONTENT: - status = g_cdb_archive_set_content(archive, &in_pbuf, &out_pbuf); - if (!status) goto gcap_bad_reply; - - status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].tls_fd); - if (!status) goto gcap_bad_reply; - - exit_packed_buffer(&out_pbuf); break; @@ -1007,7 +1164,7 @@ static void *g_cdb_archive_process(GCdbArchive *archive) error = g_cdb_archive_write(archive); - init_packed_buffer(&out_pbuf); + //init_packed_buffer(&out_pbuf); status = extend_packed_buffer(&out_pbuf, (uint32_t []) { DBC_SAVE }, sizeof(uint32_t), true); @@ -1016,7 +1173,7 @@ static void *g_cdb_archive_process(GCdbArchive *archive) status = extend_packed_buffer(&out_pbuf, (uint32_t []) { error }, sizeof(uint32_t), true); if (!status) goto gcap_bad_reply; - status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].tls_fd); + status = ssl_send_packed_buffer(&out_pbuf, clients[i]->tls_fd); if (!status) goto gcap_bad_reply; exit_packed_buffer(&out_pbuf); @@ -1057,10 +1214,10 @@ static void *g_cdb_archive_process(GCdbArchive *archive) status = extend_packed_buffer(&out_pbuf, (uint8_t []) { 0x0 }, sizeof(uint8_t), true); if (!status) goto gcap_bad_reply; - status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].tls_fd); - if (!status) goto gcap_bad_reply; + //status = ssl_send_packed_buffer(&out_pbuf, clients[i]->tls_fd); + //if (!status) goto gcap_bad_reply; - exit_packed_buffer(&out_pbuf); + //exit_packed_buffer(&out_pbuf); break; @@ -1079,7 +1236,7 @@ static void *g_cdb_archive_process(GCdbArchive *archive) &in_pbuf, &out_pbuf, archive->db); if (!status) goto gcap_bad_reply; - status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].tls_fd); + status = ssl_send_packed_buffer(&out_pbuf, clients[i]->tls_fd); if (!status) goto gcap_bad_reply; exit_packed_buffer(&out_pbuf); @@ -1091,10 +1248,12 @@ static void *g_cdb_archive_process(GCdbArchive *archive) if (!g_cdb_archive_send_snapshot_update(archive, &out_pbuf)) goto critical_error; - status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].tls_fd); - if (!status) goto gcap_bad_reply; + status = true; - exit_packed_buffer(&out_pbuf); + //status = ssl_send_packed_buffer(&out_pbuf, clients[i]->tls_fd); + //if (!status) goto gcap_bad_reply; + + //exit_packed_buffer(&out_pbuf); break; @@ -1103,10 +1262,10 @@ static void *g_cdb_archive_process(GCdbArchive *archive) if (!g_cdb_archive_send_snapshot_change(archive, &out_pbuf)) goto critical_error; - status = ssl_send_packed_buffer(&out_pbuf, archive->clients[i].tls_fd); - if (!status) goto gcap_bad_reply; + //status = ssl_send_packed_buffer(&out_pbuf, clients[i]->tls_fd); + //if (!status) goto gcap_bad_reply; - exit_packed_buffer(&out_pbuf); + //exit_packed_buffer(&out_pbuf); break; @@ -1225,6 +1384,17 @@ static void *g_cdb_archive_process(GCdbArchive *archive) } + if (!status) + goto gcap_bad_reply; + + if (get_packed_buffer_payload_length(&out_pbuf) > 0) + { + status = ssl_send_packed_buffer(&out_pbuf, clients[i]->tls_fd); + if (!status) goto gcap_bad_reply; + } + + exit_packed_buffer(&out_pbuf); + if (has_more_data_in_packed_buffer(&in_pbuf)) goto next_command; @@ -1268,6 +1438,12 @@ static void *g_cdb_archive_process(GCdbArchive *archive) g_server_backend_stop(G_SERVER_BACKEND(archive)); + for (i = 0; i < last_count; i++) + unref_cdb_client(clients[i]); + + if (clients != NULL) + free(clients); + if (fds != NULL) free(fds); @@ -1291,40 +1467,100 @@ static void *g_cdb_archive_process(GCdbArchive *archive) * * ******************************************************************************/ +static LoadingStatusHint g_cdb_archive_compute_loading_hint(GCdbArchive *archive) +{ + LoadingStatusHint result; /* Statut à retourner */ + + + // Try + // g_mutex_lock(&archive->loading_access); + + + + // cnt_file + + if (archive->cnt_file == NULL) + result = LSH_NEED_CONTENT; + + else + result = LSH_NEED_FORMAT; + + + + + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : archive = support pour le suivi d'une connexion. * +* fd = canal de communication réseau ouvert. * +* peer_name = désignation de la connexion. * +* user = désignation de l'utilisateur de la connexion. * +* * +* Description : Prend en compte une connexion nouvelle d'un utilisateur. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + static void g_cdb_archive_add_client(GCdbArchive *archive, SSL *fd, const char *peer_name, const char *user) { cdb_client *client; /* Nouvelle fiche d'entité */ + packed_buffer_t out_pbuf; /* Tampon d'émission */ + LoadingStatusHint hint; /* Statut de chargement */ + bool status; /* Bilan de lecture initiale */ + + client = create_cdb_client(fd, peer_name, user); /** - * La situation est un peu compliquée lors de l'accueil d'un nouveau client : - * - * - soit on envoie tous les éléments à prendre en compte, mais on doit - * bloquer la base de données jusqu'à l'intégration pleine et entière - * du client, afin que ce dernier ne loupe pas l'envoi d'un nouvel - * élément entre temps. + * Le verrou encadrant les évolutions des contenus initiaux doit englober + * l'extension de la liste des clients. * - * - soit on intègre le client et celui ci demande des mises à jour - * collection par collection ; c'est également à lui que revient le rejet - * des éléments envoyés en solitaires avant la réception de la base - * complète. + * En effet, une évolution partielle peut intervenir dans la fonction + * g_cdb_archive_process(), à un moment au seul le verrou dans les + * évolutions sera posé (g_cdb_archive_set_content() par exemple). * - * On fait le choix du second scenario ici, du fait de la difficulté - * de maîtriser facilement la reconstitution d'une liste de clients dans - * g_cdb_archive_process() depuis un autre flot d'exécution. + * Or g_cdb_archive_compute_loading_hint() doit fournir ici un état qui ne + * varie pas entre le calcul et l'envoi. Donc verrous sur les clients et + * l'état de l'archive doivent englover l'ensemble des traitements ci-après. */ + g_mutex_lock(&archive->loading_access); + g_mutex_lock(&archive->clients_access); - archive->clients = realloc(archive->clients, ++archive->count * sizeof(cdb_client)); + hint = g_cdb_archive_compute_loading_hint(archive); + + if (hint != LSH_READY) + hint = (archive->count == 0 ? hint : LSH_ON_WAIT_LIST); + + init_packed_buffer(&out_pbuf); + + status = craft_server_short_answer(DBC_LOADING_STATUS, hint, &out_pbuf); + + if (status) + status = ssl_send_packed_buffer(&out_pbuf, fd); + + exit_packed_buffer(&out_pbuf); + + if (status) + { + archive->clients = realloc(archive->clients, ++archive->count * sizeof(cdb_client *)); - client = &archive->clients[archive->count - 1]; + archive->clients[archive->count - 1] = client; - client->tls_fd = fd; - client->peer_name = strdup(peer_name); - client->user = strdup(user); + } g_mutex_unlock(&archive->clients_access); + g_mutex_unlock(&archive->loading_access); + } @@ -1343,20 +1579,15 @@ static void g_cdb_archive_add_client(GCdbArchive *archive, SSL *fd, const char * static void _g_cdb_archive_remove_client(GCdbArchive *archive, size_t index) { - cdb_client *client; /* Client à traiter */ - assert(!g_mutex_trylock(&archive->clients_access)); - client = &archive->clients[index]; - - SSL_free(client->tls_fd); - free(client->user); + unref_cdb_client(archive->clients[index]); if ((index + 1) < archive->count) memmove(&archive->clients[index], &archive->clients[index + 1], - (archive->count - index - 1) * sizeof(cdb_client)); + (archive->count - index - 1) * sizeof(cdb_client *)); - archive->clients = realloc(archive->clients, --archive->count * sizeof(cdb_client)); + archive->clients = realloc(archive->clients, --archive->count * sizeof(cdb_client *)); } @@ -1407,7 +1638,7 @@ static void g_cdb_archive_send_reply_to_all_clients(GCdbArchive *archive, packed for (i = 0; i < archive->count; i++) { - status = ssl_send_packed_buffer(pbuf, archive->clients[i].tls_fd); + status = ssl_send_packed_buffer(pbuf, archive->clients[i]->tls_fd); if (!status) { log_variadic_message(LMT_ERROR, _("Error while replying to client %zu"), i); @@ -1533,10 +1764,10 @@ static bool g_cdb_archive_send_snapshot_change(GCdbArchive *archive, packed_buff /****************************************************************************** * * * Paramètres : cmd = commande à l'origine d'un traitement. * -* error = bilan de traitement à communiquer. * +* value = valeur à communiquer. * * out_pbuf = paquet à consituer pour un retour au client. [OUT]* * * -* Description : Prépare la réponse à envoyer à un client connecté. * +* Description : Prépare une courte réponse à envoyer à un client connecté. * * * * Retour : Indication pour le maintien de la communication. * * * @@ -1544,7 +1775,7 @@ static bool g_cdb_archive_send_snapshot_change(GCdbArchive *archive, packed_buff * * ******************************************************************************/ -static bool setup_server_answer(DBCommand cmd, DBError error, packed_buffer_t *out_pbuf) +static bool craft_server_short_answer(DBCommand cmd, uleb128_t value, packed_buffer_t *out_pbuf) { bool result; /* Bilan à retourner */ @@ -1553,7 +1784,7 @@ static bool setup_server_answer(DBCommand cmd, DBError error, packed_buffer_t *o result = extend_packed_buffer(out_pbuf, (uint32_t []) { cmd }, sizeof(uint32_t), true); if (result) - result = extend_packed_buffer(out_pbuf, (uint32_t []) { error }, sizeof(uint32_t), true); + result = pack_uleb128((uleb128_t []){ value }, out_pbuf); return result; @@ -1587,6 +1818,7 @@ static bool g_cdb_archive_set_content(GCdbArchive *archive, packed_buffer_t *in_ const gchar *hash; /* Empreinte de ce contenu */ int fd; /* Flux ouvert en écriture */ bool status; /* Bilan d'une écriture */ + LoadingStatusHint hint; /* Statut de chargement */ result = true; error = DBE_NONE; @@ -1687,7 +1919,15 @@ static bool g_cdb_archive_set_content(GCdbArchive *archive, packed_buffer_t *in_ /* Formulation de la réponse */ - result = setup_server_answer(DBC_SET_CONTENT, error, out_pbuf); + result = craft_server_short_answer(DBC_SET_CONTENT, error, out_pbuf); + + if (result && error == DBE_NONE) + { + hint = g_cdb_archive_compute_loading_hint(archive); + + result = craft_server_short_answer(DBC_LOADING_STATUS, hint, out_pbuf); + + } free_and_exit: diff --git a/src/analysis/db/cdb.h b/src/analysis/db/cdb.h index b2c3fc3..7a557f2 100644 --- a/src/analysis/db/cdb.h +++ b/src/analysis/db/cdb.h @@ -54,7 +54,7 @@ typedef struct _GCdbArchiveClass GCdbArchiveClass; GType g_cdb_archive_get_type(void); /* Prépare un client pour une connexion à une BD. */ -GCdbArchive *g_cdb_archive_new(const char *, const char *, const rle_string *, DBError *); +GCdbArchive *g_cdb_archive_new(const char *, const char *, const rle_string *, const rle_string *, DBError *); /* Construit un chemin pour un fichier propre à l'archive. */ char *g_cdb_archive_get_tmp_filename(const GCdbArchive *, const char *); @@ -62,8 +62,8 @@ char *g_cdb_archive_get_tmp_filename(const GCdbArchive *, const char *); /* Enregistre une archive avec tous les éléments à conserver. */ DBError g_cdb_archive_write(const GCdbArchive *); -/* Détermine si une empreinte correspond à celle d'une archive. */ -int g_cdb_archive_compare_hash(const GCdbArchive *, const rle_string *); +/* Détermine l'archive correspond à une cible recherchée. */ +bool g_cdb_archive_compare_is_suitable_for(const GCdbArchive *, const rle_string *, const rle_string *); diff --git a/src/analysis/db/items/Makefile.am b/src/analysis/db/items/Makefile.am index b9ce117..f8f70d5 100644 --- a/src/analysis/db/items/Makefile.am +++ b/src/analysis/db/items/Makefile.am @@ -7,18 +7,9 @@ libanalysisdbitems_la_SOURCES = \ move.h move.c \ switcher.h switcher.c -libanalysisdbitems_la_LIBADD = - -libanalysisdbitems_la_LDFLAGS = +libanalysisdbitems_la_CFLAGS = $(TOOLKIT_CFLAGS) $(LIBXML_CFLAGS) $(LIBSQLITE_CFLAGS) devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysisdbitems_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = diff --git a/src/analysis/db/items/comment.c b/src/analysis/db/items/comment.c index da7a4c0..fb27f60 100644 --- a/src/analysis/db/items/comment.c +++ b/src/analysis/db/items/comment.c @@ -39,9 +39,9 @@ #include "../../human/asm/lang.h" #include "../../../common/array.h" #include "../../../common/extstr.h" +#include "../../../core/columns.h" #include "../../../glibext/gbinarycursor.h" #include "../../../glibext/linegen-int.h" -#include "../../../gtkext/gtkblockdisplay.h" diff --git a/src/analysis/db/items/move.c b/src/analysis/db/items/move.c index af1c8c1..e4f503b 100644 --- a/src/analysis/db/items/move.c +++ b/src/analysis/db/items/move.c @@ -35,9 +35,13 @@ #include "../collection-int.h" #include "../item-int.h" -#include "../../../gui/core/global.h" +#ifdef INCLUDE_GTK_SUPPORT +# include "../../../gui/core/global.h" +#endif #include "../../../glibext/gbinarycursor.h" -#include "../../../glibext/gloadedpanel.h" +#ifdef INCLUDE_GTK_SUPPORT +# include "../../../glibext/gloadedpanel.h" +#endif @@ -410,6 +414,8 @@ static char *g_db_move_build_label(GDbMove *move) static bool g_db_move_run(const GDbMove *move, GLineCursor *cursor) { +#ifdef INCLUDE_GTK_SUPPORT + GLoadedPanel *panel; /* Afficheur effectif de code */ typedef struct _move_params @@ -465,6 +471,8 @@ static bool g_db_move_run(const GDbMove *move, GLineCursor *cursor) if (panel != NULL) g_object_unref(G_OBJECT(panel)); +#endif + return true; } diff --git a/src/analysis/db/misc/Makefile.am b/src/analysis/db/misc/Makefile.am index 6d4af6c..fc3cab2 100644 --- a/src/analysis/db/misc/Makefile.am +++ b/src/analysis/db/misc/Makefile.am @@ -6,18 +6,7 @@ libanalysisdbmisc_la_SOURCES = \ snapshot.h snapshot.c \ timestamp.h timestamp.c -libanalysisdbmisc_la_LIBADD = - -libanalysisdbmisc_la_LDFLAGS = - devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysisdbmisc_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = diff --git a/src/analysis/db/protocol.h b/src/analysis/db/protocol.h index 17263c8..7707058 100644 --- a/src/analysis/db/protocol.h +++ b/src/analysis/db/protocol.h @@ -76,14 +76,21 @@ typedef enum _ServerPrivLevels +/** + * Précisions pour la commande DBC_LOADING_STATUS. + */ + + /* Eléments de base nécessaires */ -typedef enum _RequiredBasics +typedef enum _LoadingStatusHint { - RBS_NONE = 0x0, /* (Plus) rien n'est requis */ - RBS_CONTENT = 0x1, /* Contenu binaire à analyser */ - RBS_LOADED = 0x2, /* Contenu binaire analysé */ + LSH_READY = 0, /* (Plus) rien n'est requis */ + LSH_ON_WAIT_LIST = 1, /* Concurrence des connexions */ + LSH_NEED_CONTENT = 2, /* Suppléments nécessaires */ + LSH_NEED_FORMAT = 3, /* Suppléments nécessaires */ + LSH_NEED_ARCH = 4, /* Suppléments nécessaires */ -} RequiredBasics; +} LoadingStatusHint; @@ -135,6 +142,8 @@ typedef enum _DBAction */ typedef enum _DBCommand { + /* ------------------------- Commandes à portée générale ------------------------- */ + /** * Le client envoie un tout premier paquet de la forme suivante : * @@ -176,6 +185,18 @@ typedef enum _DBCommand /* ------------------------ Commandes pour analyste ------------------------ */ /** + * Gestion de la commande 'DBC_LOADING_STATUS'. + * + * Le serveur envoie un statut de prise en charge au début d'une connexion : + * + * [ Indication du serveur : DBC_LOADING_STATUS] + * [ Statut courant ; cf. LoadingStatusHint ] + * + */ + + DBC_LOADING_STATUS, /* Indications initiales */ + + /** * Gestion de la commande 'DBC_SET_CONTENT'. * * Le client connecté envoie un paquet de la forme suivante : diff --git a/src/analysis/db/server.c b/src/analysis/db/server.c index b08962c..79d5df1 100644 --- a/src/analysis/db/server.c +++ b/src/analysis/db/server.c @@ -1028,7 +1028,7 @@ static GServerBackend *g_hub_server_handle_admin(GHubServer *server, packed_buff if (has_more_data_in_packed_buffer(in_pbuf)) { - log_variadic_message(LMT_ERROR, _("The client from '%s' provided to much data!"), peer_name); + log_variadic_message(LMT_ERROR, _("The client from '%s' provided too much data!"), peer_name); result = NULL; @@ -1074,6 +1074,7 @@ static GServerBackend *g_hub_server_handle_analyst(GHubServer *server, packed_bu { GCdbArchive *result; /* Support de suivi à retourner*/ rle_string hash; /* Empreinte du binaire visé */ + rle_string class; /* Nature du contenu visé */ bool status; /* Bilan d'une opération */ GList *iter; /* Boucle de parcours */ GCdbArchive *archive; /* Destinataire final du client*/ @@ -1087,6 +1088,8 @@ static GServerBackend *g_hub_server_handle_analyst(GHubServer *server, packed_bu /* Fin de réception des données envoyées */ + setup_empty_rle_string(&hash); + status = unpack_rle_string(&hash, in_pbuf); if (!status) { @@ -1097,13 +1100,28 @@ static GServerBackend *g_hub_server_handle_analyst(GHubServer *server, packed_bu if (is_rle_string_empty(&hash)) { log_variadic_message(LMT_ERROR, _("The submitted binary hash from '%s' is empty!"), peer_name); - goto wrong_receiving; + goto wrong_receiving_0; + } + + setup_empty_rle_string(&class); + + status = unpack_rle_string(&class, in_pbuf); + if (!status) + { + log_variadic_message(LMT_ERROR, _("Error while getting the content class from '%s'..."), peer_name); + goto wrong_receiving_0; + } + + if (is_rle_string_empty(&class)) + { + log_variadic_message(LMT_ERROR, _("The submitted content class from '%s' is empty!"), peer_name); + goto wrong_receiving_1; } if (has_more_data_in_packed_buffer(in_pbuf)) { - log_variadic_message(LMT_ERROR, _("The client from '%s' provided to much data!"), peer_name); - goto wrong_receiving; + log_variadic_message(LMT_ERROR, _("The client from '%s' provided too much data!"), peer_name); + goto wrong_receiving_1; } /* Recherche d'un support existant adapté */ @@ -1114,7 +1132,7 @@ static GServerBackend *g_hub_server_handle_analyst(GHubServer *server, packed_bu { archive = G_CDB_ARCHIVE(iter->data); - if (g_cdb_archive_compare_hash(archive, &hash) == 0) + if (g_cdb_archive_compare_is_suitable_for(archive, &hash, &class)) break; } @@ -1137,7 +1155,7 @@ static GServerBackend *g_hub_server_handle_analyst(GHubServer *server, packed_bu tmpdir = strdup(server->working); tmpdir = stradd(tmpdir, "tmp" G_DIR_SEPARATOR_S); - result = g_cdb_archive_new(basedir, tmpdir, &hash, error); + result = g_cdb_archive_new(basedir, tmpdir, &hash, &class, error); free(tmpdir); free(basedir); @@ -1146,7 +1164,11 @@ static GServerBackend *g_hub_server_handle_analyst(GHubServer *server, packed_bu } - wrong_receiving: + wrong_receiving_1: + + exit_rle_string(&class); + + wrong_receiving_0: exit_rle_string(&hash); diff --git a/src/analysis/disass/Makefile.am b/src/analysis/disass/Makefile.am index 5631468..fe840c6 100644 --- a/src/analysis/disass/Makefile.am +++ b/src/analysis/disass/Makefile.am @@ -15,14 +15,9 @@ libanalysisdisass_la_SOURCES = \ rank.h rank.c \ routines.h routines.c -libanalysisdisass_la_LDFLAGS = +libanalysisdisass_la_CFLAGS = $(TOOLKIT_CFLAGS) $(LIBXML_CFLAGS) devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysisdisass_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) diff --git a/src/analysis/disass/area.h b/src/analysis/disass/area.h index 12c4617..0817419 100644 --- a/src/analysis/disass/area.h +++ b/src/analysis/disass/area.h @@ -30,7 +30,7 @@ #include "../../format/preload.h" #include "../../format/symbol.h" #include "../../glibext/delayed.h" -#include "../../gtkext/gtkstatusstack.h" +#include "../../glibext/notifier.h" diff --git a/src/analysis/disass/block.c b/src/analysis/disass/block.c index ea1441f..e15b4c1 100644 --- a/src/analysis/disass/block.c +++ b/src/analysis/disass/block.c @@ -34,9 +34,9 @@ #include "../block-int.h" #include "../../arch/instructions/raw.h" #include "../../common/extstr.h" +#include "../../core/columns.h" #include "../../core/params.h" #include "../../glibext/gbinarycursor.h" -#include "../../gtkext/gtkblockdisplay.h" @@ -88,12 +88,16 @@ static block_link_t *g_basic_block_get_sources(const GBasicBlock *, const GBlock /* Fournit les détails des destinations de bloc de code. */ static block_link_t *g_basic_block_get_destinations(const GBasicBlock *, const GBlockList *, size_t *); +#ifdef INCLUDE_GTK_SUPPORT + /* Fournit la représentation graphique d'un bloc de code. */ static GBufferView *g_basic_block_build_view(const GBasicBlock *, segcnt_list *); /* Construit un ensemble d'indications pour bloc. */ static char *g_basic_block_build_tooltip(const GBasicBlock *); +#endif + /* ---------------------------------------------------------------------------------- */ @@ -133,8 +137,10 @@ static void g_basic_block_class_init(GBasicBlockClass *class) block->cmp_links = (block_compare_links_fc)g_basic_block_compare_links; block->get_src = (block_get_links_fc)g_basic_block_get_sources; block->get_dest = (block_get_links_fc)g_basic_block_get_destinations; +#ifdef INCLUDE_GTK_SUPPORT block->build = (block_build_view_fc)g_basic_block_build_view; block->build_tooltip = (block_build_tooltip_fc)g_basic_block_build_tooltip; +#endif } @@ -466,6 +472,9 @@ static block_link_t *g_basic_block_get_destinations(const GBasicBlock *block, co } +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : block = bloc de code à manipuler. * @@ -856,6 +865,9 @@ static char *g_basic_block_build_tooltip(const GBasicBlock *block) } +#endif + + /****************************************************************************** * * * Paramètres : block = bloc d'instructions à consulter. * diff --git a/src/analysis/disass/disassembler.c b/src/analysis/disass/disassembler.c index 4056c59..4baa810 100644 --- a/src/analysis/disass/disassembler.c +++ b/src/analysis/disass/disassembler.c @@ -38,11 +38,11 @@ #include "routines.h" #include "../human/asm/lang.h" #include "../../arch/storage.h" +#include "../../core/columns.h" #include "../../core/global.h" #include "../../core/params.h" #include "../../core/nproc.h" #include "../../glibext/generators/prologue.h" -#include "../../gtkext/gtkblockdisplay.h" #include "../../plugins/pglist.h" @@ -391,7 +391,9 @@ void output_disassembly(GLoadedBinary *binary, GProcContext *context, GtkStatusS GBinContent *content; /* Contenu bianire manipulé */ GCodingLanguage *lang; /* Langage de sortie préféré */ int offset; /* Décalage des étiquettes */ +#ifdef INCLUDE_GTK_SUPPORT GWidthTracker *tracker; /* Gestionnaire de largeurs */ +#endif char **text; /* Contenu brute à imprimer */ char *desc; /* Désignation du binaire */ const gchar *checksum; /* Identifiant de binaire */ @@ -409,9 +411,11 @@ void output_disassembly(GLoadedBinary *binary, GProcContext *context, GtkStatusS g_generic_config_get_value(get_main_configuration(), MPK_LABEL_OFFSET, &offset); +#ifdef INCLUDE_GTK_SUPPORT tracker = g_buffer_cache_get_width_tracker(*cache); g_width_tracker_set_column_min_width(tracker, DLC_ASSEMBLY_LABEL, offset); g_object_unref(G_OBJECT(tracker)); +#endif g_buffer_cache_wlock(*cache); diff --git a/src/analysis/disass/fetch.h b/src/analysis/disass/fetch.h index 7afabc6..44b5424 100644 --- a/src/analysis/disass/fetch.h +++ b/src/analysis/disass/fetch.h @@ -27,7 +27,7 @@ #include "../binary.h" #include "../../glibext/delayed.h" -#include "../../gtkext/gtkstatusstack.h" +#include "../../glibext/notifier.h" diff --git a/src/analysis/disass/instructions.h b/src/analysis/disass/instructions.h index c0cd4ac..24fe982 100644 --- a/src/analysis/disass/instructions.h +++ b/src/analysis/disass/instructions.h @@ -28,7 +28,7 @@ #include "../routine.h" #include "../../arch/processor.h" #include "../../format/executable.h" -#include "../../gtkext/gtkstatusstack.h" +#include "../../glibext/notifier.h" diff --git a/src/analysis/disass/limit.c b/src/analysis/disass/limit.c index 1e460e0..2caefd6 100644 --- a/src/analysis/disass/limit.c +++ b/src/analysis/disass/limit.c @@ -76,7 +76,7 @@ void compute_routine_limit(GBinSymbol *symbol, const vmpa2t *next, GArchProcesso /* Dans tous les cas, on va se référer à la portion contenante... */ - portion = g_binary_portion_find_at_addr(portions, &addr, (GdkRectangle []) { { 0 } }); + portion = g_binary_portion_find_at_addr(portions, &addr); assert(portion != NULL); range = g_binary_portion_get_range(portion); diff --git a/src/analysis/disass/output.h b/src/analysis/disass/output.h index 20729d2..2213840 100644 --- a/src/analysis/disass/output.h +++ b/src/analysis/disass/output.h @@ -29,7 +29,7 @@ #include "../human/lang.h" #include "../../format/preload.h" #include "../../glibext/buffercache.h" -#include "../../gtkext/gtkstatusstack.h" +#include "../../glibext/notifier.h" diff --git a/src/analysis/disass/routines.h b/src/analysis/disass/routines.h index 9a2c308..af8e814 100644 --- a/src/analysis/disass/routines.h +++ b/src/analysis/disass/routines.h @@ -27,7 +27,7 @@ #include "../binary.h" #include "../routine.h" -#include "../../gtkext/gtkstatusstack.h" +#include "../../glibext/notifier.h" diff --git a/src/analysis/human/Makefile.am b/src/analysis/human/Makefile.am index bd5fa9f..a8e98e6 100644 --- a/src/analysis/human/Makefile.am +++ b/src/analysis/human/Makefile.am @@ -6,19 +6,15 @@ libanalysishuman_la_SOURCES = \ lang-int.h \ lang.h lang.c +libanalysishuman_la_CFLAGS = $(TOOLKIT_CFLAGS) + libanalysishuman_la_LIBADD = \ asm/libanalysishumanasm.la -libanalysishuman_la_LDFLAGS = - devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysishuman_la_SOURCES:%c=) -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - SUBDIRS = asm diff --git a/src/analysis/human/asm/Makefile.am b/src/analysis/human/asm/Makefile.am index 9dbf717..a3ab6a4 100644 --- a/src/analysis/human/asm/Makefile.am +++ b/src/analysis/human/asm/Makefile.am @@ -5,18 +5,9 @@ noinst_LTLIBRARIES = libanalysishumanasm.la libanalysishumanasm_la_SOURCES = \ lang.h lang.c -libanalysishumanasm_la_LIBADD = - -libanalysishumanasm_la_LDFLAGS = +libanalysishumanasm_la_CFLAGS = $(TOOLKIT_CFLAGS) devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysishumanasm_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = diff --git a/src/analysis/loaded-int.h b/src/analysis/loaded-int.h index cd47a6a..245b5ef 100644 --- a/src/analysis/loaded-int.h +++ b/src/analysis/loaded-int.h @@ -39,8 +39,8 @@ typedef bool (* save_content_fc) (GLoadedContent *, xmlDoc *, xmlXPathContext *, /* Fournit le contenu représenté de l'élément chargé. */ typedef GBinContent * (* get_content_fc) (const GLoadedContent *); -/* Fournit le format associé à l'élément chargé. */ -typedef char * (* get_format_name_fc) (const GLoadedContent *); +/* Décrit la nature du contenu reconnu pour l'élément chargé. */ +typedef char * (* get_content_class_fc) (const GLoadedContent *, bool); /* Assure l'analyse d'un contenu chargé en différé. */ typedef bool (* analyze_loaded_fc) (GLoadedContent *, bool, bool, wgroup_id_t, GtkStatusStack *); @@ -48,6 +48,8 @@ typedef bool (* analyze_loaded_fc) (GLoadedContent *, bool, bool, wgroup_id_t, G /* Fournit le désignation associée à l'élément chargé. */ typedef char * (* describe_loaded_fc) (const GLoadedContent *, bool); +#ifdef INCLUDE_GTK_SUPPORT + /* Détermine le nombre de vues disponibles pour un contenu. */ typedef unsigned int (* count_loaded_views_fc) (const GLoadedContent *); @@ -66,6 +68,8 @@ typedef unsigned int (* get_loaded_view_index_fc) (GLoadedContent *, GtkWidget * /* Fournit toutes les options d'affichage pour un contenu. */ typedef GDisplayOptions * (* get_loaded_options_fc) (const GLoadedContent *, unsigned int); +#endif + /* Accès à un contenu binaire quelconque (instance) */ struct _GLoadedContent @@ -85,12 +89,14 @@ struct _GLoadedContentClass save_content_fc save; /* Sauvegarde dans du XML */ get_content_fc get_content; /* Fourniture du contenu brut */ - get_format_name_fc get_format_name; /* Fourniture du format associé*/ + get_content_class_fc get_content_class; /* Indication de classe liée */ analyze_loaded_fc analyze; /* Analyse du contenu chargé */ describe_loaded_fc describe; /* Description de contenu */ +#ifdef INCLUDE_GTK_SUPPORT + count_loaded_views_fc count_views; /* Compteur de vues */ get_loaded_view_name_fc get_view_name; /* Désignation d'une vue donnée*/ build_loaded_def_view_fc build_def_view;/* Mise en place initiale */ @@ -99,6 +105,8 @@ struct _GLoadedContentClass get_loaded_options_fc get_options; /* Obtention de liste d'options*/ +#endif + /* Signaux */ void (* analyzed) (GLoadedContent *, gboolean); diff --git a/src/analysis/loaded.c b/src/analysis/loaded.c index 3a497f9..9a7b1fd 100644 --- a/src/analysis/loaded.c +++ b/src/analysis/loaded.c @@ -32,8 +32,10 @@ #include "../core/global.h" #include "../core/queue.h" #include "../glibext/chrysamarshal.h" -#include "../glibext/gloadedpanel.h" -#include "../glibext/named-int.h" +#ifdef INCLUDE_GTK_SUPPORT +# include "../glibext/gloadedpanel.h" +# include "../glibext/named-int.h" +#endif #include "../glibext/seq.h" #include "../plugins/pglist.h" @@ -60,9 +62,13 @@ static void g_loaded_content_class_init(GLoadedContentClass *); /* Initialise un contenu chargé. */ static void g_loaded_content_init(GLoadedContent *); +#ifdef INCLUDE_GTK_SUPPORT + /* Procède à l'initialisation de l'interface de composant nommé. */ static void g_loaded_content_named_init(GNamedWidgetIface *); +#endif + /* Supprime toutes les références externes. */ static void g_loaded_content_dispose(GLoadedContent *); @@ -89,8 +95,12 @@ static void on_loaded_content_analysis_completed(GSeqWork *, analysis_data_t *); /* Détermine le type d'une interface pour l'intégration de contenu chargé. */ +#ifdef INCLUDE_GTK_SUPPORT G_DEFINE_TYPE_WITH_CODE(GLoadedContent, g_loaded_content, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(G_TYPE_NAMED_WIDGET, g_loaded_content_named_init)); +#else +G_DEFINE_TYPE(GLoadedContent, g_loaded_content, G_TYPE_OBJECT); +#endif /****************************************************************************** @@ -143,6 +153,9 @@ static void g_loaded_content_init(GLoadedContent *content) } +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : iface = interface GLib à initialiser. * @@ -163,6 +176,9 @@ static void g_loaded_content_named_init(GNamedWidgetIface *iface) } +#endif + + /****************************************************************************** * * * Paramètres : content = instance d'objet GLib à traiter. * @@ -296,23 +312,24 @@ GBinContent *g_loaded_content_get_content(const GLoadedContent *content) /****************************************************************************** * * * Paramètres : content = élément chargé à manipuler. * +* human = description humaine attendue ? * * * -* Description : Fournit le format associé à l'élément chargé. * +* Description : Décrit la nature du contenu reconnu pour l'élément chargé. * * * -* Retour : Format associé à l'élément chargé. * +* Retour : Classe de contenu associée à l'élément chargé. * * * * Remarques : - * * * ******************************************************************************/ -char *g_loaded_content_get_format_name(const GLoadedContent *content) +char *g_loaded_content_get_content_class(const GLoadedContent *content, bool human) { char *result; /* Contenu interne à renvoyer */ GLoadedContentClass *class; /* Classe de l'instance */ class = G_LOADED_CONTENT_GET_CLASS(content); - result = class->get_format_name(content); + result = class->get_content_class(content, human); return result; @@ -576,6 +593,9 @@ char **g_loaded_content_detect_obfuscators(const GLoadedContent *content, bool v /* ---------------------------------------------------------------------------------- */ +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : content = contenu chargé à consulter. * @@ -744,12 +764,18 @@ GDisplayOptions *g_loaded_content_get_display_options(const GLoadedContent *cont } +#endif + + /* ---------------------------------------------------------------------------------- */ /* VUES ET BASCULEMENT ENTRE LES VUES */ /* ---------------------------------------------------------------------------------- */ +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : panel = panneau affichant un contenu binaire. * @@ -865,3 +891,6 @@ GtkWidget *get_loaded_panel_from_built_view(GtkWidget *view) return result; } + + +#endif diff --git a/src/analysis/loaded.h b/src/analysis/loaded.h index 9a88f8c..0f627b1 100644 --- a/src/analysis/loaded.h +++ b/src/analysis/loaded.h @@ -27,13 +27,17 @@ #include <glib-object.h> #include <stdbool.h> -#include <gtk/gtk.h> +#ifdef INCLUDE_GTK_SUPPORT +# include <gtk/gtk.h> +#endif #include "content.h" #include "../common/xml.h" #include "../glibext/gdisplayoptions.h" -#include "../gtkext/gtkdockstation.h" +#ifdef INCLUDE_GTK_SUPPORT +# include "../gtkext/gtkdockstation.h" +#endif @@ -67,8 +71,8 @@ bool g_loaded_content_save(GLoadedContent *, xmlDoc *, xmlXPathContext *, const /* Fournit le contenu représenté de l'élément chargé. */ GBinContent *g_loaded_content_get_content(const GLoadedContent *); -/* Fournit le format associé à l'élément chargé. */ -char *g_loaded_content_get_format_name(const GLoadedContent *); +/* Décrit la nature du contenu reconnu pour l'élément chargé. */ +char *g_loaded_content_get_content_class(const GLoadedContent *, bool); /* Lance l'analyse propre à l'élément chargé. */ void g_loaded_content_analyze(GLoadedContent *, bool, bool); @@ -87,6 +91,8 @@ char **g_loaded_content_detect_obfuscators(const GLoadedContent *, bool, size_t /* --------------------------- GESTION DYNAMIQUE DES VUES --------------------------- */ +#ifdef INCLUDE_GTK_SUPPORT + /* Détermine le nombre de vues disponibles pour un contenu. */ unsigned int g_loaded_content_count_views(const GLoadedContent *); @@ -105,11 +111,15 @@ unsigned int g_loaded_content_get_view_index(GLoadedContent *, GtkWidget *); /* Fournit toutes les options d'affichage pour un contenu. */ GDisplayOptions *g_loaded_content_get_display_options(const GLoadedContent *, unsigned int); +#endif + /* ----------------------- VUES ET BASCULEMENT ENTRE LES VUES ----------------------- */ +#ifdef INCLUDE_GTK_SUPPORT + /* Fournit la station d'accueil d'un panneau d'affichage. */ GtkDockStation *get_dock_station_for_view_panel(GtkWidget *); @@ -119,6 +129,8 @@ GtkWidget *get_scroll_window_for_view_panel(GtkWidget *); /* Fournit le panneau chargé inclus dans un affichage. */ GtkWidget *get_loaded_panel_from_built_view(GtkWidget *); +#endif + #endif /* _ANALYSIS_LOADED_H */ diff --git a/src/analysis/project.c b/src/analysis/project.c index b57afc7..9a5e4e2 100644 --- a/src/analysis/project.c +++ b/src/analysis/project.c @@ -1249,12 +1249,12 @@ static void on_new_content_resolved(GContentResolver *resolver, wgroup_id_t wid, hash = g_binary_content_get_checksum(content); g_object_unref(G_OBJECT(content)); - format = g_loaded_content_get_format_name(available[i]); + format = "FIXME";//g_loaded_content_get_format_name(available[i]); asprintf(&access, "/ChrysalideProject/LoadedContents/Content[@hash='%s' and @format='%s']", hash, format); - free(format); + //free(format); xobject = get_node_xpath_object(handler->context, access); @@ -1309,7 +1309,7 @@ static void on_new_content_resolved(GContentResolver *resolver, wgroup_id_t wid, /** * S'il s'agit des résultats de la dernière exploration, * alors les groupes contenant les éléments chargés vont - * être libéré, potentiellement pendant l'analyse. + * être libérés, potentiellement pendant l'analyse. * * On temporise en incrémentant les références. */ @@ -1365,6 +1365,9 @@ static void on_new_content_resolved(GContentResolver *resolver, wgroup_id_t wid, /* ---------------------------------------------------------------------------------- */ +#ifdef INCLUDE_GTK_SUPPORT + + /****************************************************************************** * * * Paramètres : - * @@ -1437,3 +1440,6 @@ void push_project_into_recent_list(const GStudyProject *project) g_generic_config_set_value(get_main_configuration(), MPK_LAST_PROJECT, project->filename); } + + +#endif diff --git a/src/analysis/project.h b/src/analysis/project.h index e8c6365..a5b1a73 100644 --- a/src/analysis/project.h +++ b/src/analysis/project.h @@ -25,7 +25,9 @@ #define _ANALYSIS_PROJECT_H -#include <gtk/gtk.h> +#ifdef INCLUDE_GTK_SUPPORT +# include <gtk/gtk.h> +#endif #include "loaded.h" @@ -115,12 +117,16 @@ GLoadedContent **g_study_project_get_contents(GStudyProject *, size_t *); /* ------------------------- GESTION GLOBALISEE DES PROJETS ------------------------- */ +#ifdef INCLUDE_GTK_SUPPORT + /* Fournit le gestionnaire des projets connus. */ GtkRecentManager *get_project_manager(void); /* Place un projet au sommet de la pile des projets récents. */ void push_project_into_recent_list(const GStudyProject *); +#endif + #endif /* _PROJECT_H */ diff --git a/src/analysis/routine.c b/src/analysis/routine.c index 41bf451..2cb4ad3 100644 --- a/src/analysis/routine.c +++ b/src/analysis/routine.c @@ -37,9 +37,9 @@ #include "routine-int.h" #include "../arch/instructions/raw.h" #include "../common/extstr.h" +#include "../core/columns.h" #include "../core/params.h" #include "../glibext/gbinarycursor.h" -#include "../gtkext/gtkblockdisplay.h" @@ -1047,6 +1047,8 @@ void g_binary_routine_print_code(const GBinRoutine *routine, GLangOutput *lang, +#ifdef INCLUDE_GTK_SUPPORT + /****************************************************************************** * * @@ -1334,3 +1336,6 @@ char *g_binary_routine_build_tooltip(const GBinRoutine *routine, const GLoadedBi return result; } + + +#endif diff --git a/src/analysis/routine.h b/src/analysis/routine.h index f148406..ac33fbd 100644 --- a/src/analysis/routine.h +++ b/src/analysis/routine.h @@ -133,10 +133,13 @@ char *g_binary_routine_to_string(const GBinRoutine *, bool); +#ifdef INCLUDE_GTK_SUPPORT /* Construit un petit résumé concis de la routine. */ char *g_binary_routine_build_tooltip(const GBinRoutine *, const GLoadedBinary *); +#endif + #endif /* _ANALYSIS_ROUTINE_H */ diff --git a/src/analysis/scan/Makefile.am b/src/analysis/scan/Makefile.am new file mode 100644 index 0000000..f7e85ad --- /dev/null +++ b/src/analysis/scan/Makefile.am @@ -0,0 +1,67 @@ + +BUILT_SOURCES = grammar.h + + +# On évite d'utiliser les variables personnalisées de type *_la_[YL]FLAGS +# afin de conserver des noms de fichiers simples, ie sans le nom de la +# bibliothèque de sortie en préfixe. + +AM_YFLAGS = -v -d -p rost_ -Wno-yacc -Wcounterexamples + +AM_LFLAGS = -b -Cf -P rost_ -o lex.yy.c --header-file=tokens.h \ + -Dyyget_lineno=rost_get_lineno \ + -Dyy_scan_bytes=rost__scan_bytes \ + -Dyy_delete_buffer=rost__delete_buffer + +noinst_LTLIBRARIES = libanalysisscan.la + + +libanalysisscan_la_SOURCES = \ + cond-int.h \ + cond.h cond.c \ + context-int.h \ + context.h context.c \ + core.h core.c \ + expr-int.h \ + expr.h expr.c \ + item-int.h \ + item.h item.c \ + matches-int.h \ + matches.h matches.c \ + options-int.h \ + options.h options.c \ + pattern-int.h \ + pattern.h pattern.c \ + rule-int.h \ + rule.h rule.c \ + scanner-int.h \ + scanner.h scanner.c \ + scope-int.h \ + scope.h scope.c \ + space-int.h \ + space.h space.c \ + tokens.l \ + grammar.y + +libanalysisscan_la_LIBADD = \ + exprs/libanalysisscanexprs.la \ + items/libanalysisscanitems.la \ + matches/libanalysisscanmatches.la \ + patterns/libanalysisscanpatterns.la + +libanalysisscan_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscan_la_SOURCES:%c=) + + +# Automake fait les choses à moitié +CLEANFILES = grammar.h grammar.c grammar.output tokens.c tokens.h + +# Pareil : de tous les fichiers générés, seule la sortie de Flex saute pour les distributions ! +EXTRA_DIST = tokens.h + + +SUBDIRS = exprs items matches patterns diff --git a/src/analysis/scan/cond-int.h b/src/analysis/scan/cond-int.h new file mode 100644 index 0000000..aeb3fc9 --- /dev/null +++ b/src/analysis/scan/cond-int.h @@ -0,0 +1,63 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * cond-int.h - prototypes internes pour le parcours de contenus à la recherche de motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_COND_INT_H +#define _ANALYSIS_SCAN_COND_INT_H + + +#include "cond.h" + + + +/* Indique le statut d'une condition de validation. */ +typedef bool (* resolve_cond_fc) (const GMatchCondition *); + +/* Indique le statut d'une condition de validation. */ +typedef unsigned long long (* resolve_cond_as_number_fc) (const GMatchCondition *); + +/* Avance vers la validation d'une condition, si besoin est. */ +typedef void (* analyze_cond_fc) (const GMatchCondition *, const bin_t *, phys_t, phys_t, bool); + + + +/* Expression conditionnelle manipulant des motifs (instance) */ +struct _GMatchCondition +{ + GObject parent; /* A laisser en premier */ + +}; + +/* Expression conditionnelle manipulant des motifs (classe) */ +struct _GMatchConditionClass +{ + GObjectClass parent; /* A laisser en premier */ + + resolve_cond_fc resolve; /* Réduction en booléen */ + resolve_cond_as_number_fc resolve_as_num; /* Réduction en nombre */ + analyze_cond_fc analyze; /* Analyse selon une position */ + +}; + + + +#endif /* _ANALYSIS_SCAN_COND_INT_H */ diff --git a/src/analysis/scan/cond.c b/src/analysis/scan/cond.c new file mode 100644 index 0000000..be5b3cb --- /dev/null +++ b/src/analysis/scan/cond.c @@ -0,0 +1,220 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * cond.c - expression conditionnelle validant la présence de motifs donnés + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "cond.h" + + +#include "cond-int.h" + + + +/* Initialise la classe des recherches dans du binaire. */ +static void g_match_condition_class_init(GMatchConditionClass *); + +/* Initialise une instance de recherche dans du binaire. */ +static void g_match_condition_init(GMatchCondition *); + +/* Supprime toutes les références externes. */ +static void g_match_condition_dispose(GMatchCondition *); + +/* Procède à la libération totale de la mémoire. */ +static void g_match_condition_finalize(GMatchCondition *); + + + +/* Indique le type défini pour une expression de validation. */ +G_DEFINE_TYPE(GMatchCondition, g_match_condition, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des recherches dans du binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_match_condition_class_init(GMatchConditionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + klass->resolve = NULL; + klass->resolve_as_num = NULL; + klass->analyze = NULL; + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_match_condition_dispose; + object->finalize = (GObjectFinalizeFunc)g_match_condition_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : cond = instance à initialiser. * +* * +* Description : Initialise une instance de recherche dans du binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_match_condition_init(GMatchCondition *cond) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : cond = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_match_condition_dispose(GMatchCondition *cond) +{ + G_OBJECT_CLASS(g_match_condition_parent_class)->dispose(G_OBJECT(cond)); + +} + + +/****************************************************************************** +* * +* Paramètres : cond = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_match_condition_finalize(GMatchCondition *cond) +{ + G_OBJECT_CLASS(g_match_condition_parent_class)->finalize(G_OBJECT(cond)); + +} + + +/****************************************************************************** +* * +* Paramètres : cond = condition à consulter. * +* * +* Description : Indique le statut d'une condition de validation. * +* * +* Retour : Validation de la condition considérée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_match_condition_resolve(const GMatchCondition *cond) +{ + bool result; /* Bilan à retourner */ + GMatchConditionClass *class; /* Classe à activer */ + unsigned long long number; /* Valeur à considérer */ + + class = G_MATCH_CONDITION_GET_CLASS(cond); + + if (class->resolve != NULL) + result = class->resolve(cond); + + else if (class->resolve_as_num != NULL) + { + number = class->resolve_as_num(cond); + result = (number > 0); + } + + else + result = false; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : cond = condition à consulter. * +* * +* Description : Indique le statut d'une condition de validation. * +* * +* Retour : Forme numérique de la condition considérée pour validation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +unsigned long long g_match_condition_resolve_as_number(const GMatchCondition *cond) +{ + unsigned long long result; /* Valeur à retourner */ + GMatchConditionClass *class; /* Classe à activer */ + + class = G_MATCH_CONDITION_GET_CLASS(cond); + + result = class->resolve_as_num(cond); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : cond = condition à considérer. * +* data = données binaires brutes à considérer. * +* size = quantité de ces données. * +* pos = position du point d'étude courant. * +* full = force une recherche pleine et entière. * +* * +* Description : Avance vers la validation d'une condition, si besoin est. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_match_condition_analyze(const GMatchCondition *cond, const bin_t *data, phys_t size, phys_t pos, bool full) +{ + GMatchConditionClass *class; /* Classe à activer */ + + class = G_MATCH_CONDITION_GET_CLASS(cond); + + class->analyze(cond, data, size, pos, full); + +} diff --git a/src/analysis/scan/cond.h b/src/analysis/scan/cond.h new file mode 100644 index 0000000..7a5d3c4 --- /dev/null +++ b/src/analysis/scan/cond.h @@ -0,0 +1,65 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * cond.h - prototypes pour l'expression conditionnelle validant la présence de motifs donnés + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_COND_H +#define _ANALYSIS_SCAN_COND_H + + +#include <glib-object.h> + + +#include "../../arch/archbase.h" +#include "../../arch/vmpa.h" + + + +#define G_TYPE_MATCH_CONDITION g_match_condition_get_type() +#define G_MATCH_CONDITION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_MATCH_CONDITION, GMatchCondition)) +#define G_IS_MATCH_CONDITION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_MATCH_CONDITION)) +#define G_MATCH_CONDITION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_MATCH_CONDITION, GMatchConditionClass)) +#define G_IS_MATCH_CONDITION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_MATCH_CONDITION)) +#define G_MATCH_CONDITION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_MATCH_CONDITION, GMatchConditionClass)) + + +/* Expression conditionnelle manipulant des motifs (instance) */ +typedef struct _GMatchCondition GMatchCondition; + +/* Expression conditionnelle manipulant des motifs (classe) */ +typedef struct _GMatchConditionClass GMatchConditionClass; + + +/* Indique le type défini pour une expression de validation. */ +GType g_match_condition_get_type(void); + +/* Indique le statut d'une condition de validation. */ +bool g_match_condition_resolve(const GMatchCondition *); + +/* Indique le statut d'une condition de validation. */ +unsigned long long g_match_condition_resolve_as_number(const GMatchCondition *); + +/* Avance vers la validation d'une condition, si besoin est. */ +void g_match_condition_analyze(const GMatchCondition *, const bin_t *, phys_t, phys_t, bool); + + + +#endif /* _ANALYSIS_SCAN_COND_H */ diff --git a/src/analysis/scan/context-int.h b/src/analysis/scan/context-int.h new file mode 100644 index 0000000..6135201 --- /dev/null +++ b/src/analysis/scan/context-int.h @@ -0,0 +1,100 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * context-int.h - prototypes internes pour un suivi d'analyses via contextes + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_CONTEXT_INT_H +#define _ANALYSIS_SCAN_CONTEXT_INT_H + + +#include "context.h" + + +#include "expr.h" +#include "../../common/fnv1a.h" +#include "../../glibext/umemslice.h" + + +//#define __USE_TABLE_FOR_MATCHES + + +#ifndef __USE_TABLE_FOR_MATCHES + +/* Lien entre un motif et ses correspondances */ +typedef struct _matched_pattern_t +{ + const GSearchPattern *pattern; /* Motif recherché */ + GScanMatches *matches; /* Correspondances associées */ + +} matched_pattern_t; + +#endif + +/* Condition définissant une règle de correspondance */ +typedef struct _rule_condition_t +{ + char *name; /* Désignation de la règle */ + fnv64_t name_hash; /* Empreinte de la désignation */ + + GScanExpression *expr; /* Condition de correspondance */ + bool final_reduced; /* Réduction finale tentée ? */ + +} rule_condition_t; + +/* Contexte de suivi d'une analyse en cours (instance) */ +struct _GScanContext +{ + GObject parent; /* A laisser en premier */ + + GScanOptions *options; /* Options d'analyses */ + + GBinContent *content; /* Contenu binaire traité */ + bool scan_done; /* Phase d'analyse terminée ? */ + + GUMemSlice *match_allocator; /* Suivi de correspondances */ + match_area_t **match_storages; /* Suivi de correspondances */ + size_t storages_count; /* Quantité de ces suivis */ + +#ifdef __USE_TABLE_FOR_MATCHES + GHashTable *full_trackers; /* Correspondances confirmées */ +#else + matched_pattern_t *full_trackers; /* Correspondances confirmées */ + size_t full_allocated; /* Quantité d'éléments alloués */ + size_t full_count; /* Quantité de correspondances */ +#endif + + bool global; /* Validation globale */ + + rule_condition_t *conditions; /* Ensemble de règles suivies */ + size_t cond_count; /* Quantité de ces conditions */ + +}; + +/* Contexte de suivi d'une analyse en cours (classe) */ +struct _GScanContextClass +{ + GObjectClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_CONTEXT_INT_H */ diff --git a/src/analysis/scan/context.c b/src/analysis/scan/context.c new file mode 100644 index 0000000..7929f9c --- /dev/null +++ b/src/analysis/scan/context.c @@ -0,0 +1,841 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * context.c - suivi d'analyses via contextes + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "context.h" + + +#include <assert.h> +#include <malloc.h> +#include <stdlib.h> +#include <string.h> + + +#include "context-int.h" +#include "exprs/literal.h" +#include "matches/area.h" +#include "matches/bytes.h" +#include "../../common/sort.h" + + + +/* --------------------- MEMORISATION DE PROGRESSIONS D'ANALYSE --------------------- */ + + +/* Initialise la classe des contextes de suivi d'analyses. */ +static void g_scan_context_class_init(GScanContextClass *); + +/* Initialise une instance de contexte de suivi d'analyse. */ +static void g_scan_context_init(GScanContext *); + +/* Supprime toutes les références externes. */ +static void g_scan_context_dispose(GScanContext *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_context_finalize(GScanContext *); + +#ifndef __USE_TABLE_FOR_MATCHES + +/* Compare un lien entre motif et correspondances avec un autre. */ +static int compare_matched_pattern(const matched_pattern_t *, const matched_pattern_t *); + +#endif + + + +/* ---------------------------------------------------------------------------------- */ +/* MEMORISATION DE PROGRESSIONS D'ANALYSE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un contexte de suivi d'analyse. */ +G_DEFINE_TYPE(GScanContext, g_scan_context, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des contextes de suivi d'analyses. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_context_class_init(GScanContextClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_context_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_context_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à initialiser. * +* * +* Description : Initialise une instance de contexte de suivi d'analyse. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_context_init(GScanContext *context) +{ + context->options = NULL; + + context->content = NULL; + context->scan_done = false; + + context->match_allocator = g_umem_slice_new(sizeof(match_area_t)); + context->match_storages = NULL; + context->storages_count = 0; + +#ifdef __USE_TABLE_FOR_MATCHES + context->full_trackers = g_hash_table_new_full(NULL, NULL, NULL/*g_object_unref*/, g_object_unref); +#else + context->full_trackers = NULL; + context->full_allocated = 0; + context->full_count = 0; +#endif + + context->global = true; + + context->conditions = NULL; + context->cond_count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_context_dispose(GScanContext *context) +{ +#ifndef __USE_TABLE_FOR_MATCHES + matched_pattern_t *iter; /* Boucle de parcours #1 */ + matched_pattern_t *max; /* Borne de fin de parcours */ +#endif + size_t i; /* Boucle de parcours #2 */ + + g_clear_object(&context->options); + + g_clear_object(&context->content); + + g_clear_object(&context->match_allocator); + + if (context->full_trackers != NULL) + { +#ifdef __USE_TABLE_FOR_MATCHES + + g_hash_table_destroy(context->full_trackers); + context->full_trackers = NULL; + +#else + + iter = context->full_trackers; + max = iter + context->full_count; + + for (; iter < max; iter++) + g_object_unref(G_OBJECT(iter->matches)); + + free(context->full_trackers); + context->full_trackers = NULL; + +#endif + + } + + for (i = 0; i < context->cond_count; i++) + g_clear_object(&context->conditions[i].expr); + + G_OBJECT_CLASS(g_scan_context_parent_class)->dispose(G_OBJECT(context)); + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_context_finalize(GScanContext *context) +{ + size_t i; /* Boucle de parcours */ + + if (context->match_storages != NULL) + free(context->match_storages); + + if (context->conditions != NULL) + { + for (i = 0; i < context->cond_count; i++) + free(context->conditions[i].name); + + free(context->conditions); + + } + + G_OBJECT_CLASS(g_scan_context_parent_class)->finalize(G_OBJECT(context)); + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à respecter. * +* * +* Description : Définit un contexte pour suivi d'analyse. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanContext *g_scan_context_new(GScanOptions *options) +{ + GScanContext *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_CONTEXT, NULL); + + result->options = options; + g_object_ref(G_OBJECT(options)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à consulter. * +* * +* Description : Fournit l'ensemble des options à respecter pour les analyses.* +* * +* Retour : Ensemble d'options en vigueur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanOptions *g_scan_context_get_options(const GScanContext *context) +{ + GScanOptions *result; /* Ensemble à retourner */ + + result = context->options; + + g_object_ref(G_OBJECT(result)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à consulter. * +* content = contenu binaire en cours d'analyse. * +* ids_count = nombre d'identifiants enregistrés. * +* * +* Description : Définit le contenu principal à analyser. * +* * +* Retour : Content binaire associé au context. * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_context_set_content(GScanContext *context, GBinContent *content, size_t ids_count) +{ + g_clear_object(&context->content); + + context->content = content; + + g_object_ref(G_OBJECT(content)); + + context->match_storages = calloc(ids_count, sizeof(match_area_t *)); + context->storages_count = ids_count; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à consulter. * +* * +* Description : Fournit une référence au contenu principal analysé. * +* * +* Retour : Content binaire associé au context. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GBinContent *g_scan_context_get_content(const GScanContext *context) +{ + GBinContent *result; /* Instance à retourner */ + + result = context->content; + + g_object_ref(G_OBJECT(result)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à consulter. * +* * +* Description : Indique si la phase d'analyse de contenu est terminée. * +* * +* Retour : true si la phase de scan est terminée, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_context_is_scan_done(const GScanContext *context) +{ + bool result; /* Statut à retourner */ + + result = context->scan_done; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à mettre à jour. * +* * +* Description : Note que la phase d'analyse de contenu est terminée. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_context_mark_scan_as_done(GScanContext *context) +{ + context->scan_done = true; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à mettre à jour. * +* id = identifiant du motif trouvé. * +* end = position finale d'une correspondance partielle. * +* * +* Description : Retourne tous les correspondances partielles notées. * +* * +* Retour : Liste interne des localisations conservées. * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_context_store_atom_match_end(GScanContext *context, patid_t id, phys_t end) +{ + match_area_t *new; /* Nouvel enregistrement */ + + new = g_umem_slice_alloc(context->match_allocator); + + new->end = end + 1; + + add_tail_match_area(new, &context->match_storages[id]); + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à mettre à jour. * +* id = identifiant du motif trouvé. * +* * +* Description : Retourne tous les correspondances partielles notées. * +* * +* Retour : Liste interne des localisations conservées. * +* * +* Remarques : - * +* * +******************************************************************************/ + +match_area_t *g_scan_context_get_atom_matches(const GScanContext *context, patid_t id) +{ + match_area_t *result; /* Liste constituée à renvoyer */ + + result = context->match_storages[id]; + + return result; + +} + + +#ifndef __USE_TABLE_FOR_MATCHES + +/****************************************************************************** +* * +* Paramètres : a = premier lien motif/correspondances à comparer. * +* b = second lien motif/correspondances à comparer. * +* * +* Description : Compare un lien entre motif et correspondances avec un autre.* +* * +* Retour : Bilan de la comparaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static int compare_matched_pattern(const matched_pattern_t *a, const matched_pattern_t *b) +{ + int result; /* Bilan à renvoyer */ + + assert(sizeof(unsigned long) == sizeof(void *)); + + result = sort_unsigned_long((unsigned long)a->pattern, (unsigned long)b->pattern); + + return result; + +} + +#endif + + +/****************************************************************************** +* * +* Paramètres : context = instance à mettre à jour. * +* pattern = definition initiale d'un motif recherché. * +* matches = mémorisation de correspondances établies. * +* * +* Description : Enregistre toutes les correspondances établies pour un motif.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_context_register_full_matches(GScanContext *context, GSearchPattern *pattern, GScanMatches *matches) +{ +#ifndef NDEBUG + GSearchPattern *matches_pattern; /* Clef d'un suivi */ +#endif +#ifndef __USE_TABLE_FOR_MATCHES + matched_pattern_t new; /* Nouvel enregistrement */ +#endif + +#ifndef NDEBUG + + matches_pattern = g_scan_matches_get_source(matches); + + assert(matches_pattern == pattern); + + g_object_unref(G_OBJECT(matches_pattern)); + +#endif + +#ifdef __USE_TABLE_FOR_MATCHES + + assert(!g_hash_table_contains(context->full_trackers, pattern)); + + //g_object_ref(G_OBJECT(pattern)); /* TODO : REMME */ + g_object_ref(G_OBJECT(matches)); + + g_hash_table_insert(context->full_trackers, pattern, matches); + +#else + + new.pattern = pattern; + new.matches = matches; + + g_object_ref(G_OBJECT(matches)); + + context->full_trackers = qinsert_managed(context->full_trackers, &context->full_count, &context->full_allocated, + sizeof(matched_pattern_t), (__compar_fn_t)compare_matched_pattern, + &new); + +#endif + + g_scan_matches_attach(matches, context, pattern); + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à mettre à jour. * +* pattern = motif dont des correspondances sont à retrouver. * +* * +* Description : Fournit la liste de toutes les correspondances pour un motif.* +* * +* Retour : Liste courante de correspondances établies. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanMatches *g_scan_context_get_full_matches(const GScanContext *context, const GSearchPattern *pattern) +{ + GScanMatches *result; /* Correspondance à renvoyer */ +#ifndef __USE_TABLE_FOR_MATCHES + matched_pattern_t target; /* Lien ciblé */ + matched_pattern_t *found; /* Lien trouvé */ +#endif + +#ifdef __USE_TABLE_FOR_MATCHES + + result = g_hash_table_lookup(context->full_trackers, pattern); + + if (result != NULL) + g_object_ref(G_OBJECT(result)); + +#else + + target.pattern = pattern; + + found = bsearch(&target, context->full_trackers, context->full_count, + sizeof(matched_pattern_t), (__compar_fn_t)compare_matched_pattern); + + if (found == NULL) + result = NULL; + + else + { + result = found->matches; + g_object_ref(G_OBJECT(result)); + } + +#endif + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = instance à mettre à jour. * +* pattern = motif dont des correspondances sont à retrouver. * +* * +* Description : Dénombre les correspondances associées à un motif. * +* * +* Retour : Quantité de correspondances établies pour un motif entier. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_scan_context_count_full_matches(const GScanContext *context, const GSearchPattern *pattern) +{ + size_t result; /* Quantité à retourner */ +#ifdef __USE_TABLE_FOR_MATCHES + GScanMatches *matches; /* Ensemble de Correspondances */ +#else + matched_pattern_t target; /* Lien ciblé */ + matched_pattern_t *found; /* Lien trouvé */ +#endif + +#ifdef __USE_TABLE_FOR_MATCHES + + matches = g_hash_table_lookup(context->full_trackers, pattern); + + if (matches != NULL) + result = g_scan_matches_count(matches); + else + result = 0; + +#else + + target.pattern = pattern; + + found = bsearch(&target, context->full_trackers, context->full_count, + sizeof(matched_pattern_t), (__compar_fn_t)compare_matched_pattern); + + if (found == NULL) + result = 0; + else + result = g_scan_matches_count(found->matches); + +#endif + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = mémoire de résultats d'analyse à compléter. * +* name = désignation de la règle ciblée. * +* expr = expression de condition à réduire. * +* * +* Description : Intègre une condition de correspondance pour règle. * +* * +* Retour : Bilan final d'une intégration (false si nom déjà présent). * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_context_set_rule_condition(GScanContext *context, const char *name, GScanExpression *expr) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + rule_condition_t *new; /* Nouvel élément à intégrer */ + + result = true; + + /* Recherche d'antécédent */ + + for (i = 0; i < context->cond_count; i++) + if (strcmp(name, context->conditions[i].name) == 0) + { + result = false; + break; + } + + /* Ajout d'un nouvel élément ? */ + + if (result) + { + context->conditions = realloc(context->conditions, ++context->cond_count * sizeof(rule_condition_t)); + + new = &context->conditions[context->cond_count - 1]; + + new->name = strdup(name); + new->name_hash = fnv_64a_hash(name); + + new->expr = expr; + g_object_ref(G_OBJECT(expr)); + new->final_reduced = false; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = mémoire de résultats d'analyse à consulter. * +* name = désignation de la règle ciblée. * +* * +* Description : Indique si un nom donné correspond à une règle. * +* * +* Retour : Bilan de la présence d'une règle désignée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_context_has_rule_for_name(const GScanContext *context, const char *name) +{ + bool result; /* Bilan à retourner */ + fnv64_t hash; /* Empreinte du nom à retrouver*/ + size_t i; /* Boucle de parcours */ + const rule_condition_t *cond; /* Condition connue du contexte*/ + + result = false; + + hash = fnv_64a_hash(name); + + for (i = 0; i < context->cond_count; i++) + { + cond = context->conditions + i; + + if (cond->name_hash != hash) + continue; + + if (strcmp(cond->name, name) == 0) + { + result = true; + break; + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = mémoire de résultats d'analyse à consulter. * +* * +* Description : Indique le bilan des règles globales. * +* * +* Retour : Bilan global des analyses menées. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_context_has_global_match(const GScanContext *context) +{ + bool result; /* Bilan global à retourner */ + + result = context->global; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : context = mémoire de résultats d'analyse à actualiser. * +* global = bilan global des analyses menées. * +* * +* Description : Définit le bilan des règles globales. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_context_set_global_match(GScanContext *context, bool global) +{ + context->global = global; + +} + + +/****************************************************************************** +* * +* Paramètres : context = mémoire de résultats d'analyse à consulter. * +* name = désignation de la règle ciblée. * +* * +* Description : Indique si une correspondance globale a pu être établie. * +* * +* Retour : Bilan final d'une analyse (false par défaut). * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_context_has_match_for_rule(GScanContext *context, const char *name) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + rule_condition_t *cond; /* Condition à considérer */ + GScanScope *scope; /* Définition de portées */ + GScanExpression *new; /* Nouvelle expression réduite */ + ScanReductionState state; /* Statut d'une réduction */ + bool valid; /* Validité d'une récupération */ + + result = false; + + if (!context->global) + goto exit; + + /* Recherche de la règle visée */ + + cond = NULL; + + for (i = 0; i < context->cond_count; i++) + if (strcmp(name, context->conditions[i].name) == 0) + { + cond = &context->conditions[i]; + break; + } + + if (cond == NULL) + goto exit; + + /* Tentative de réduction finale */ + + if (!cond->final_reduced) + { + scope = g_scan_scope_new(name); + + state = g_scan_expression_reduce(cond->expr, context, scope, &new); + if (state == SRS_UNRESOLVABLE) goto exit_reduction; + + g_object_unref(G_OBJECT(cond->expr)); + cond->expr = new; + + valid = g_scan_expression_reduce_to_boolean(cond->expr, context, scope, &new); + if (!valid || new == NULL) goto exit_reduction; + + g_object_unref(G_OBJECT(cond->expr)); + cond->expr = new; + + cond->final_reduced = true; + + exit_reduction: + + g_object_unref(G_OBJECT(scope)); + + } + + /* Tentative de récupération d'un bilan final */ + + if (cond->final_reduced) + { + valid = g_scan_literal_expression_get_boolean_value(G_SCAN_LITERAL_EXPRESSION(cond->expr), &result); + + if (!valid) + { + assert(!result); + result = false; + } + + } + + exit: + + return result; + +} diff --git a/src/analysis/scan/context.h b/src/analysis/scan/context.h new file mode 100644 index 0000000..c3b979d --- /dev/null +++ b/src/analysis/scan/context.h @@ -0,0 +1,111 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * context.h - prototypes pour le suivi d'analyses via contextes + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_CONTEXT_H +#define _ANALYSIS_SCAN_CONTEXT_H + + +#include <glib-object.h> + + +#include "matches.h" +#include "options.h" +#include "matches/area.h" +#include "patterns/patid.h" +#include "../content.h" + + + +/* Depuis expr.h : expression d'évaluation généraliste (instance) */ +typedef struct _GScanExpression GScanExpression; + + +#define G_TYPE_SCAN_CONTEXT g_scan_context_get_type() +#define G_SCAN_CONTEXT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_CONTEXT, GScanContext)) +#define G_IS_SCAN_CONTEXT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_CONTEXT)) +#define G_SCAN_CONTEXT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_CONTEXT, GScanContextClass)) +#define G_IS_SCAN_CONTEXT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_CONTEXT)) +#define G_SCAN_CONTEXT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_CONTEXT, GScanContextClass)) + + +/* Contexte de suivi d'une analyse en cours (instance) */ +typedef struct _GScanContext GScanContext; + +/* Contexte de suivi d'une analyse en cours (classe) */ +typedef struct _GScanContextClass GScanContextClass; + + +/* Indique le type défini pour un contexte de suivi d'analyse. */ +GType g_scan_context_get_type(void); + +/* Définit un contexte pour suivi d'analyse. */ +GScanContext *g_scan_context_new(GScanOptions *); + +/* Fournit l'ensemble des options à respecter pour les analyses. */ +GScanOptions *g_scan_context_get_options(const GScanContext *); + +/* Définit le contenu principal à analyser. */ +void g_scan_context_set_content(GScanContext *, GBinContent *, size_t); + +/* Fournit une référence au contenu principal analysé. */ +GBinContent *g_scan_context_get_content(const GScanContext *); + +/* Indique si la phase d'analyse de contenu est terminée. */ +bool g_scan_context_is_scan_done(const GScanContext *); + +/* Note que la phase d'analyse de contenu est terminée. */ +void g_scan_context_mark_scan_as_done(GScanContext *); + +/* Retourne tous les correspondances partielles notées. */ +void g_scan_context_store_atom_match_end(GScanContext *, patid_t, phys_t); + +/* Retourne tous les correspondances partielles notées. */ +match_area_t *g_scan_context_get_atom_matches(const GScanContext *, patid_t); + +/* Enregistre toutes les correspondances établies pour un motif. */ +void g_scan_context_register_full_matches(GScanContext *, GSearchPattern *, GScanMatches *); + +/* Fournit la liste de toutes les correspondances pour un motif. */ +GScanMatches *g_scan_context_get_full_matches(const GScanContext *, const GSearchPattern *); + +/* Dénombre les correspondances associées à un motif. */ +size_t g_scan_context_count_full_matches(const GScanContext *, const GSearchPattern *); + +/* Intègre une condition de correspondance pour règle. */ +bool g_scan_context_set_rule_condition(GScanContext *, const char *, GScanExpression *); + +/* Indique si un nom donné correspond à une règle. */ +bool g_scan_context_has_rule_for_name(const GScanContext *, const char *); + +/* Indique le bilan des règles globales. */ +bool g_scan_context_has_global_match(const GScanContext *); + +/* Définit le bilan des règles globales. */ +void g_scan_context_set_global_match(GScanContext *, bool); + +/* Indique si une correspondance globale a pu être établie. */ +bool g_scan_context_has_match_for_rule(GScanContext *, const char *); + + + +#endif /* _ANALYSIS_SCAN_CONTEXT_H */ diff --git a/src/analysis/scan/core.c b/src/analysis/scan/core.c new file mode 100644 index 0000000..2b4fd92 --- /dev/null +++ b/src/analysis/scan/core.c @@ -0,0 +1,385 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * core.c - enregistrement des fonctions principales + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "core.h" + + +#include <malloc.h> +#include <string.h> + + +#include "items/count.h" +#include "items/datasize.h" +#include "items/maxcommon.h" +#include "items/modpath.h" +#include "items/uint.h" +#include "items/console/log.h" +#ifdef INCLUDE_MAGIC_SUPPORT +# include "items/magic/type.h" +# include "items/magic/mime-encoding.h" +# include "items/magic/mime-type.h" +#endif +#include "items/math/to_string.h" +#include "items/string/lower.h" +#include "items/string/to_int.h" +#include "items/string/upper.h" +#include "items/string/wide.h" +#include "items/time/make.h" +#include "items/time/now.h" +#include "patterns/modifiers/hex.h" +#include "patterns/modifiers/lower.h" +#include "patterns/modifiers/plain.h" +#include "patterns/modifiers/rev.h" +#include "patterns/modifiers/upper.h" +#include "patterns/modifiers/wide.h" +#include "patterns/modifiers/xor.h" + + +/* Liste des modificateurs disponibles */ + +typedef struct _available_modifier_t +{ + sized_string_t name; /* Désignation humaine */ + GScanTokenModifier *instance; /* Mécanisme correspondant */ + +} available_modifier_t; + +static available_modifier_t *__modifiers = NULL; +static size_t __modifiers_count = 0; + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à rendre disponible. * +* * +* Description : Inscrit un modificateur dans la liste des disponibles. * +* * +* Retour : Bilan des enregistrements effectués : true si nouveauté. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool register_scan_token_modifier(GScanTokenModifier *modifier) +{ + bool result; /* Bilan à retourner */ + sized_string_t name; /* Nom donné au modificateur */ + GScanTokenModifier *found; /* Alternative présente */ + available_modifier_t *last; /* Emplacement disponible */ + + name.data = g_scan_token_modifier_get_name(modifier); + name.len = strlen(name.data); + + found = find_scan_token_modifiers_for_name(&name); + + result = (found == NULL); + + if (!result) + exit_szstr(&name); + + else + { + __modifiers_count++; + __modifiers = realloc(__modifiers, __modifiers_count * sizeof(available_modifier_t)); + + last = &__modifiers[__modifiers_count - 1]; + + last->name = name; + last->instance = modifier; + + g_object_ref(G_OBJECT(modifier)); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Charge tous les modificateurs de base. * +* * +* Retour : Bilan des opérations d'enregistrement. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool load_all_known_scan_token_modifiers(void) +{ + bool result; /* Bilan à retourner */ + + result = true; + +#define REGISTER_SCAN_MODIFIER(m) \ + ({ \ + GScanTokenModifier *__mod; \ + bool __status; \ + __mod = m; \ + __status = register_scan_token_modifier(__mod); \ + g_object_unref(G_OBJECT(__mod)); \ + __status; \ + }) + + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_hex_modifier_new()); + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_lower_modifier_new()); + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_plain_modifier_new()); + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_reverse_modifier_new()); + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_upper_modifier_new()); + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_wide_modifier_new()); + if (result) result = REGISTER_SCAN_MODIFIER(g_scan_xor_modifier_new()); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : count = nombre de motificateurs exportés. [OUT] * +* * +* Description : Fournit la désignation de l'ensemble des modificateurs. * +* * +* Retour : Liste de modificateurs enregistrés. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char **list_all_scan_token_modifiers(size_t *count) +{ + char **result; /* Liste à retourner */ + size_t i; /* Boucle de parcours */ + + result = malloc(__modifiers_count * sizeof(char *)); + + *count = __modifiers_count; + + for (i = 0; i < __modifiers_count; i++) + result[i] = strndup(__modifiers[i].name.data, __modifiers[i].name.len); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Décharge tous les modificateurs inscrits. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void unload_all_scan_token_modifiers(void) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < __modifiers_count; i++) + { + exit_szstr(&__modifiers[i].name); + g_object_unref(G_OBJECT(__modifiers[i].instance)); + } + + if (__modifiers != NULL) + free(__modifiers); + +} + + +/****************************************************************************** +* * +* Paramètres : name = désignation du modificateur recherché. * +* * +* Description : Fournit le modificateur correspondant à un nom. * +* * +* Retour : Instance du modificateur identifié ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *find_scan_token_modifiers_for_name(const sized_string_t *name) +{ + GScanTokenModifier *result; /* Instance à renvoyer */ + size_t i; /* Boucle de parcours */ + available_modifier_t *registered; /* Infos d'enregistrement */ + + result = NULL; + + for (i = 0; i < __modifiers_count; i++) + { + registered = __modifiers + i; + + if (registered->name.len != name->len) + continue; + + if (strncmp(registered->name.data, name->data, name->len) == 0) + { + result = registered->instance; + g_object_ref(G_OBJECT(result)); + break; + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : space = espace de noms à composer. * +* * +* Description : Inscrit les principales fonctions dans l'espace racine. * +* * +* Retour : Bilan des enregistrements effectués. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool populate_main_scan_namespace(GScanNamespace *space) +{ + bool result; /* Bilan à retourner */ + GScanNamespace *ns; /* Nouvel espace de noms */ + + result = true; + +#define REGISTER_FUNC(s, f) \ + ({ \ + GScanRegisteredItem *__item; \ + bool __result; \ + __item = f; \ + __result = g_scan_namespace_register_item(s, __item); \ + g_object_unref(G_OBJECT(__item)); \ + __result; \ + }) + + if (result) result = REGISTER_FUNC(space, g_scan_count_function_new()); + if (result) result = REGISTER_FUNC(space, g_scan_datasize_function_new()); + if (result) result = REGISTER_FUNC(space, g_scan_maxcommon_function_new()); + if (result) result = REGISTER_FUNC(space, g_scan_modpath_function_new()); + + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_8_BITS_SIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_8_BITS_UNSIGNED, SRE_LITTLE)); + + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_16_BITS_SIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_16_BITS_SIGNED, SRE_BIG)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_16_BITS_UNSIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_16_BITS_UNSIGNED, SRE_BIG)); + + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_32_BITS_SIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_32_BITS_SIGNED, SRE_BIG)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_32_BITS_UNSIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_32_BITS_UNSIGNED, SRE_BIG)); + + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_64_BITS_SIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_64_BITS_SIGNED, SRE_BIG)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_64_BITS_UNSIGNED, SRE_LITTLE)); + if (result) result = REGISTER_FUNC(space, g_scan_uint_function_new(MDS_64_BITS_UNSIGNED, SRE_BIG)); + + /* Console */ + + if (result) + { + ns = g_scan_namespace_new("console"); + result = g_scan_namespace_register_item(space, G_SCAN_REGISTERED_ITEM(ns)); + + if (result) result = REGISTER_FUNC(ns, g_scan_console_log_function_new()); + + g_object_unref(G_OBJECT(ns)); + + } + + /* Magic */ + +#ifdef INCLUDE_MAGIC_SUPPORT + if (result) + { + ns = g_scan_namespace_new("magic"); + result = g_scan_namespace_register_item(space, G_SCAN_REGISTERED_ITEM(ns)); + + if (result) result = REGISTER_FUNC(ns, g_scan_magic_type_function_new()); + if (result) result = REGISTER_FUNC(ns, g_scan_mime_encoding_function_new()); + if (result) result = REGISTER_FUNC(ns, g_scan_mime_type_function_new()); + + g_object_unref(G_OBJECT(ns)); + + } +#endif + + /* Math */ + + if (result) + { + ns = g_scan_namespace_new("math"); + result = g_scan_namespace_register_item(space, G_SCAN_REGISTERED_ITEM(ns)); + + if (result) result = REGISTER_FUNC(ns, g_scan_math_to_string_function_new()); + + g_object_unref(G_OBJECT(ns)); + + } + + /* String */ + + if (result) + { + ns = g_scan_namespace_new("string"); + result = g_scan_namespace_register_item(space, G_SCAN_REGISTERED_ITEM(ns)); + + if (result) result = REGISTER_FUNC(ns, g_scan_string_lower_function_new()); + if (result) result = REGISTER_FUNC(ns, g_scan_string_to_int_function_new()); + if (result) result = REGISTER_FUNC(ns, g_scan_string_upper_function_new()); + if (result) result = REGISTER_FUNC(ns, g_scan_string_wide_function_new()); + + g_object_unref(G_OBJECT(ns)); + + } + + /* Time */ + + if (result) + { + ns = g_scan_namespace_new("time"); + result = g_scan_namespace_register_item(space, G_SCAN_REGISTERED_ITEM(ns)); + + if (result) result = REGISTER_FUNC(ns, g_scan_time_make_function_new()); + if (result) result = REGISTER_FUNC(ns, g_scan_time_now_function_new()); + + g_object_unref(G_OBJECT(ns)); + + } + + return result; + +} diff --git a/src/analysis/scan/core.h b/src/analysis/scan/core.h new file mode 100644 index 0000000..a56ce16 --- /dev/null +++ b/src/analysis/scan/core.h @@ -0,0 +1,53 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * core.h - prototypes pour l'enregistrement des fonctions principales + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_CORE_H +#define _ANALYSIS_SCAN_CORE_H + + +#include "space.h" +#include "patterns/modifier.h" + + + +/* Inscrit un modificateur dans la liste des disponibles. */ +bool register_scan_token_modifier(GScanTokenModifier *); + +/* Charge tous les modificateurs de base. */ +bool load_all_known_scan_token_modifiers(void); + +/* Fournit la désignation de l'ensemble des modificateurs. */ +char **list_all_scan_token_modifiers(size_t *); + +/* Décharge tous les modificateurs inscrits. */ +void unload_all_scan_token_modifiers(void); + +/* Fournit le modificateur correspondant à un nom. */ +GScanTokenModifier *find_scan_token_modifiers_for_name(const sized_string_t *); + +/* Inscrit les principales fonctions dans l'espace racine. */ +bool populate_main_scan_namespace(GScanNamespace *); + + + +#endif /* _ANALYSIS_SCAN_CORE_H */ diff --git a/src/analysis/scan/decl.h b/src/analysis/scan/decl.h new file mode 100644 index 0000000..ab70368 --- /dev/null +++ b/src/analysis/scan/decl.h @@ -0,0 +1,40 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * decl.h - déclarations de prototypes utiles + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Chrysalide. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_DECL_H +#define _ANALYSIS_SCAN_DECL_H + + +#include <stdbool.h> + + +#include "scanner.h" + + + +/* Complète une recherche de motifs avec des règles. */ +bool process_rules_definitions(GContentScanner *, const char *, size_t); + + + +#endif /* _ANALYSIS_SCAN_DECL_H */ diff --git a/src/analysis/scan/expr-int.h b/src/analysis/scan/expr-int.h new file mode 100644 index 0000000..618ecf7 --- /dev/null +++ b/src/analysis/scan/expr-int.h @@ -0,0 +1,88 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * expr-int.h - prototypes internes pour la définition d'une expression servant aux conditions de correspondance + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPR_INT_H +#define _ANALYSIS_SCAN_EXPR_INT_H + + +#include "expr.h" + + +#include <stdbool.h> + + +#include "../../glibext/comparison-int.h" + + + +/* Réalise une comparaison entre objets selon un critère précis. */ +typedef bool (* compare_expr_rich_fc) (const GScanExpression *, const GScanExpression *, RichCmpOperation, bool *); + +/* Réduit une expression à une forme plus simple. */ +typedef ScanReductionState (* reduce_expr_fc) (GScanExpression *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réduit une expression à une forme booléenne. */ +typedef bool (* reduce_expr_to_bool_fc) (GScanExpression *, GScanContext *, GScanScope *, GScanExpression **); + +/* Dénombre les éléments portés par une expression. */ +typedef bool (* count_scan_expr_fc) (const GScanExpression *, GScanContext *, size_t *); + +/* Fournit un élément donné issu d'un ensemble constitué. */ +typedef bool (* get_scan_expr_fc) (const GScanExpression *, size_t, GScanContext *, GScanExpression **); + +/* Réalise l'intersection entre deux ensembles. */ +typedef GScanExpression * (* intersect_scan_expr_fc) (GScanExpression *, const GScanExpression *, GScanContext *, GScanScope *); + + +/* Expression d'évaluation généraliste (instance) */ +struct _GScanExpression +{ + GObject parent; /* A laisser en premier */ + + ScanReductionState state; /* Etat synthétisé de l'élément*/ + +}; + +/* Expression d'évaluation généraliste (classe) */ +struct _GScanExpressionClass +{ + GObjectClass parent; /* A laisser en premier */ + + compare_expr_rich_fc cmp_rich; /* Comparaison de façon précise*/ + + reduce_expr_fc reduce; /* Simplification d'expression */ + reduce_expr_to_bool_fc reduce_to_bool; /* Conversion en booléen */ + + count_scan_expr_fc count; /* Décompte d'éléments */ + get_scan_expr_fc get; /* Extraction d'un élément */ + intersect_scan_expr_fc intersect; /* Intersection entre ensembles*/ + +}; + + +/* Met en place une expression d'évaluation pour analyse. */ +bool g_scan_expression_create(GScanExpression *, ScanReductionState); + + + +#endif /* _ANALYSIS_SCAN_EXPR_INT_H */ diff --git a/src/analysis/scan/expr.c b/src/analysis/scan/expr.c new file mode 100644 index 0000000..332619d --- /dev/null +++ b/src/analysis/scan/expr.c @@ -0,0 +1,638 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * expr.c - définition d'une expression servant aux conditions de correspondance + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "expr.h" + + +#include <assert.h> + + +#include "expr-int.h" +#include "exprs/literal.h" +#include "exprs/set.h" + + + +/* ----------------------- BASES D'OBJET POUR LE SYSTEME GLIB ----------------------- */ + + +/* Initialise la classe des expressions de validation. */ +static void g_scan_expression_class_init(GScanExpressionClass *); + +/* Initialise une instance d'expression de validation. */ +static void g_scan_expression_init(GScanExpression *); + +/* Procède à l'initialisation de l'interface de comparaison. */ +static void g_scan_expression_cmp_interface_init(GComparableItemInterface *); + +/* Supprime toutes les références externes. */ +static void g_scan_expression_dispose(GScanExpression *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_expression_finalize(GScanExpression *); + +/* Réalise l'intersection entre deux ensembles. */ +static GScanExpression *_g_scan_expression_intersect(GScanExpression *, const GScanExpression *, GScanContext *, GScanScope *); + + + +/* ----------------------- INTERFACE OFFRANT DES COMPARAISONS ----------------------- */ + + +/* Réalise une comparaison entre objets selon un critère précis. */ +static bool g_scan_expression_compare_rich(const GScanExpression *, const GScanExpression *, RichCmpOperation, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* BASES D'OBJET POUR LE SYSTEME GLIB */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une expression de validation. */ +G_DEFINE_TYPE_WITH_CODE(GScanExpression, g_scan_expression, G_TYPE_OBJECT, + G_IMPLEMENT_INTERFACE(G_TYPE_COMPARABLE_ITEM, g_scan_expression_cmp_interface_init)); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des expressions de validation. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_expression_class_init(GScanExpressionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_expression_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_expression_finalize; + + klass->intersect = _g_scan_expression_intersect; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance à initialiser. * +* * +* Description : Initialise une instance d'expression de validation. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_expression_init(GScanExpression *expr) +{ + expr->state = SRS_PENDING; + +} + + +/****************************************************************************** +* * +* Paramètres : iface = interface GLib à initialiser. * +* * +* Description : Procède à l'initialisation de l'interface de comparaison. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_expression_cmp_interface_init(GComparableItemInterface *iface) +{ + iface->cmp_rich = (compare_rich_fc)g_scan_expression_compare_rich; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_expression_dispose(GScanExpression *expr) +{ + G_OBJECT_CLASS(g_scan_expression_parent_class)->dispose(G_OBJECT(expr)); + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_expression_finalize(GScanExpression *expr) +{ + G_OBJECT_CLASS(g_scan_expression_parent_class)->finalize(G_OBJECT(expr)); + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance à initialiser pleinement. * +* state = état de réduction initial associé par l'expression. * +* * +* Description : Met en place une expression d'évaluation pour analyse. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_expression_create(GScanExpression *expr, ScanReductionState state) +{ + bool result; /* Bilan à retourner */ + + result = true; + + expr->state = state; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* * +* Description : Indique l'état de réduction d'une expression. * +* * +* Retour : Etat courant associé à l'expression. * +* * +* Remarques : - * +* * +******************************************************************************/ + +ScanReductionState g_scan_expression_get_state(const GScanExpression *expr) +{ + ScanReductionState result; /* Etat à retourner */ + + result = expr->state; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +ScanReductionState g_scan_expression_reduce(GScanExpression *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + GScanExpressionClass *class; /* Classe à activer */ + + if (expr->state == SRS_REDUCED) + { + *out = expr; + g_object_ref(G_OBJECT(expr)); + } + + else + { + *out = NULL; + + class = G_SCAN_EXPRESSION_GET_CLASS(expr); + + if (class->reduce != NULL) + { + expr->state = class->reduce(expr, ctx, scope, out); + + if (expr->state != SRS_UNRESOLVABLE && *out == NULL) + { + *out = expr; + g_object_ref(G_OBJECT(expr)); + } + + } + + else + expr->state = SRS_UNRESOLVABLE; + +#ifndef NDEBUG + if (*out != NULL) + assert(expr->state != SRS_UNRESOLVABLE); +#endif + + } + + assert(expr->state != SRS_PENDING); + + + return expr->state; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme booléenne. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_expression_reduce_to_boolean(GScanExpression *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + GScanExpression *inter; /* Expression intermédiaire */ + GScanExpressionClass *class; /* Classe à activer */ + + *out = NULL; + + result = g_scan_expression_reduce(expr, ctx, scope, &inter); + if (!result) goto exit; + + if (inter != NULL) + { + class = G_SCAN_EXPRESSION_GET_CLASS(inter); + + if (class->reduce_to_bool != NULL) + result = class->reduce_to_bool(inter, ctx, scope, out); + else + result = false; + + g_object_unref(G_OBJECT(inter)); + + /* Validation d'un type booléen */ + if (result && *out != NULL) + { + if (!G_IS_SCAN_LITERAL_EXPRESSION(*out)) + { + g_clear_object(out); + result = false; + } + + if (g_scan_literal_expression_get_value_type(G_SCAN_LITERAL_EXPRESSION(*out)) != LVT_BOOLEAN) + { + g_clear_object(out); + result = false; + } + + } + + } + + exit: + +#ifndef NDEBUG + if (*out != NULL) + assert(result); +#endif + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* * +* Description : Détermine si l'expression peut représenter un ensemble. * +* * +* Retour : Bilan de la consultation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_expression_handle_set_features(const GScanExpression *expr) +{ + bool result; /* Bilan à retourner */ + GScanExpressionClass *class; /* Classe à activer */ + + class = G_SCAN_EXPRESSION_GET_CLASS(expr); + + result = (class->count != NULL); + + assert((result && (class->get != NULL)) || (!result && (class->get == NULL))); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* count = quantité d'éléments déterminée. [OUT] * +* * +* Description : Dénombre les éléments portés par une expression. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_expression_count_items(const GScanExpression *expr, GScanContext *ctx, size_t *count) +{ + bool result; /* Bilan à retourner */ + GScanExpressionClass *class; /* Classe à activer */ + + *count = -1; + + class = G_SCAN_EXPRESSION_GET_CLASS(expr); + + if (class->count != NULL) + result = class->count(expr, ctx, count); + else + result = false; + +#ifndef NDEBUG + if (*count != -1) + assert(result); +#endif + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* index = indice de l'élément à transférer. * +* ctx = contexte de suivi de l'analyse courante. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Fournit un élément donné issu d'un ensemble constitué. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_expression_get_item(const GScanExpression *expr, size_t index, GScanContext *ctx, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + GScanExpressionClass *class; /* Classe à activer */ + + *out = NULL; + + class = G_SCAN_EXPRESSION_GET_CLASS(expr); + + if (class->get != NULL) + { + result = class->get(expr, index, ctx, out); + + if (*out != NULL) + g_object_ref(G_OBJECT(*out)); + + } + + else + result = false; + +#ifndef NDEBUG + if (*out != NULL) + assert(result); +#endif + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à filtrer. * +* other = expression utilisée pour le filtrage. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* * +* Description : Réalise l'intersection entre deux ensembles. * +* * +* Retour : Intersection entre les deux ensembles ou NULL en cas d'échec.* +* * +* Remarques : - * +* * +******************************************************************************/ + +static GScanExpression *_g_scan_expression_intersect(GScanExpression *expr, const GScanExpression *other, GScanContext *ctx, GScanScope *scope) +{ + GScanExpression *result; /* Instance à retourner */ + size_t other_count; /* Taille du second ensemble */ + bool valid; /* Bilan de validité */ + size_t expr_count; /* Taille du premier ensemble */ + size_t k; /* Boucle de parcours #1 */ + GComparableItem *comparable; /* Premier élément à comparer */ + size_t i; /* Boucle de parcours #2 */ + GScanExpression *item; /* Elément à comparer */ + bool status; /* Bilan d'une comparaison */ + + result = NULL; + + valid = g_scan_expression_count_items(other, ctx, &other_count); + if (!valid) goto done; + + /* Intersection entre deux ensembles ? */ + if (g_scan_expression_handle_set_features(expr)) + { + valid = g_scan_expression_count_items(expr, ctx, &expr_count); + if (!valid) goto done; + + result = g_scan_generic_set_new(); + + for (k = 0; k < expr_count; k++) + { + valid = g_scan_expression_get_item(expr, k, ctx, &item); + if (!valid) break; + + comparable = G_COMPARABLE_ITEM(item); + + for (i = 0; i < other_count; i++) + { + valid = g_scan_expression_get_item(other, i, ctx, &item); + if (!valid) break; + + valid = g_comparable_item_compare_rich(comparable, G_COMPARABLE_ITEM(item), RCO_EQ, &status); + + if (valid && status) + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET(result), item); + + g_object_unref(G_OBJECT(item)); + + } + + g_object_unref(G_OBJECT(comparable)); + + } + + } + + /* Intersection entre un élément et un ensemble */ + else + { + comparable = G_COMPARABLE_ITEM(expr); + + for (i = 0; i < other_count && result == NULL; i++) + { + valid = g_scan_expression_get_item(other, i, ctx, &item); + if (!valid) break; + + valid = g_comparable_item_compare_rich(comparable, G_COMPARABLE_ITEM(item), RCO_EQ, &status); + + if (valid && status) + result = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { true }); + + g_object_unref(G_OBJECT(item)); + + } + + if (result && result == NULL) + result = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { false }); + + } + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à filtrer. * +* other = expression utilisée pour le filtrage. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* * +* Description : Réalise l'intersection entre deux ensembles. * +* * +* Retour : Intersection entre les deux ensembles ou NULL en cas d'échec.* +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_expression_intersect(GScanExpression *expr, const GScanExpression *other, GScanContext *ctx, GScanScope *scope) +{ + GScanExpression *result; /* Instance à retourner */ + GScanExpressionClass *class; /* Classe à activer */ + + class = G_SCAN_EXPRESSION_GET_CLASS(expr); + + result = class->intersect(expr, other, ctx, scope); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* INTERFACE OFFRANT DES COMPARAISONS */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = premier objet à cnsulter pour une comparaison. * +* other = second objet à cnsulter pour une comparaison. * +* op = opération de comparaison à réaliser. * +* status = bilan des opérations de comparaison. [OUT] * +* * +* Description : Réalise une comparaison entre objets selon un critère précis.* +* * +* Retour : true si la comparaison a pu être effectuée, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_expression_compare_rich(const GScanExpression *item, const GScanExpression *other, RichCmpOperation op, bool *status) +{ + bool result; /* Etat à retourner */ + GScanExpressionClass *class; /* Classe à activer */ + + class = G_SCAN_EXPRESSION_GET_CLASS(item); + + if (class->cmp_rich != NULL) + { + result = (G_TYPE_FROM_INSTANCE(item) == G_TYPE_FROM_INSTANCE(other)); // FIXME : subtype ? cf. literal ? + + if (result) + result = class->cmp_rich(item, other, op, status); + + } + + else + result = false; + + return result; + +} diff --git a/src/analysis/scan/expr.h b/src/analysis/scan/expr.h new file mode 100644 index 0000000..38cbac6 --- /dev/null +++ b/src/analysis/scan/expr.h @@ -0,0 +1,89 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * expr.h - prototypes pour la définition d'une expression servant aux conditions de correspondance + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPR_H +#define _ANALYSIS_SCAN_EXPR_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "context.h" +#include "scope.h" + + + +#define G_TYPE_SCAN_EXPRESSION g_scan_expression_get_type() +#define G_SCAN_EXPRESSION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_EXPRESSION, GScanExpression)) +#define G_IS_SCAN_EXPRESSION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_EXPRESSION)) +#define G_SCAN_EXPRESSION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_EXPRESSION, GScanExpressionClass)) +#define G_IS_SCAN_EXPRESSION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_EXPRESSION)) +#define G_SCAN_EXPRESSION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_EXPRESSION, GScanExpressionClass)) + + +/* Expression d'évaluation généraliste (instance) */ +typedef struct _GScanExpression GScanExpression; + +/* Expression d'évaluation généraliste (classe) */ +typedef struct _GScanExpressionClass GScanExpressionClass; + + +/* Etat de l'expression vis à vis des réductions */ +typedef enum _ScanReductionState +{ + SRS_PENDING, /* Nature à déterminer */ + SRS_REDUCED, /* Nature compacte finale */ + SRS_WAIT_FOR_SCAN, /* Nature vouée à évoluer */ + SRS_UNRESOLVABLE, /* Nature indéterminable */ + +} ScanReductionState; + + +/* Indique le type défini pour une expression de validation. */ +GType g_scan_expression_get_type(void); + +/* Indique l'état de réduction d'une expression. */ +ScanReductionState g_scan_expression_get_state(const GScanExpression *); + +/* Réduit une expression à une forme plus simple. */ +ScanReductionState g_scan_expression_reduce(GScanExpression *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réduit une expression à une forme booléenne. */ +bool g_scan_expression_reduce_to_boolean(GScanExpression *, GScanContext *, GScanScope *, GScanExpression **); + +/* Détermine si l'expression peut représenter un ensemble. */ +bool g_scan_expression_handle_set_features(const GScanExpression *); + +/* Dénombre les éléments portés par une expression. */ +bool g_scan_expression_count_items(const GScanExpression *, GScanContext *, size_t *); + +/* Fournit un élément donné issu d'un ensemble constitué. */ +bool g_scan_expression_get_item(const GScanExpression *, size_t, GScanContext *, GScanExpression **); + +/* Réalise l'intersection entre deux ensembles. */ +GScanExpression *g_scan_expression_intersect(GScanExpression *, const GScanExpression *, GScanContext *, GScanScope *); + + + +#endif /* _ANALYSIS_SCAN_EXPR_H */ diff --git a/src/analysis/scan/exprs/Makefile.am b/src/analysis/scan/exprs/Makefile.am new file mode 100644 index 0000000..c97fa25 --- /dev/null +++ b/src/analysis/scan/exprs/Makefile.am @@ -0,0 +1,40 @@ + +noinst_LTLIBRARIES = libanalysisscanexprs.la + + +libanalysisscanexprs_la_SOURCES = \ + access-int.h \ + access.h access.c \ + arithmetic-int.h \ + arithmetic.h arithmetic.c \ + call-int.h \ + call.h call.c \ + extract-int.h \ + extract.h extract.c \ + handler-int.h \ + handler.h handler.c \ + intersect-int.h \ + intersect.h intersect.c \ + item-int.h \ + item.h item.c \ + literal-int.h \ + literal.h literal.c \ + logical-int.h \ + logical.h logical.c \ + range-int.h \ + range.h range.c \ + relational-int.h \ + relational.h relational.c \ + set-int.h \ + set.h set.c \ + setcounter-int.h \ + setcounter.h setcounter.c \ + strop-int.h \ + strop.h strop.c + +libanalysisscanexprs_la_CFLAGS = $(TOOLKIT_CFLAGS) $(LIBXML_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanexprs_la_SOURCES:%c=) diff --git a/src/analysis/scan/exprs/access-int.h b/src/analysis/scan/exprs/access-int.h new file mode 100644 index 0000000..be37241 --- /dev/null +++ b/src/analysis/scan/exprs/access-int.h @@ -0,0 +1,74 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * access-int.h - prototypes internes pour l'accès à un élément d'expression sous-jacent + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_ACCESS_INT_H +#define _ANALYSIS_SCAN_EXPRS_ACCESS_INT_H + + +#include "access.h" + + +#include "../expr-int.h" + + + +/* Reproduit un accès en place dans une nouvelle instance. */ +typedef void (* copy_scan_access_fc) (GScanNamedAccess *, const GScanNamedAccess *); + +/* Accès à un élément d'expression sous-jacent (instance) */ +struct _GScanNamedAccess +{ + GScanExpression parent; /* A laisser en premier */ + + union + { + GScanRegisteredItem *base; /* Base de recherche */ + GScanRegisteredItem *resolved; /* Elément ciblé au final */ + GObject *any; /* Accès indistinct */ + }; + + char *target; /* Cible dans l'espace */ + + struct _GScanNamedAccess *next; /* Evnetuel prochain élément */ + +}; + +/* Accès à un élément d'expression sous-jacent (classe) */ +struct _GScanNamedAccessClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + + copy_scan_access_fc copy; /* Reproduction d'accès */ + +}; + + +/* Met en place une expression d'accès. */ +bool g_scan_named_access_create(GScanNamedAccess *, const sized_string_t *); + +/* Prépare une réduction en menant une résolution locale. */ +GScanRegisteredItem *_g_scan_named_access_prepare_reduction(const GScanNamedAccess *, GScanContext *, GScanScope *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_ACCESS_INT_H */ diff --git a/src/analysis/scan/exprs/access.c b/src/analysis/scan/exprs/access.c new file mode 100644 index 0000000..342c2d7 --- /dev/null +++ b/src/analysis/scan/exprs/access.c @@ -0,0 +1,508 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * access.c - accès à un élément d'expression sous-jacent + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "access.h" + + +#include <assert.h> +#include <malloc.h> +#include <string.h> + + +#include "access-int.h" +#include "literal.h" +#include "../../../core/global.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des appels de fonction avec arguments. */ +static void g_scan_named_access_class_init(GScanNamedAccessClass *); + +/* Initialise une instance d'appel de fonction avec arguments. */ +static void g_scan_named_access_init(GScanNamedAccess *); + +/* Supprime toutes les références externes. */ +static void g_scan_named_access_dispose(GScanNamedAccess *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_named_access_finalize(GScanNamedAccess *); + +/* Reproduit un accès en place dans une nouvelle instance. */ +static void g_scan_named_access_copy(GScanNamedAccess *, const GScanNamedAccess *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_named_access_reduce(const GScanNamedAccess *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un appel de fonction enregistrée. */ +G_DEFINE_TYPE(GScanNamedAccess, g_scan_named_access, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des appels de fonction avec arguments. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_named_access_class_init(GScanNamedAccessClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_named_access_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_named_access_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)NULL; + expr->reduce = (reduce_expr_fc)g_scan_named_access_reduce; + + klass->copy = g_scan_named_access_copy; + +} + + +/****************************************************************************** +* * +* Paramètres : access = instance à initialiser. * +* * +* Description : Initialise une instance d'appel de fonction avec arguments. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_named_access_init(GScanNamedAccess *access) +{ + access->any = NULL; + access->target = NULL; + + access->next = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : access = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_named_access_dispose(GScanNamedAccess *access) +{ + g_clear_object(&access->any); + + g_clear_object(&access->next); + + G_OBJECT_CLASS(g_scan_named_access_parent_class)->dispose(G_OBJECT(access)); + +} + + +/****************************************************************************** +* * +* Paramètres : access = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_named_access_finalize(GScanNamedAccess *access) +{ + if (access->target != NULL) + free(access->target); + + G_OBJECT_CLASS(g_scan_named_access_parent_class)->finalize(G_OBJECT(access)); + +} + + +/****************************************************************************** +* * +* Paramètres : target = désignation de l'objet d'appel à identifier. * +* * +* Description : Organise un accès à un élément d'expression sous-jacent. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_named_access_new(const sized_string_t *target) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_NAMED_ACCESS, NULL); + + if (!g_scan_named_access_create(G_SCAN_NAMED_ACCESS(result), target)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : access = instance à initialiser pleinement. * +* target = désignation de l'objet d'appel à identifier. * +* * +* Description : Met en place une expression d'accès. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_named_access_create(GScanNamedAccess *access, const sized_string_t *target) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(access), SRS_PENDING); + if (!result) goto exit; + + if (target != NULL) + access->target = strndup(target->data, target->len); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = emplacement d'enregistrement à constituer. [OUT] * +* src = expression source à copier. * +* * +* Description : Reproduit un accès en place dans une nouvelle instance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_named_access_copy(GScanNamedAccess *dest, const GScanNamedAccess *src) +{ + /** + * Les champs suivants sont voués à être remplacés ou supprimés. + * + * On évite donc une instanciation inutile. + */ + + /* + if (src->any != NULL) + { + dest->any = src->any; + g_object_ref(src->any); + } + */ + + if (src->target != NULL) + dest->target = strdup(src->target); + + if (src->next != NULL) + { + dest->next = src->next; + g_object_ref(src->next); + } + +} + + +/****************************************************************************** +* * +* Paramètres : accès = expression d'accès à copier. * +* resolved = nouvelle base à imposer. * +* * +* Description : Reproduit un accès en place dans une nouvelle instance. * +* * +* Retour : Nouvelle instance d'expression d'accès. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_named_access_duplicate(const GScanNamedAccess *access, GScanRegisteredItem *resolved) +{ + GScanExpression *result; /* Instance copiée à retourner */ + GType type; /* Type d'objet à copier */ + GScanNamedAccessClass *class; /* Classe à activer */ + + type = G_TYPE_FROM_INSTANCE(access); + + result = g_object_new(type, NULL); + + class = G_SCAN_NAMED_ACCESS_GET_CLASS(access); + + class->copy(G_SCAN_NAMED_ACCESS(result), access); + + g_scan_named_access_set_base(G_SCAN_NAMED_ACCESS(result), resolved); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : access = expression d'appel à actualiser. * +* base = zone de recherche pour la résolution à venir. * +* * +* Description : Définit une base de recherche pour la cible d'accès. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_named_access_set_base(GScanNamedAccess *access, GScanRegisteredItem *base) +{ + g_clear_object(&access->base); + + access->base = base; + g_object_ref(G_OBJECT(base)); + +} + + +/****************************************************************************** +* * +* Paramètres : access = expression d'appel à compléter. * +* next = expression d'appel suivante dans la chaîne. * +* * +* Description : Complète la chaine d'accès à des expressions. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_named_access_attach_next(GScanNamedAccess *access, GScanNamedAccess *next) +{ + if (access->next != NULL) + g_scan_named_access_attach_next(access->next, next); + + else + { + access->next = next; + g_object_ref(G_OBJECT(next)); + } + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* * +* Description : Prépare une réduction en menant une résolution locale. * +* * +* Retour : Elément résolu avec les moyens du bord ou NULL si échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *_g_scan_named_access_prepare_reduction(const GScanNamedAccess *expr, GScanContext *ctx, GScanScope *scope) +{ + GScanRegisteredItem *result; /* Etat synthétisé à retourner */ + GScanRegisteredItem *base; /* Base de recherche courante */ + + result = NULL; + + if (expr->target != NULL) + { + if (expr->base != NULL) + { + base = expr->base; + g_object_ref(G_OBJECT(base)); + } + else + base = G_SCAN_REGISTERED_ITEM(get_rost_root_namespace()); + + g_scan_registered_item_resolve(base, expr->target, ctx, scope, &result); + + g_object_unref(G_OBJECT(base)); + + } + + /** + * Si plus aucune indication n'est diponible pour avancer dans les réductions, + * c'est que l'opération est déjà conclue. + */ + else + { + assert(expr->resolved != NULL); + + result = expr->resolved; + g_object_ref(G_OBJECT(result)); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_named_access_reduce(const GScanNamedAccess *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanRegisteredItem *resolved; /* Cible concrète obtenue */ + GScanExpression *new_next; /* Nouvelle version du suivant */ + const char *current_rule; /* Nom de la règle courante */ + bool status; /* Bilan d'une autre règle */ + + resolved = _g_scan_named_access_prepare_reduction(expr, ctx, scope); + + if (resolved != NULL) + { + result = SRS_PENDING; + + /** + * Si l'élément résolu se trouve en fin de chaîne, alors cet élément + * est sollicité pour obtenir une expression d'évaluation classique. + * Le produit de cette réduction finale bénéficie d'une promotion et + * représente à lui seul la réduction produite pour la chaîne. + */ + if (expr->next == NULL) + { + status = g_scan_registered_item_reduce(resolved, ctx, scope, out); + + result = (status ? SRS_REDUCED : SRS_UNRESOLVABLE); + + } + + /** + * Sinon, l'élément résolu constitue une base pour l'étage suivant de + * la chaîne de résolution. + */ + else + { + new_next = g_scan_named_access_duplicate(expr->next, resolved); + + result = g_scan_expression_reduce(new_next, ctx, scope, out); + + g_object_unref(G_OBJECT(new_next)); + + } + + g_object_unref(G_OBJECT(resolved)); + + } + + /** + * Si le nom fournit le correspond à aucun élément de la grammaire, + * des recherches sont menées ailleurs. + */ + else + { + result = SRS_UNRESOLVABLE; + + if (g_scan_context_has_rule_for_name(ctx, expr->target)) + { + current_rule = g_scan_scope_get_rule_name(scope); + + /* Si référence circulaire il y a... */ + if (strcmp(current_rule, expr->target) == 0) + result = SRS_UNRESOLVABLE; + + else + { + status = g_scan_context_has_match_for_rule(ctx, expr->target); + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, &status); + result = SRS_REDUCED; + + } + + } + + } + + return result; + +} diff --git a/src/analysis/scan/exprs/access.h b/src/analysis/scan/exprs/access.h new file mode 100644 index 0000000..bf83dd0 --- /dev/null +++ b/src/analysis/scan/exprs/access.h @@ -0,0 +1,66 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * access.h - prototypes pour l'accès à un élément d'expression sous-jacent + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_ACCESS_H +#define _ANALYSIS_SCAN_EXPRS_ACCESS_H + + +#include "../expr.h" +#include "../item.h" +#include "../../../common/szstr.h" + + + +#define G_TYPE_SCAN_NAMED_ACCESS g_scan_named_access_get_type() +#define G_SCAN_NAMED_ACCESS(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_NAMED_ACCESS, GScanNamedAccess)) +#define G_IS_SCAN_NAMED_ACCESS(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_NAMED_ACCESS)) +#define G_SCAN_NAMED_ACCESS_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_NAMED_ACCESS, GScanNamedAccessClass)) +#define G_IS_SCAN_NAMED_ACCESS_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_NAMED_ACCESS)) +#define G_SCAN_NAMED_ACCESS_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_NAMED_ACCESS, GScanNamedAccessClass)) + + +/* Accès à un élément d'expression sous-jacent (instance) */ +typedef struct _GScanNamedAccess GScanNamedAccess; + +/* Accès à un élément d'expression sous-jacent (classe) */ +typedef struct _GScanNamedAccessClass GScanNamedAccessClass; + + +/* Indique le type défini pour un appel de fonction enregistrée. */ +GType g_scan_named_access_get_type(void); + +/* Organise un accès à un élément d'expression sous-jacent. */ +GScanExpression *g_scan_named_access_new(const sized_string_t *); + +/* Reproduit un accès en place dans une nouvelle instance. */ +GScanExpression *g_scan_named_access_duplicate(const GScanNamedAccess *, GScanRegisteredItem *); + +/* Définit une base de recherche pour la cible d'accès. */ +void g_scan_named_access_set_base(GScanNamedAccess *, GScanRegisteredItem *); + +/* Complète la chaine d'accès à des expressions. */ +void g_scan_named_access_attach_next(GScanNamedAccess *, GScanNamedAccess *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_ACCESS_H */ diff --git a/src/analysis/scan/exprs/arithmetic-int.h b/src/analysis/scan/exprs/arithmetic-int.h new file mode 100644 index 0000000..c5010b0 --- /dev/null +++ b/src/analysis/scan/exprs/arithmetic-int.h @@ -0,0 +1,60 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * arithmetic-int.h - prototypes internes pour la gestion des opérations arithmétiques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_ARITHMETIC_INT_H +#define _ANALYSIS_SCAN_EXPRS_ARITHMETIC_INT_H + + +#include "arithmetic.h" + + +#include "../expr-int.h" + + + +/* Opération arithmétique impliquant deux opérandes (instance) */ +struct _GScanArithmeticOperation +{ + GScanExpression parent; /* A laisser en premier */ + + ArithmeticExpressionOperator operator; /* Type d'opération menée */ + + GScanExpression *left; /* Expression impactée #1 */ + GScanExpression *right; /* Expression impactée #2 */ + +}; + +/* Opération arithmétique impliquant deux opérandes (classe) */ +struct _GScanArithmeticOperationClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une opération arithmétique entre expressions. */ +bool g_scan_arithmetic_operation_create(GScanArithmeticOperation *, ArithmeticExpressionOperator, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_ARITHMETIC_INT_H */ diff --git a/src/analysis/scan/exprs/arithmetic.c b/src/analysis/scan/exprs/arithmetic.c new file mode 100644 index 0000000..06cfc48 --- /dev/null +++ b/src/analysis/scan/exprs/arithmetic.c @@ -0,0 +1,641 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * arithmetic.c - gestion des opérations arithmétiques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "arithmetic.h" + + +#include <assert.h> + + +#include "arithmetic-int.h" +#include "literal.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des opérations arithmétiques. */ +static void g_scan_arithmetic_operation_class_init(GScanArithmeticOperationClass *); + +/* Initialise une instance d'opération arithmétique. */ +static void g_scan_arithmetic_operation_init(GScanArithmeticOperation *); + +/* Supprime toutes les références externes. */ +static void g_scan_arithmetic_operation_dispose(GScanArithmeticOperation *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_arithmetic_operation_finalize(GScanArithmeticOperation *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réalise une comparaison entre objets selon un critère précis. */ +static bool g_scan_arithmetic_operation_compare_rich(const GScanArithmeticOperation *, const GScanArithmeticOperation *, RichCmpOperation, bool *); + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_arithmetic_operation_reduce(const GScanArithmeticOperation *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une opération de relation entre expressions. */ +G_DEFINE_TYPE(GScanArithmeticOperation, g_scan_arithmetic_operation, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des opérations arithmétiques. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_arithmetic_operation_class_init(GScanArithmeticOperationClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_arithmetic_operation_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_arithmetic_operation_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)g_scan_arithmetic_operation_compare_rich; + expr->reduce = (reduce_expr_fc)g_scan_arithmetic_operation_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser. * +* * +* Description : Initialise une instance d'opération arithmétique. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_arithmetic_operation_init(GScanArithmeticOperation *op) +{ + op->left = NULL; + op->right = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_arithmetic_operation_dispose(GScanArithmeticOperation *op) +{ + g_clear_object(&op->left); + g_clear_object(&op->right); + + G_OBJECT_CLASS(g_scan_arithmetic_operation_parent_class)->dispose(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_arithmetic_operation_finalize(GScanArithmeticOperation *op) +{ + G_OBJECT_CLASS(g_scan_arithmetic_operation_parent_class)->finalize(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : operator = type d'opération arithmétique à représenter. * +* left = premier opérande concerné. * +* right = éventuel second opérande impliqué ou NULL. * +* * +* Description : Organise une opération arithmétique entre expressions. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_arithmetic_operation_new(ArithmeticExpressionOperator operator, GScanExpression *left, GScanExpression *right) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_ARITHMETIC_OPERATION, NULL); + + if (!g_scan_arithmetic_operation_create(G_SCAN_ARITHMETIC_OPERATION(result), operator, left, right)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser pleinement. * +* operator = type d'opération booléenne à représenter. * +* left = premier opérande concerné. * +* right = éventuel second opérande impliqué ou NULL. * +* * +* Description : Met en place une opération arithmétique entre expressions. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_arithmetic_operation_create(GScanArithmeticOperation *op, ArithmeticExpressionOperator operator, GScanExpression *left, GScanExpression *right) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(op), SRS_PENDING); + if (!result) goto exit; + + op->operator = operator; + + op->left = left; + g_object_ref(G_OBJECT(op->left)); + + op->right = right; + g_object_ref(G_OBJECT(op->right)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = premier objet à consulter pour une comparaison. * +* other = second objet à consulter pour une comparaison. * +* op = opération de comparaison à réaliser. * +* status = bilan des opérations de comparaison. [OUT] * +* * +* Description : Réalise une comparaison entre objets selon un critère précis.* +* * +* Retour : true si la comparaison a pu être effectuée, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_arithmetic_operation_compare_rich(const GScanArithmeticOperation *item, const GScanArithmeticOperation *other, RichCmpOperation op, bool *status) +{ + bool result; /* Etat à retourner */ + + result = g_type_is_a(G_TYPE_FROM_INSTANCE(other), G_TYPE_SCAN_ARITHMETIC_OPERATION); + if (!result) goto done; + + if (item->operator != other->operator) + { + result = compare_rich_integer_values_unsigned(item->operator, other->operator, op); + goto done; + } + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item), G_COMPARABLE_ITEM(other), RCO_EQ, status); + if (!result || STATUS_NOT_EQUAL(*status, op)) goto done; + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item->left), + G_COMPARABLE_ITEM(other->left), + op, status); + if (!result || STATUS_NOT_EQUAL(*status, op)) goto done; + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item->right), + G_COMPARABLE_ITEM(other->right), + op, status); + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_arithmetic_operation_reduce(const GScanArithmeticOperation *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_left; /* Expression réduite (gauche) */ + GScanExpression *new_right; /* Expression réduite (droite) */ + ScanReductionState state_left; /* Etat synthétisé #1 */ + ScanReductionState state_right; /* Etat synthétisé #2 */ + GScanLiteralExpression *op_left; /* Opérande gauche final */ + GScanLiteralExpression *op_right; /* Opérande droite final */ + LiteralValueType vtype_left; /* Type de valeur portée #1 */ + LiteralValueType vtype_right; /* Type de valeur portée #2 */ + long long val_1_s; /* Première valeur à traiter */ + unsigned long long val_1_u; /* Première valeur à traiter */ + long long val_2_s; /* Seconde valeur à traiter */ + unsigned long long val_2_u; /* Seconde valeur à traiter */ + LiteralValueType state_final; /* Nature de la valeur finale */ + long long reduced_s; /* Valeur réduite finale */ + unsigned long long reduced_u; /* Valeur réduite finale */ + + /* Réduction des éléments considérés */ + + new_left = NULL; + new_right = NULL; + + state_left = g_scan_expression_reduce(expr->left, ctx, scope, &new_left); + if (state_left == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + state_right = g_scan_expression_reduce(expr->right, ctx, scope, &new_right); + if (state_right == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Construction d'une réduction locale ? */ + + if (G_IS_SCAN_LITERAL_EXPRESSION(new_left) && G_IS_SCAN_LITERAL_EXPRESSION(new_right)) + { + /* Récupération de l'opérande de gauche */ + + op_left = G_SCAN_LITERAL_EXPRESSION(new_left); + vtype_left = g_scan_literal_expression_get_value_type(op_left); + + if (vtype_left == LVT_SIGNED_INTEGER) + { + if (!g_scan_literal_expression_get_signed_integer_value(op_left, &val_1_s)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + } + else if (vtype_left == LVT_UNSIGNED_INTEGER) + { + if (!g_scan_literal_expression_get_unsigned_integer_value(op_left, &val_1_u)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + } + else + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Récupération de l'opérande de droite */ + + op_right = G_SCAN_LITERAL_EXPRESSION(new_right); + vtype_right = g_scan_literal_expression_get_value_type(op_right); + + if (vtype_right == LVT_SIGNED_INTEGER) + { + if (!g_scan_literal_expression_get_signed_integer_value(op_right, &val_2_s)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + } + else if (vtype_right == LVT_UNSIGNED_INTEGER) + { + if (!g_scan_literal_expression_get_unsigned_integer_value(op_right, &val_2_u)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + } + else + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Partie des calculs */ + + result = SRS_REDUCED; + + switch (expr->operator) + { + case AEO_PLUS: + if (vtype_left == LVT_SIGNED_INTEGER) + { + if (vtype_right == LVT_SIGNED_INTEGER) + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_s + val_2_s; + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + if ((long long)val_2_u > val_1_s) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_s + (long long)val_2_u; + } + else + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_s + (long long)val_2_u; + } + + } + } + else + { + assert(vtype_left == LVT_UNSIGNED_INTEGER); + + if (vtype_right == LVT_SIGNED_INTEGER) + { + if ((long long)val_1_u > val_2_s) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = (long long)val_1_u + val_2_s; + } + else + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = (long long)val_1_u + val_2_s; + } + + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_u + val_2_u; + + } + } + break; + + case AEO_MINUS: + if (vtype_left == LVT_SIGNED_INTEGER) + { + if (vtype_right == LVT_SIGNED_INTEGER) + { + if (val_2_s < val_1_s) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_s - val_2_s; + } + else + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_s - val_2_s; + } + + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_s - (long long)val_2_u; + + } + } + else + { + assert(vtype_left == LVT_UNSIGNED_INTEGER); + + if (vtype_right == LVT_SIGNED_INTEGER) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = (long long)val_1_u - val_2_s; + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + if (val_1_u > val_2_u) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_u - val_2_u; + } + else + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_u - val_2_u; + } + + } + } + break; + + case AEO_MUL: + if (vtype_left == LVT_SIGNED_INTEGER) + { + if (vtype_right == LVT_SIGNED_INTEGER) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_s * val_2_s; + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_s * (long long)val_2_u; + + } + } + else + { + assert(vtype_left == LVT_UNSIGNED_INTEGER); + + if (vtype_right == LVT_SIGNED_INTEGER) + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = (long long)val_1_u * val_2_s; + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_u * val_2_u; + + } + } + break; + + case AEO_DIV: + if ((vtype_right == LVT_SIGNED_INTEGER && val_2_s == 0) + || (vtype_right == LVT_UNSIGNED_INTEGER && val_2_u == 0)) + { + result = SRS_UNRESOLVABLE; + break; + } + + if (vtype_left == LVT_SIGNED_INTEGER) + { + if (vtype_right == LVT_SIGNED_INTEGER) + { + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_s / val_2_s; + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + state_final = LVT_SIGNED_INTEGER; + reduced_s = val_1_s / (long long)val_2_u; + + } + } + else + { + assert(vtype_left == LVT_UNSIGNED_INTEGER); + + if (vtype_right == LVT_SIGNED_INTEGER) + { + state_final = LVT_SIGNED_INTEGER; + reduced_s = (long long)val_1_u / val_2_s; + } + else + { + assert(vtype_right == LVT_UNSIGNED_INTEGER); + + state_final = LVT_UNSIGNED_INTEGER; + reduced_u = val_1_u / val_2_u; + + } + } + break; + + case AEO_MOD: + result = SRS_UNRESOLVABLE; + /* FIXME + result = (val_2 != 0); + if (result) + reduced = val_1 % val_2; + */ + break; + + } + + if (result == SRS_REDUCED) + { + if (state_final == LVT_SIGNED_INTEGER) + *out = g_scan_literal_expression_new(LVT_SIGNED_INTEGER, &reduced_s); + else + { + assert(state_final == LVT_UNSIGNED_INTEGER); + *out = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, &reduced_u); + } + + } + + } + + /* Mise à jour de la progression ? */ + + else if (state_left == SRS_WAIT_FOR_SCAN || state_right == SRS_WAIT_FOR_SCAN) + { + if (new_left != expr->left || new_right != expr->right) + *out = g_scan_arithmetic_operation_new(expr->operator, new_left, new_right); + + result = SRS_WAIT_FOR_SCAN; + + } + + /* Cas des situations où les expressions ne sont pas exploitables (!) */ + else + { + assert(state_left == SRS_REDUCED && state_right == SRS_REDUCED); + + result = SRS_UNRESOLVABLE; + + } + + /* Sortie propre */ + + exit: + + g_clear_object(&new_left); + g_clear_object(&new_right); + + return result; + +} diff --git a/src/analysis/scan/exprs/arithmetic.h b/src/analysis/scan/exprs/arithmetic.h new file mode 100644 index 0000000..8a1e844 --- /dev/null +++ b/src/analysis/scan/exprs/arithmetic.h @@ -0,0 +1,67 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * arithmetic.h - prototypes pour la gestion des opérations arithmétiques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_ARITHMETIC_H +#define _ANALYSIS_SCAN_EXPRS_ARITHMETIC_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_ARITHMETIC_OPERATION g_scan_arithmetic_operation_get_type() +#define G_SCAN_ARITHMETIC_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_ARITHMETIC_OPERATION, GScanArithmeticOperation)) +#define G_IS_SCAN_ARITHMETIC_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_ARITHMETIC_OPERATION)) +#define G_SCAN_ARITHMETIC_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_ARITHMETIC_OPERATION, GScanArithmeticOperationClass)) +#define G_IS_SCAN_ARITHMETIC_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_ARITHMETIC_OPERATION)) +#define G_SCAN_ARITHMETIC_OPERATION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_ARITHMETIC_OPERATION, GScanArithmeticOperationClass)) + + +/* Opération arithmétique impliquant deux opérandes (instance) */ +typedef struct _GScanArithmeticOperation GScanArithmeticOperation; + +/* Opération arithmétique impliquant deux opérandes (classe) */ +typedef struct _GScanArithmeticOperationClass GScanArithmeticOperationClass; + + +/* Type d'opération arithmétique */ +typedef enum _ArithmeticExpressionOperator +{ + AEO_PLUS, /* Opération binaire "+" */ + AEO_MINUS, /* Opération binaire "-" */ + AEO_MUL, /* Opération binaire "*" */ + AEO_DIV, /* Opération binaire "\" */ + AEO_MOD, /* Opération binaire "%" */ + +} ArithmeticExpressionOperator; + + +/* Indique le type défini pour une opération arithmétique entre expressions. */ +GType g_scan_arithmetic_operation_get_type(void); + +/* Organise une opération arithmétique entre expressions. */ +GScanExpression *g_scan_arithmetic_operation_new(ArithmeticExpressionOperator, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_ARITHMETIC_H */ diff --git a/src/analysis/scan/exprs/call-int.h b/src/analysis/scan/exprs/call-int.h new file mode 100644 index 0000000..9646b95 --- /dev/null +++ b/src/analysis/scan/exprs/call-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * call-int.h - prototypes internes pour l'organisation d'un appel à un élément de scan enregistré + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_CALL_INT_H +#define _ANALYSIS_SCAN_EXPRS_CALL_INT_H + + +#include "call.h" + + +#include "access-int.h" + + + +/* Exécution d'une fonction auxiliaire d'analyse (instance) */ +struct _GScanPendingCall +{ + GScanNamedAccess parent; /* A laisser en premier */ + + GScanExpression **args; /* Arguments d'appel fournis */ + size_t count; /* Quantité de ces arguments */ + +}; + +/* Exécution d'une fonction auxiliaire d'analyse (classe) */ +struct _GScanPendingCallClass +{ + GScanNamedAccessClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une expression d'appel. */ +bool g_scan_pending_call_create(GScanPendingCall *, const sized_string_t *, GScanExpression **, size_t); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_CALL_INT_H */ diff --git a/src/analysis/scan/exprs/call.c b/src/analysis/scan/exprs/call.c new file mode 100644 index 0000000..3997ff6 --- /dev/null +++ b/src/analysis/scan/exprs/call.c @@ -0,0 +1,467 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * call.c - organisation d'un appel à un élément de scan enregistré + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "call.h" + + +#include <assert.h> +#include <malloc.h> +#include <string.h> + + +#include "call-int.h" +#include "../../../core/global.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des appels de fonction avec arguments. */ +static void g_scan_pending_call_class_init(GScanPendingCallClass *); + +/* Initialise une instance d'appel de fonction avec arguments. */ +static void g_scan_pending_call_init(GScanPendingCall *); + +/* Supprime toutes les références externes. */ +static void g_scan_pending_call_dispose(GScanPendingCall *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_pending_call_finalize(GScanPendingCall *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_pending_call_reduce(const GScanPendingCall *, GScanContext *, GScanScope *, GScanExpression **); + +/* Reproduit un accès en place dans une nouvelle instance. */ +static void g_scan_pending_call_copy(GScanPendingCall *, const GScanPendingCall *); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un appel de fonction enregistrée. */ +G_DEFINE_TYPE(GScanPendingCall, g_scan_pending_call, G_TYPE_SCAN_NAMED_ACCESS); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des appels de fonction avec arguments. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_call_class_init(GScanPendingCallClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + GScanNamedAccessClass *access; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_pending_call_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_pending_call_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)NULL; + expr->reduce = (reduce_expr_fc)g_scan_pending_call_reduce; + + access = G_SCAN_NAMED_ACCESS_CLASS(klass); + + access->copy = (copy_scan_access_fc)g_scan_pending_call_copy; + +} + + +/****************************************************************************** +* * +* Paramètres : call = instance à initialiser. * +* * +* Description : Initialise une instance d'appel de fonction avec arguments. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_call_init(GScanPendingCall *call) +{ + call->args = NULL; + call->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : call = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_call_dispose(GScanPendingCall *call) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < call->count; i++) + g_clear_object(&call->args[i]); + + G_OBJECT_CLASS(g_scan_pending_call_parent_class)->dispose(G_OBJECT(call)); + +} + + +/****************************************************************************** +* * +* Paramètres : call = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_call_finalize(GScanPendingCall *call) +{ + if (call->args != NULL) + free(call->args); + + G_OBJECT_CLASS(g_scan_pending_call_parent_class)->finalize(G_OBJECT(call)); + +} + + +/****************************************************************************** +* * +* Paramètres : target = désignation de l'objet d'appel à identifier. * +* args = éventuelle liste d'arguments à actionner. * +* count = quantité de ces arguments. * +* * +* Description : Organise un appel de fonction avec ses arguments. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_pending_call_new(const sized_string_t *target, GScanExpression **args, size_t count) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_PENDING_CALL, NULL); + + if (!g_scan_pending_call_create(G_SCAN_PENDING_CALL(result), target, args, count)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : call = instance à initialiser pleinement. * +* target = désignation de l'objet d'appel à identifier. * +* args = éventuelle liste d'arguments à actionner. * +* count = quantité de ces arguments. * +* * +* Description : Met en place une expression d'appel. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_pending_call_create(GScanPendingCall *call, const sized_string_t *target, GScanExpression **args, size_t count) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + + result = g_scan_named_access_create(G_SCAN_NAMED_ACCESS(call), target); + if (!result) goto exit; + + call->args = malloc(count * sizeof(GScanExpression *)); + call->count = count; + + for (i = 0; i < count; i++) + { + call->args[i] = args[i]; + g_object_ref(G_OBJECT(args[i])); + } + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_pending_call_reduce(const GScanPendingCall *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanNamedAccess *access; /* Autre vision de l'expression*/ + GScanRegisteredItem *resolved; /* Cible concrète obtenue */ + size_t i; /* Boucle de parcours #1 */ + GScanExpression *arg; /* Argument réduit à échanger */ + GScanExpression *new; /* Nouvelle réduction obtenue */ + ScanReductionState state; /* Etat synthétisé d'un élément*/ + size_t k; /* Boucle de parcours #2 */ + GScanExpression **new_args; /* Nouvelle séquence d'args. */ + GObject *final; /* Expression ou élément ? */ + bool valid; /* Validité de l'élément */ + GScanExpression *new_next; /* Nouvelle version du suivant */ + + access = G_SCAN_NAMED_ACCESS(expr); + + resolved = _g_scan_named_access_prepare_reduction(access, ctx, scope); + + if (resolved == NULL) + result = SRS_UNRESOLVABLE; + + else + { + result = SRS_PENDING; + + /* Actualisation nécessaire des arguments ? */ + + new_args = NULL; + + for (i = 0; i < expr->count; i++) + { + arg = expr->args[i]; + + state = g_scan_expression_reduce(arg, ctx, scope, &new); + if (state == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + break; + } + + if (state == SRS_WAIT_FOR_SCAN) + result = SRS_WAIT_FOR_SCAN; + + if (new != arg) + { + if (new_args == NULL) + { + new_args = calloc(expr->count, sizeof(GScanExpression *)); + + for (k = 0; k < i; k++) + { + new_args[k] = expr->args[k]; + g_object_ref(G_OBJECT(new_args[k])); + } + + } + + new_args[i] = new; + + } + + else + { + if (new_args != NULL) + new_args[i] = new; + + else + g_object_unref(G_OBJECT(new)); + + } + + } + + /* Suite des traitements */ + + if (result == SRS_WAIT_FOR_SCAN) + { + /** + * Si changement il y a eu... + */ + if (new_args != NULL) + { + *out = g_scan_pending_call_new(NULL, new_args, expr->count); + + /** + * Fonctionnement équivalent de : + * g_scan_named_access_set_base(G_SCAN_NAMED_ACCESS(*out), resolved); + */ + G_SCAN_NAMED_ACCESS(*out)->resolved = resolved; + g_object_ref(G_OBJECT(resolved)); + + if (G_SCAN_NAMED_ACCESS(expr)->next != NULL) + g_scan_named_access_attach_next(G_SCAN_NAMED_ACCESS(*out), G_SCAN_NAMED_ACCESS(expr)->next); + + } + + } + + else if (result == SRS_PENDING) + { + if (new_args == NULL) + valid = g_scan_registered_item_run_call(resolved, + expr->args, + expr->count, + ctx, scope, &final); + else + valid = g_scan_registered_item_run_call(resolved, + new_args, + expr->count, + ctx, scope, &final); + + if (valid && final != NULL) + { + /** + * Si le produit de l'appel à la fonction est une expression d'évaluation + * classique, alors ce produit constitue la réduction finale de la chaîne. + * + * Ce cas de figure ne se rencontre normalement qu'en bout de chaîne. + */ + if (!G_IS_SCAN_REGISTERED_ITEM(final)) + { + if (access->next != NULL) + result = SRS_UNRESOLVABLE; + + else + { + *out = G_SCAN_EXPRESSION(final); + g_object_ref(G_OBJECT(final)); + + result = SRS_REDUCED; + + } + + } + else + { + assert(access->next != NULL); + + new_next = g_scan_named_access_duplicate(access->next, G_SCAN_REGISTERED_ITEM(final)); + + result = g_scan_expression_reduce(new_next, ctx, scope, out); + + g_object_unref(G_OBJECT(new_next)); + + } + + } + + else + result = SRS_UNRESOLVABLE; + + g_clear_object(&final); + + } + + /* Libération locale des arguments reconstruits */ + + if (new_args != NULL) + { + for (i = 0; i < expr->count; i++) + g_clear_object(&new_args[i]); + } + + g_object_unref(G_OBJECT(resolved)); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = emplacement d'enregistrement à constituer. [OUT] * +* src = expression source à copier. * +* * +* Description : Reproduit un accès en place dans une nouvelle instance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_call_copy(GScanPendingCall *dest, const GScanPendingCall *src) +{ + GScanNamedAccessClass *class; /* Classe parente à solliciter */ + size_t i; /* Boucle de parcours */ + + class = G_SCAN_NAMED_ACCESS_CLASS(g_scan_pending_call_parent_class); + + class->copy(G_SCAN_NAMED_ACCESS(dest), G_SCAN_NAMED_ACCESS(src)); + + dest->args = malloc(src->count * sizeof(GScanExpression *)); + dest->count = src->count; + + for (i = 0; i < src->count; i++) + { + dest->args[i] = src->args[i]; + g_object_ref(G_OBJECT(src->args[i])); + } + +} diff --git a/src/analysis/scan/exprs/call.h b/src/analysis/scan/exprs/call.h new file mode 100644 index 0000000..c4d8964 --- /dev/null +++ b/src/analysis/scan/exprs/call.h @@ -0,0 +1,56 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * call.h - prototypes pour l'organisation d'un appel à un élément de scan enregistré + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_CALL_H +#define _ANALYSIS_SCAN_EXPRS_CALL_H + + +#include "../expr.h" +#include "../../../common/szstr.h" + + + +#define G_TYPE_SCAN_PENDING_CALL g_scan_pending_call_get_type() +#define G_SCAN_PENDING_CALL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_PENDING_CALL, GScanPendingCall)) +#define G_IS_SCAN_PENDING_CALL(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_PENDING_CALL)) +#define G_SCAN_PENDING_CALL_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_PENDING_CALL, GScanPendingCallClass)) +#define G_IS_SCAN_PENDING_CALL_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_PENDING_CALL)) +#define G_SCAN_PENDING_CALL_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_PENDING_CALL, GScanPendingCallClass)) + + +/* Exécution d'une fonction auxiliaire d'analyse (instance) */ +typedef struct _GScanPendingCall GScanPendingCall; + +/* Exécution d'une fonction auxiliaire d'analyse (classe) */ +typedef struct _GScanPendingCallClass GScanPendingCallClass; + + +/* Indique le type défini pour un appel de fonction enregistrée. */ +GType g_scan_pending_call_get_type(void); + +/* Organise un appel de fonction avec ses arguments. */ +GScanExpression *g_scan_pending_call_new(const sized_string_t *, GScanExpression **, size_t); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_CALL_H */ diff --git a/src/analysis/scan/exprs/extract-int.h b/src/analysis/scan/exprs/extract-int.h new file mode 100644 index 0000000..562e537 --- /dev/null +++ b/src/analysis/scan/exprs/extract-int.h @@ -0,0 +1,57 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * extract-int.h - prototypes internes pour l'organisation d'une extraction d'un élément d'une série interne + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_EXTRACT_INT_H +#define _ANALYSIS_SCAN_EXPRS_EXTRACT_INT_H + + +#include "extract.h" + + +#include "access-int.h" + + + +/* Extraction d'un élément donné au sein d'une série interne (instance) */ +struct _GScanPendingExtraction +{ + GScanNamedAccess parent; /* A laisser en premier */ + + GScanExpression *index; /* Arguments d'appel fournis */ + +}; + +/* Extraction d'un élément donné au sein d'une série interne (classe) */ +struct _GScanPendingExtractionClass +{ + GScanNamedAccessClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une expression d'extraction d'élément interne. */ +bool g_scan_pending_extraction_create(GScanPendingExtraction *, const sized_string_t *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_EXTRACT_INT_H */ diff --git a/src/analysis/scan/exprs/extract.c b/src/analysis/scan/exprs/extract.c new file mode 100644 index 0000000..b140ed9 --- /dev/null +++ b/src/analysis/scan/exprs/extract.c @@ -0,0 +1,396 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * extract.c - organisation d'une extraction d'un élément d'une série interne + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "extract.h" + + +#include <assert.h> +#include <string.h> + + +#include "extract-int.h" +#include "../../../core/global.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des extractions d'éléments internes. */ +static void g_scan_pending_extraction_class_init(GScanPendingExtractionClass *); + +/* Initialise une instance d'extraction d'élément interne. */ +static void g_scan_pending_extraction_init(GScanPendingExtraction *); + +/* Supprime toutes les références externes. */ +static void g_scan_pending_extraction_dispose(GScanPendingExtraction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_pending_extraction_finalize(GScanPendingExtraction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_pending_extraction_reduce(const GScanPendingExtraction *, GScanContext *, GScanScope *, GScanExpression **); + +/* Reproduit un accès en place dans une nouvelle instance. */ +static void g_scan_pending_extraction_copy(GScanPendingExtraction *, const GScanPendingExtraction *); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une extraction d'élément de série interne. */ +G_DEFINE_TYPE(GScanPendingExtraction, g_scan_pending_extraction, G_TYPE_SCAN_NAMED_ACCESS); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des extractions d'éléments internes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_extraction_class_init(GScanPendingExtractionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + GScanNamedAccessClass *access; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_pending_extraction_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_pending_extraction_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)NULL; + expr->reduce = (reduce_expr_fc)g_scan_pending_extraction_reduce; + + access = G_SCAN_NAMED_ACCESS_CLASS(klass); + + access->copy = (copy_scan_access_fc)g_scan_pending_extraction_copy; + +} + + +/****************************************************************************** +* * +* Paramètres : extract = instance à initialiser. * +* * +* Description : Initialise une instance d'extraction d'élément interne. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_extraction_init(GScanPendingExtraction *extract) +{ + extract->index = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : extract = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_extraction_dispose(GScanPendingExtraction *extract) +{ + g_clear_object(&extract->index); + + G_OBJECT_CLASS(g_scan_pending_extraction_parent_class)->dispose(G_OBJECT(extract)); + +} + + +/****************************************************************************** +* * +* Paramètres : extract = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_extraction_finalize(GScanPendingExtraction *extract) +{ + G_OBJECT_CLASS(g_scan_pending_extraction_parent_class)->finalize(G_OBJECT(extract)); + +} + + +/****************************************************************************** +* * +* Paramètres : target = désignation de l'objet d'appel à identifier. * +* index = indice de l'élément à extraire. * +* * +* Description : Organise l'extraction d'un élément d'une série interne. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_pending_extraction_new(const sized_string_t *target, GScanExpression *index) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_PENDING_EXTRACTION, NULL); + + if (!g_scan_pending_extraction_create(G_SCAN_PENDING_EXTRACTION(result), target, index)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : extract = instance à initialiser pleinement. * +* target = désignation de l'objet d'appel à identifier. * +* index = indice de l'élément à extraire. * +* * +* Description : Met en place une expression d'extraction d'élément interne. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_pending_extraction_create(GScanPendingExtraction *extract, const sized_string_t *target, GScanExpression *index) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_named_access_create(G_SCAN_NAMED_ACCESS(extract), target); + if (!result) goto exit; + + extract->index = index; + g_object_ref(G_OBJECT(index)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_pending_extraction_reduce(const GScanPendingExtraction *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanNamedAccess *access; /* Autre vision de l'expression*/ + GScanRegisteredItem *resolved; /* Cible concrète obtenue */ + GScanExpression *new; /* Nouvelle réduction obtenue */ + GObject *final; /* Expression ou élément ? */ + GScanExpression *new_next; /* Nouvelle version du suivant */ + + access = G_SCAN_NAMED_ACCESS(expr); + + resolved = _g_scan_named_access_prepare_reduction(access, ctx, scope); + + if (resolved == NULL) + result = SRS_UNRESOLVABLE; + + else + { + /* Actualisation nécessaire des arguments ? */ + + result = g_scan_expression_reduce(expr->index, ctx, scope, &new); + + /* Suite des traitements */ + + if (result == SRS_WAIT_FOR_SCAN) + { + /** + * Si changement il y a eu... + */ + if (new != expr->index) + { + *out = g_scan_pending_extraction_new(NULL, new); + + /** + * Fonctionnement équivalent de : + * g_scan_named_access_set_base(G_SCAN_NAMED_ACCESS(*out), resolved); + */ + G_SCAN_NAMED_ACCESS(*out)->resolved = resolved; + g_object_ref(G_OBJECT(resolved)); + + if (G_SCAN_NAMED_ACCESS(expr)->next != NULL) + g_scan_named_access_attach_next(G_SCAN_NAMED_ACCESS(*out), G_SCAN_NAMED_ACCESS(expr)->next); + + } + + } + + else if (result == SRS_REDUCED) + { + final = g_scan_registered_item_extract_at(resolved, new, ctx, scope); + + if (final != NULL) + { + /** + * Si le produit de l'appel à la fonction est une expression d'évaluation + * classique, alors ce produit constitue la réduction finale de la chaîne. + * + * Ce cas de figure ne se rencontre normalement qu'en bout de chaîne. + */ + if (!G_IS_SCAN_REGISTERED_ITEM(final)) + { + if (access->next != NULL) + result = SRS_UNRESOLVABLE; + + else + { + *out = G_SCAN_EXPRESSION(final); + g_object_ref(G_OBJECT(final)); + + result = SRS_REDUCED; + + } + + } + else + { + if (access->next != NULL) + { + new_next = g_scan_named_access_duplicate(access->next, G_SCAN_REGISTERED_ITEM(final)); + + result = g_scan_expression_reduce(new_next, ctx, scope, out); + + g_object_unref(G_OBJECT(new_next)); + + } + + /** + * Le cas ci-après est typique de l'extension Kaitai : field[n] + * renvoie vers une instance GScanRegisteredItem (GKaitaiBrowser). + * + * Il n'y a donc pas d'expression en jeu, et l'élément est le dernier + * de la liste. + */ + else + { + if (g_scan_registered_item_reduce(G_SCAN_REGISTERED_ITEM(final), ctx, scope, out)) + result = SRS_REDUCED; + else + result = SRS_UNRESOLVABLE; + + } + + } + + } + + else + result = SRS_UNRESOLVABLE; + + g_clear_object(&final); + + } + + /* Libération locale des arguments reconstruits */ + + g_clear_object(&new); + + g_object_unref(G_OBJECT(resolved)); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = emplacement d'enregistrement à constituer. [OUT] * +* src = expression source à copier. * +* * +* Description : Reproduit un accès en place dans une nouvelle instance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pending_extraction_copy(GScanPendingExtraction *dest, const GScanPendingExtraction *src) +{ + GScanNamedAccessClass *class; /* Classe parente à solliciter */ + + class = G_SCAN_NAMED_ACCESS_CLASS(g_scan_pending_extraction_parent_class); + + class->copy(G_SCAN_NAMED_ACCESS(dest), G_SCAN_NAMED_ACCESS(src)); + + dest->index = src->index; + g_object_ref(G_OBJECT(src->index)); + +} diff --git a/src/analysis/scan/exprs/extract.h b/src/analysis/scan/exprs/extract.h new file mode 100644 index 0000000..8ed1cfa --- /dev/null +++ b/src/analysis/scan/exprs/extract.h @@ -0,0 +1,56 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * extract.h - prototypes pour l'organisation d'une extraction d'un élément d'une série interne + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_EXTRACT_H +#define _ANALYSIS_SCAN_EXPRS_EXTRACT_H + + +#include "../expr.h" +#include "../../../common/szstr.h" + + + +#define G_TYPE_SCAN_PENDING_EXTRACTION g_scan_pending_extraction_get_type() +#define G_SCAN_PENDING_EXTRACTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_PENDING_EXTRACTION, GScanPendingExtraction)) +#define G_IS_SCAN_PENDING_EXTRACTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_PENDING_EXTRACTION)) +#define G_SCAN_PENDING_EXTRACTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_PENDING_EXTRACTION, GScanPendingExtractionClass)) +#define G_IS_SCAN_PENDING_EXTRACTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_PENDING_EXTRACTION)) +#define G_SCAN_PENDING_EXTRACTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_PENDING_EXTRACTION, GScanPendingExtractionClass)) + + +/* Extraction d'un élément donné au sein d'une série interne (instance) */ +typedef struct _GScanPendingExtraction GScanPendingExtraction; + +/* Extraction d'un élément donné au sein d'une série interne (classe) */ +typedef struct _GScanPendingExtractionClass GScanPendingExtractionClass; + + +/* Indique le type défini pour une extraction d'élément de série interne. */ +GType g_scan_pending_extraction_get_type(void); + +/* Organise l'extraction d'un élément d'une série interne. */ +GScanExpression *g_scan_pending_extraction_new(const sized_string_t *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_EXTRACT_H */ diff --git a/src/analysis/scan/exprs/handler-int.h b/src/analysis/scan/exprs/handler-int.h new file mode 100644 index 0000000..e051b30 --- /dev/null +++ b/src/analysis/scan/exprs/handler-int.h @@ -0,0 +1,68 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * handler-int.h - prototypes internes pour la manipulation des correspondances établies lors d'un scan + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_HANDLER_INT_H +#define _ANALYSIS_SCAN_EXPRS_HANDLER_INT_H + + +#include "handler.h" + + +#include "../expr-int.h" + + + +/* Manipulation des correspondances établies lors d'un scan de binaire (instance) */ +struct _GScanPatternHandler +{ + GScanExpression parent; /* A laisser en premier */ + + union + { + const GSearchPattern **patterns; /* Motifs associés */ + GSearchPattern **ref_patterns; /* Motifs associés */ + }; + size_t count; /* Nombre de ces motifs */ + bool shared; /* Définition de propriété */ + + ScanHandlerType type; /* Manipulation attendue */ + +}; + +/* Manipulation des correspondances établies lors d'un scan de binaire (classe) */ +struct _GScanPatternHandlerClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une manipulation de correspondances établies. */ +bool g_scan_pattern_handler_create_shared(GScanPatternHandler *, const GSearchPattern ** const, size_t, ScanHandlerType); + +/* Met en place une manipulation de correspondances établies. */ +bool g_scan_pattern_handler_create_and_ref(GScanPatternHandler *, GSearchPattern ** const, size_t, ScanHandlerType); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_HANDLER_INT_H */ diff --git a/src/analysis/scan/exprs/handler.c b/src/analysis/scan/exprs/handler.c new file mode 100644 index 0000000..2706dae --- /dev/null +++ b/src/analysis/scan/exprs/handler.c @@ -0,0 +1,622 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * handler.c - manipulation des correspondances établies lors d'un scan + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "handler.h" + + +#include <assert.h> + + +#include "literal.h" +#include "handler-int.h" +#include "../matches/bytes.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des manipulations de correspondances. */ +static void g_scan_pattern_handler_class_init(GScanPatternHandlerClass *); + +/* Initialise une instance de manipulation de correspondances. */ +static void g_scan_pattern_handler_init(GScanPatternHandler *); + +/* Supprime toutes les références externes. */ +static void g_scan_pattern_handler_dispose(GScanPatternHandler *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_pattern_handler_finalize(GScanPatternHandler *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_pattern_handler_reduce(const GScanPatternHandler *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réduit une expression à une forme booléenne. */ +static bool g_scan_pattern_handler_reduce_to_boolean(const GScanPatternHandler *, GScanContext *, GScanScope *, GScanExpression **); + +/* Dénombre les éléments portés par une expression. */ +static bool g_scan_pattern_handler_count_items(const GScanPatternHandler *, GScanContext *, size_t *); + +/* Fournit un élément donné issu d'un ensemble constitué. */ +static bool g_scan_pattern_handler_get_item(const GScanPatternHandler *, size_t, GScanContext *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une manipulation de correspondances établies lors d'un scan. */ +G_DEFINE_TYPE(GScanPatternHandler, g_scan_pattern_handler, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des manipulations de correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pattern_handler_class_init(GScanPatternHandlerClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_pattern_handler_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_pattern_handler_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->reduce = (reduce_expr_fc)g_scan_pattern_handler_reduce; + expr->reduce_to_bool = (reduce_expr_to_bool_fc)g_scan_pattern_handler_reduce_to_boolean; + expr->count = (count_scan_expr_fc)g_scan_pattern_handler_count_items; + expr->get = (get_scan_expr_fc)g_scan_pattern_handler_get_item; + +} + + +/****************************************************************************** +* * +* Paramètres : handler = instance à initialiser. * +* * +* Description : Initialise une instance de manipulation de correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pattern_handler_init(GScanPatternHandler *handler) +{ + handler->patterns = NULL; + handler->count = 0; + handler->shared = true; + + handler->type = SHT_RAW; + +} + + +/****************************************************************************** +* * +* Paramètres : handler = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pattern_handler_dispose(GScanPatternHandler *handler) +{ + size_t i; /* Boucle de parcours */ + + if (!handler->shared) + for (i = 0; i < handler->count; i++) + g_clear_object(&handler->ref_patterns[i]); + + G_OBJECT_CLASS(g_scan_pattern_handler_parent_class)->dispose(G_OBJECT(handler)); + +} + + +/****************************************************************************** +* * +* Paramètres : handler = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_pattern_handler_finalize(GScanPatternHandler *handler) +{ + if (handler->patterns != NULL) + free(handler->patterns); + + G_OBJECT_CLASS(g_scan_pattern_handler_parent_class)->finalize(G_OBJECT(handler)); + +} + + +/****************************************************************************** +* * +* Paramètres : patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* type = type de manipulation attendue. * +* * +* Description : Met en place une manipulation de correspondances établies. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_pattern_handler_new_shared(const GSearchPattern ** const patterns, size_t count, ScanHandlerType type) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_PATTERN_HANDLER, NULL); + + if (!g_scan_pattern_handler_create_shared(G_SCAN_PATTERN_HANDLER(result), patterns, count, type)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : handler = instance à initialiser pleinement. * +* patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* type = type de manipulation attendue. * +* * +* Description : Met en place une manipulation de correspondances établies. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_pattern_handler_create_shared(GScanPatternHandler *handler, const GSearchPattern ** const patterns, size_t count, ScanHandlerType type) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(handler), SRS_WAIT_FOR_SCAN); + if (!result) goto exit; + + handler->patterns = malloc(count * sizeof(GSearchPattern *)); + handler->count = count; + + memcpy(handler->patterns, patterns, count * sizeof(GSearchPattern *)); + + handler->shared = true; + + handler->type = type; + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* type = type de manipulation attendue. * +* * +* Description : Met en place une manipulation de correspondances établies. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_pattern_handler_new(GSearchPattern ** const patterns, size_t count, ScanHandlerType type) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_PATTERN_HANDLER, NULL); + + if (!g_scan_pattern_handler_create_and_ref(G_SCAN_PATTERN_HANDLER(result), patterns, count, type)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : handler = instance à initialiser pleinement. * +* patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* type = type de manipulation attendue. * +* * +* Description : Met en place une manipulation de correspondances établies. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_pattern_handler_create_and_ref(GScanPatternHandler *handler, GSearchPattern ** const patterns, size_t count, ScanHandlerType type) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(handler), SRS_WAIT_FOR_SCAN); + if (!result) goto exit; + + handler->patterns = malloc(count * sizeof(GSearchPattern *)); + handler->count = count; + + memcpy(handler->patterns, patterns, count * sizeof(GSearchPattern *)); + + for (i = 0; i < count; i++) + g_object_ref(G_OBJECT(patterns[i])); + + handler->shared = false; + + handler->type = type; + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : handler = instance à initialiser pleinement. * +* * +* Description : Indique le type de manipulation de correspondances spécifié. * +* * +* Retour : Type de manipulation de correspondances représentée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +ScanHandlerType g_scan_pattern_handler_get_handler_type(const GScanPatternHandler *handler) +{ + ScanHandlerType result; /* Nature à retourner */ + + result = handler->type; + + return result; + +} + + +#if 0 /* FIXME */ + +/****************************************************************************** +* * +* Paramètres : handler = instance à initialiser pleinement. * +* ctx = contexte de suivi de l'analyse courante. * +* count = quantité de correspondances enregistrées. [OUT] * +* * +* Description : Fournit la liste de toutes les correspondances représentées. * +* * +* Retour : Liste courante de correspondances établies. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanMatch **g_scan_pattern_handler_get_all_matches(const GScanPatternHandler *handler, GScanContext *ctx, size_t *count) +{ + GScanMatch **result; /* Liste à retourner */ + size_t used; /* Indice pour le stockage */ + size_t i; /* Boucle de parcours #1 */ + size_t partial; /* Décompte partiel */ + const GScanMatch **matches; /* Correspondances en place */ + size_t k; /* Boucle de parcours #2 */ + + result = NULL; + + if (!g_scan_pattern_handler_count_items(handler, ctx, count)) + { + *count = 0; + goto exit; + } + + if (*count == 0) + goto exit; + + result = malloc(*count * sizeof(GScanMatch *)); + + used = 0; + + for (i = 0; i < handler->count; i++) + { + matches = g_scan_context_get_full_matches(ctx, handler->patterns[i], &partial); + + for (k = 0; k < partial; k++) + { + result[used++] = matches[k]; + g_object_ref(G_OBJECT(matches[k])); + } + + } + + exit: + + return result; + +} +#endif + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_pattern_handler_reduce(const GScanPatternHandler *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + size_t count; /* Quantité de correspondances */ + + if (g_scan_context_is_scan_done(ctx)) + { + if (expr->type == SHT_COUNTER) + { + if (!g_scan_pattern_handler_count_items(expr, ctx, &count)) + result = SRS_UNRESOLVABLE; + + else + { + result = SRS_REDUCED; + *out = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, (unsigned long long []){ count }); + } + + } + + else + result = SRS_REDUCED; + + } + + else + result = SRS_WAIT_FOR_SCAN; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme booléenne. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_pattern_handler_reduce_to_boolean(const GScanPatternHandler *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + size_t count; /* Quantité de correspondances */ + + result = g_scan_pattern_handler_count_items(expr, ctx, &count); + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ count > 0 }); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* count = quantité d'éléments déterminée. [OUT] * +* * +* Description : Dénombre les éléments portés par une expression. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_pattern_handler_count_items(const GScanPatternHandler *expr, GScanContext *ctx, size_t *count) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + + result = true; + + assert(g_scan_context_is_scan_done(ctx)); + + *count = 0; + + for (i = 0; i < expr->count; i++) + *count += g_scan_context_count_full_matches(ctx, expr->patterns[i]); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* index = indice de l'élément à transférer. * +* ctx = contexte de suivi de l'analyse courante. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Fournit un élément donné issu d'un ensemble constitué. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_pattern_handler_get_item(const GScanPatternHandler *expr, size_t index, GScanContext *ctx, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + size_t count; /* Quantité de correspondances */ + GScanMatches *matches; /* Correspondances d'un motif */ + const match_area_t *area; /* Zone de correspondance */ + GBinContent *content; /* Contenu binaire à relire */ + vmpa2t pos; /* Tête de lecture */ + const bin_t *data; /* Accès aux données brutes */ + sized_string_t binary; /* Conversion de formats */ + + result = false; + + assert(g_scan_context_is_scan_done(ctx)); + + /* Identification du motif concerné */ + + for (i = 0; i < expr->count; i++) + { + count = g_scan_context_count_full_matches(ctx, expr->patterns[i]); + + if (index < count) + break; + else + index -= count; + + } + + if (i == expr->count) goto done; + + /* Identification de la correspondance concernée */ + + matches = g_scan_context_get_full_matches(ctx, expr->patterns[i]); + if (matches == NULL) goto done; + + area = g_scan_bytes_matches_get(G_SCAN_BYTES_MATCHES(matches), index); + if (area == NULL) goto done_with_matches; + + /* Traitement adapté de la requête */ + + switch (expr->type) + { + case SHT_RAW: + content = g_scan_context_get_content(ctx); + + init_vmpa(&pos, area->start, VMPA_NO_VIRTUAL); + + data = g_binary_content_get_raw_access(content, &pos, area->end - area->start); + + binary.static_bin_data = data; + binary.len = area->end - area->start; + + *out = g_scan_literal_expression_new(LVT_STRING, &binary); + + g_object_unref(G_OBJECT(content)); + result = true; + break; + + case SHT_COUNTER: + assert(false); + break; + + case SHT_START: + *out = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ area->start }); + result = true; + break; + + case SHT_LENGTH: + *out = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ area->end - area->start }); + result = true; + break; + + case SHT_END: + *out = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ area->end }); + result = true; + break; + + } + + done_with_matches: + + g_object_unref(G_OBJECT(matches)); + + done: + + return result; + +} diff --git a/src/analysis/scan/exprs/handler.h b/src/analysis/scan/exprs/handler.h new file mode 100644 index 0000000..a1ddf98 --- /dev/null +++ b/src/analysis/scan/exprs/handler.h @@ -0,0 +1,80 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * handler.h - prototypes pour la manipulation des correspondances établies lors d'un scan + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_HANDLER_H +#define _ANALYSIS_SCAN_EXPRS_HANDLER_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_PATTERN_HANDLER g_scan_pattern_handler_get_type() +#define G_SCAN_PATTERN_HANDLER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_PATTERN_HANDLER, GScanPatternHandler)) +#define G_IS_SCAN_PATTERN_HANDLER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_PATTERN_HANDLER)) +#define G_SCAN_PATTERN_HANDLER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_PATTERN_HANDLER, GScanPatternHandlerClass)) +#define G_IS_SCAN_PATTERN_HANDLER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_PATTERN_HANDLER)) +#define G_SCAN_PATTERN_HANDLER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_PATTERN_HANDLER, GScanPatternHandlerClass)) + + +/* Manipulation des correspondances établies lors d'un scan de binaire (instance) */ +typedef struct _GScanPatternHandler GScanPatternHandler; + +/* Manipulation des correspondances établies lors d'un scan de binaire (classe) */ +typedef struct _GScanPatternHandlerClass GScanPatternHandlerClass; + + +/* Type de manipulation représentée */ +typedef enum _ScanHandlerType +{ + SHT_RAW, /* Correspondances brutes */ + SHT_COUNTER, /* Dénombrement de résultats */ + SHT_START, /* Départs de correspondances */ + SHT_LENGTH, /* Taille de correspondances */ + SHT_END, /* Fins de correspondances */ + +} ScanHandlerType; + + +/* Indique le type défini pour une manipulation de correspondances établies lors d'un scan. */ +GType g_scan_pattern_handler_get_type(void); + +/* Met en place une manipulation de correspondances établies. */ +GScanExpression *g_scan_pattern_handler_new_shared(const GSearchPattern ** const, size_t, ScanHandlerType); + +/* Met en place une manipulation de correspondances établies. */ +GScanExpression *g_scan_pattern_handler_new(GSearchPattern ** const, size_t, ScanHandlerType); + +/* Indique le type de manipulation de correspondances spécifié. */ +ScanHandlerType g_scan_pattern_handler_get_handler_type(const GScanPatternHandler *); + +#if 0 /* FIXME */ + +/* Fournit la liste de toutes les correspondances représentées. */ +GScanMatch **g_scan_pattern_handler_get_all_matches(const GScanPatternHandler *, GScanContext *, size_t *); + +#endif + + + +#endif /* _ANALYSIS_SCAN_EXPRS_HANDLER_H */ diff --git a/src/analysis/scan/exprs/intersect-int.h b/src/analysis/scan/exprs/intersect-int.h new file mode 100644 index 0000000..83e4251 --- /dev/null +++ b/src/analysis/scan/exprs/intersect-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * intersect-int.h - prototypes internes pour l'intersection d'ensembles aux types indentiques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_INTERSECT_INT_H +#define _ANALYSIS_SCAN_EXPRS_INTERSECT_INT_H + + +#include "intersect.h" + + +#include "../expr-int.h" + + + +/* Opération d'intersection entre deux ensembles (instance) */ +struct _GScanSetsIntersection +{ + GScanExpression parent; /* A laisser en premier */ + + GScanExpression *first; /* Expression impactée #1 */ + GScanExpression *second; /* Expression impactée #2 */ + +}; + +/* Opération d'intersection entre deux ensembles (classe) */ +struct _GScanSetsIntersectionClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une expression d'opération booléenne. */ +bool g_scan_sets_intersection_create(GScanSetsIntersection *, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_INTERSECT_INT_H */ diff --git a/src/analysis/scan/exprs/intersect.c b/src/analysis/scan/exprs/intersect.c new file mode 100644 index 0000000..c56d28c --- /dev/null +++ b/src/analysis/scan/exprs/intersect.c @@ -0,0 +1,290 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * intersect.c - intersection d'ensembles aux types indentiques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "intersect.h" + + +#include <assert.h> + + +#include "intersect-int.h" +#include "literal.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des intersections entre deux ensembles. */ +static void g_scan_sets_intersection_class_init(GScanSetsIntersectionClass *); + +/* Initialise une instance d'intersection entre deux ensembles. */ +static void g_scan_sets_intersection_init(GScanSetsIntersection *); + +/* Supprime toutes les références externes. */ +static void g_scan_sets_intersection_dispose(GScanSetsIntersection *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_sets_intersection_finalize(GScanSetsIntersection *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_sets_intersection_reduce(const GScanSetsIntersection *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une intersection entre deux ensembles. */ +G_DEFINE_TYPE(GScanSetsIntersection, g_scan_sets_intersection, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des intersections entre deux ensembles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_sets_intersection_class_init(GScanSetsIntersectionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_sets_intersection_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_sets_intersection_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->reduce = (reduce_expr_fc)g_scan_sets_intersection_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser. * +* * +* Description : Initialise une instance d'intersection entre deux ensembles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_sets_intersection_init(GScanSetsIntersection *inter) +{ + inter->first = NULL; + inter->second = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : inter = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_sets_intersection_dispose(GScanSetsIntersection *inter) +{ + g_clear_object(&inter->first); + g_clear_object(&inter->second); + + G_OBJECT_CLASS(g_scan_sets_intersection_parent_class)->dispose(G_OBJECT(inter)); + +} + + +/****************************************************************************** +* * +* Paramètres : inter = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_sets_intersection_finalize(GScanSetsIntersection *inter) +{ + G_OBJECT_CLASS(g_scan_sets_intersection_parent_class)->finalize(G_OBJECT(inter)); + +} + + +/****************************************************************************** +* * +* Paramètres : type = type d'opération booléenne à représenter. * +* first = premier élément concerné. * +* second = second élément concerné. * +* * +* Description : Organise une intersection entre deux ensembles. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_sets_intersection_new(GScanExpression *first, GScanExpression *second) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_SETS_INTERSECTION, NULL); + + if (!g_scan_sets_intersection_create(G_SCAN_SETS_INTERSECTION(result), first, second)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : inter = instance à initialiser pleinement. * +* first = premier élément concerné. * +* second = second élément concerné. * +* * +* Description : Met en place une expression d'opération booléenne. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_sets_intersection_create(GScanSetsIntersection *inter, GScanExpression *first, GScanExpression *second) +{ + bool result; /* Bilan à retourner */ + + result = true; + + inter->first = first; + g_object_ref(G_OBJECT(first)); + + inter->second = second; + g_object_ref(G_OBJECT(second)); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_sets_intersection_reduce(const GScanSetsIntersection *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_first; /* Nouvelle réduction #1 */ + GScanExpression *new_second; /* Nouvelle réduction #2 */ + ScanReductionState state_first; /* Etat synthétisé #1 */ + ScanReductionState state_second; /* Etat synthétisé #2 */ + + new_first = NULL; + new_second = NULL; + + state_first = g_scan_expression_reduce(expr->first, ctx, scope, &new_first); + if (state_first == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + state_second = g_scan_expression_reduce(expr->second, ctx, scope, &new_second); + if (state_second == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (state_first == SRS_WAIT_FOR_SCAN || state_second == SRS_WAIT_FOR_SCAN) + { + if (new_first != expr->first || new_second != expr->second) + *out = g_scan_sets_intersection_new(new_first, new_second); + + result = SRS_WAIT_FOR_SCAN; + + } + + else + { + assert(state_first == SRS_REDUCED && state_second == SRS_REDUCED); + + *out = g_scan_expression_intersect(new_first, new_second, ctx, scope); + + result = (*out != NULL ? SRS_REDUCED : SRS_UNRESOLVABLE); + + } + + exit: + + g_clear_object(&new_first); + g_clear_object(&new_second); + + return result; + +} diff --git a/src/analysis/scan/exprs/intersect.h b/src/analysis/scan/exprs/intersect.h new file mode 100644 index 0000000..56efdff --- /dev/null +++ b/src/analysis/scan/exprs/intersect.h @@ -0,0 +1,55 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * intersect.h - prototypes pour l'intersection d'ensembles aux types indentiques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_INTERSECT_H +#define _ANALYSIS_SCAN_EXPRS_INTERSECT_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_SETS_INTERSECTION g_scan_sets_intersection_get_type() +#define G_SCAN_SETS_INTERSECTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_SETS_INTERSECTION, GScanSetsIntersection)) +#define G_IS_SCAN_SETS_INTERSECTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_SETS_INTERSECTION)) +#define G_SCAN_SETS_INTERSECTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_SETS_INTERSECTION, GScanSetsIntersectionClass)) +#define G_IS_SCAN_SETS_INTERSECTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_SETS_INTERSECTION)) +#define G_SCAN_SETS_INTERSECTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_SETS_INTERSECTION, GScanSetsIntersectionClass)) + + +/* Opération d'intersection entre deux ensembles (instance) */ +typedef struct _GScanSetsIntersection GScanSetsIntersection; + +/* Opération d'intersection entre deux ensembles (classe) */ +typedef struct _GScanSetsIntersectionClass GScanSetsIntersectionClass; + + +/* Indique le type défini pour une intersection entre deux ensembles. */ +GType g_scan_sets_intersection_get_type(void); + +/* Organise une intersection entre deux ensembles. */ +GScanExpression *g_scan_sets_intersection_new(GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_INTERSECT_H */ diff --git a/src/analysis/scan/exprs/item-int.h b/src/analysis/scan/exprs/item-int.h new file mode 100644 index 0000000..56b159a --- /dev/null +++ b/src/analysis/scan/exprs/item-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * item-int.h - prototypes internes pour la récupération d'un élément à partir d'une série + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_ITEM_INT_H +#define _ANALYSIS_SCAN_EXPRS_ITEM_INT_H + + +#include "item.h" + + +#include "../expr-int.h" + + + +/* Accès à un élément donné d'une série établie (instance) */ +struct _GScanSetItem +{ + GScanExpression parent; /* A laisser en premier */ + + GScanExpression *set; /* Série d'éléments à consulter*/ + GScanExpression *index; /* Indice de l'élément visé */ + +}; + +/* Accès à un élément donné d'une série établie (classe) */ +struct _GScanSetItemClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un accès à un élément donné d'une série. */ +bool g_scan_set_item_create(GScanSetItem *, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_ITEM_INT_H */ diff --git a/src/analysis/scan/exprs/item.c b/src/analysis/scan/exprs/item.c new file mode 100644 index 0000000..a5a6fdf --- /dev/null +++ b/src/analysis/scan/exprs/item.c @@ -0,0 +1,353 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * item.c - récupération d'un élément à partir d'une série + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "set.h" + + +#include <assert.h> + + +#include "literal.h" +#include "item-int.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des accès à un élément de série. */ +static void g_scan_set_item_class_init(GScanSetItemClass *); + +/* Initialise une instance d'accès à un élément de série. */ +static void g_scan_set_item_init(GScanSetItem *); + +/* Supprime toutes les références externes. */ +static void g_scan_set_item_dispose(GScanSetItem *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_set_item_finalize(GScanSetItem *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_set_item_reduce(const GScanSetItem *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour la récupération d'un élément à partir d'une série. */ +G_DEFINE_TYPE(GScanSetItem, g_scan_set_item, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des accès à un élément de série. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_item_class_init(GScanSetItemClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_set_item_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_set_item_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->reduce = (reduce_expr_fc)g_scan_set_item_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance à initialiser. * +* * +* Description : Initialise une instance d'accès à un élément de série. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_item_init(GScanSetItem *item) +{ + item->set = NULL; + item->index = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_item_dispose(GScanSetItem *item) +{ + g_clear_object(&item->set); + g_clear_object(&item->index); + + G_OBJECT_CLASS(g_scan_set_item_parent_class)->dispose(G_OBJECT(item)); + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_item_finalize(GScanSetItem *item) +{ + G_OBJECT_CLASS(g_scan_set_item_parent_class)->finalize(G_OBJECT(item)); + +} + + +/****************************************************************************** +* * +* Paramètres : set = ensemble d'éléments à considérer. * +* index = indice de l'élément à viser. * +* * +* Description : Met en place un accès à un élément donné d'une série. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_set_item_new(GScanExpression *set, GScanExpression *index) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_SET_ITEM, NULL); + + if (!g_scan_set_item_create(G_SCAN_SET_ITEM(result), set, index)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance à initialiser pleinement. * +* set = ensemble d'éléments à considérer. * +* index = indice de l'élément à viser. * +* * +* Description : Met en place un accès à un élément donné d'une série. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_set_item_create(GScanSetItem *item, GScanExpression *set, GScanExpression *index) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(item), SRS_PENDING); + if (!result) goto exit; + + item->set = set; + g_object_ref(G_OBJECT(set)); + + item->index = index; + g_object_ref(G_OBJECT(index)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_set_item_reduce(const GScanSetItem *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_set; /* Expression réduite (série) */ + GScanExpression *new_index; /* Expression réduite (indice) */ + ScanReductionState state_set; /* Etat synthétisé #1 */ + ScanReductionState state_index; /* Etat synthétisé #2 */ + GScanLiteralExpression *op_index; /* Indice d'accès final */ + LiteralValueType vtype; /* Type de valeur portée */ + long long val_s; /* Valeur de l'indice (signée) */ + unsigned long long val_u; /* Valeur de l'indice (!signée)*/ + bool status; /* Statut final de récupération*/ + + /* Réduction des éléments considérés */ + + new_set = NULL; + new_index = NULL; + + state_set = g_scan_expression_reduce(expr->set, ctx, scope, &new_set); + if (state_set == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + state_index = g_scan_expression_reduce(expr->index, ctx, scope, &new_index); + if (state_index == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Validation de la nature des éléments en jeu */ + + if (state_set == SRS_REDUCED && !g_scan_expression_handle_set_features(new_set)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (state_index == SRS_REDUCED && !G_IS_SCAN_LITERAL_EXPRESSION(new_index)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Tentative d'accès à un élément de série */ + + if (state_set == SRS_REDUCED && state_index == SRS_REDUCED) + { + op_index = G_SCAN_LITERAL_EXPRESSION(new_index); + vtype = g_scan_literal_expression_get_value_type(op_index); + + if (vtype == LVT_SIGNED_INTEGER) + { + if (!g_scan_literal_expression_get_signed_integer_value(op_index, &val_s)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (val_s < 0) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + status = g_scan_expression_get_item(expr->set, val_s, ctx, out); + + } + + else if (vtype == LVT_UNSIGNED_INTEGER) + { + if (!g_scan_literal_expression_get_unsigned_integer_value(op_index, &val_u)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + status = g_scan_expression_get_item(expr->set, val_u, ctx, out); + + } + + else + status = false; + + result = (status ? SRS_REDUCED : SRS_UNRESOLVABLE); + + } + + /* Mise à jour de la progression ? */ + + else + { + assert(state_set == SRS_WAIT_FOR_SCAN || state_index == SRS_WAIT_FOR_SCAN); + + if (new_set != expr->set || new_index != expr->index) + *out = g_scan_set_item_new(new_set, new_index); + + result = SRS_WAIT_FOR_SCAN; + + } + + /* Sortie propre */ + + exit: + + g_clear_object(&new_set); + g_clear_object(&new_index); + + return result; + +} diff --git a/src/analysis/scan/exprs/item.h b/src/analysis/scan/exprs/item.h new file mode 100644 index 0000000..9d3cdfb --- /dev/null +++ b/src/analysis/scan/exprs/item.h @@ -0,0 +1,55 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * item.h - prototypes pour la récupération d'un élément à partir d'une série + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_ITEM_H +#define _ANALYSIS_SCAN_EXPRS_ITEM_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_SET_ITEM g_scan_set_item_get_type() +#define G_SCAN_SET_ITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_SET_ITEM, GScanSetItem)) +#define G_IS_SCAN_SET_ITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_SET_ITEM)) +#define G_SCAN_SET_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_SET_ITEM, GScanSetItemClass)) +#define G_IS_SCAN_SET_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_SET_ITEM)) +#define G_SCAN_SET_ITEM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_SET_ITEM, GScanSetItemClass)) + + +/* Accès à un élément donné d'une série établie (instance) */ +typedef struct _GScanSetItem GScanSetItem; + +/* Accès à un élément donné d'une série établie (classe) */ +typedef struct _GScanSetItemClass GScanSetItemClass; + + +/* Indique le type défini pour la récupération d'un élément à partir d'une série. */ +GType g_scan_set_item_get_type(void); + +/* Met en place un accès à un élément donné d'une série. */ +GScanExpression *g_scan_set_item_new(GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_ITEM_H */ diff --git a/src/analysis/scan/exprs/literal-int.h b/src/analysis/scan/exprs/literal-int.h new file mode 100644 index 0000000..b0a0ec5 --- /dev/null +++ b/src/analysis/scan/exprs/literal-int.h @@ -0,0 +1,71 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * literal-int.h - prototypes internes pour la représentation d'une valeur concrète + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_LITERAL_INT_H +#define _ANALYSIS_SCAN_EXPRS_LITERAL_INT_H + + +#include "literal.h" + + +#include "../expr-int.h" + + + +/* Expression portant une valeur concrète (instance) */ +struct _GScanLiteralExpression +{ + GScanExpression parent; /* A laisser en premier */ + + LiteralValueType value_type; /* Type de valeur portée */ + + union + { + bool boolean; /* Valeur booléenne */ + long long s_integer; /* Valeur entière 64 bits */ + unsigned long long u_integer; /* Valeur entière 64 bits */ + sized_string_t string; /* Chaîne de caractères */ + struct + { + char *regex; /* Formulation d'origine */ + regex_t preg; /* Expression rationnelle */ + }; + + } value; + +}; + +/* Expression portant une valeur concrète (classe) */ +struct _GScanLiteralExpressionClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une expression de valeur concrête. */ +bool g_scan_literal_expression_create(GScanLiteralExpression *, LiteralValueType, ...); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_LITERAL_INT_H */ diff --git a/src/analysis/scan/exprs/literal.c b/src/analysis/scan/exprs/literal.c new file mode 100644 index 0000000..b7aed5b --- /dev/null +++ b/src/analysis/scan/exprs/literal.c @@ -0,0 +1,734 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * literal.c - représentation d'une valeur concrète + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "literal.h" + + +#include <assert.h> +#include <stdarg.h> +#include <string.h> + + +#include "literal-int.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des expressions de valeur concrète. */ +static void g_scan_literal_expression_class_init(GScanLiteralExpressionClass *); + +/* Initialise une instance d'expression de valeur concrète. */ +static void g_scan_literal_expression_init(GScanLiteralExpression *); + +/* Supprime toutes les références externes. */ +static void g_scan_literal_expression_dispose(GScanLiteralExpression *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_literal_expression_finalize(GScanLiteralExpression *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réalise une comparaison entre objets selon un critère précis. */ +static bool g_scan_literal_expression_compare_rich(const GScanLiteralExpression *, const GScanLiteralExpression *, RichCmpOperation, bool *); + +/* Réduit une expression à une forme booléenne. */ +static bool g_scan_literal_expression_reduce_to_boolean(const GScanLiteralExpression *, GScanContext *, GScanScope *, GScanExpression **); + +/* Dénombre les éléments portés par une expression. */ +static bool g_scan_literal_expression_count(const GScanLiteralExpression *, GScanContext *, size_t *); + +/* Fournit un élément donné issu d'un ensemble constitué. */ +static bool g_scan_literal_expression_get_item(const GScanLiteralExpression *, size_t, GScanContext *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un appel de fonction enregistrée. */ +G_DEFINE_TYPE(GScanLiteralExpression, g_scan_literal_expression, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des expressions de valeur concrète. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_literal_expression_class_init(GScanLiteralExpressionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_literal_expression_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_literal_expression_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)g_scan_literal_expression_compare_rich; + expr->reduce_to_bool = (reduce_expr_to_bool_fc)g_scan_literal_expression_reduce_to_boolean; + expr->count = (count_scan_expr_fc)g_scan_literal_expression_count; + expr->get = (get_scan_expr_fc)g_scan_literal_expression_get_item; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance à initialiser. * +* * +* Description : Initialise une instance d'expression de valeur concrète. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_literal_expression_init(GScanLiteralExpression *expr) +{ + G_SCAN_EXPRESSION(expr)->state = SRS_REDUCED; + + memset(&expr->value, 0, sizeof(expr->value)); + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_literal_expression_dispose(GScanLiteralExpression *expr) +{ + G_OBJECT_CLASS(g_scan_literal_expression_parent_class)->dispose(G_OBJECT(expr)); + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_literal_expression_finalize(GScanLiteralExpression *expr) +{ + switch (expr->value_type) + { + case LVT_STRING: + exit_szstr(&expr->value.string); + break; + + case LVT_REG_EXPR: + if (expr->value.regex != NULL) + { + free(expr->value.regex); + regfree(&expr->value.preg); + } + break; + + default: + break; + + } + + G_OBJECT_CLASS(g_scan_literal_expression_parent_class)->finalize(G_OBJECT(expr)); + +} + + +/****************************************************************************** +* * +* Paramètres : vtype = type de valeur associée par l'expression. * +* ... = valeur concrête à intégrer. * +* * +* Description : Organise un appel de fonction avec ses arguments. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_literal_expression_new(LiteralValueType vtype, ...) +{ + GScanExpression *result; /* Structure à retourner */ + va_list ap; /* Liste d'arguements */ + void *ptr; /* Vision générique de valeur */ + + result = g_object_new(G_TYPE_SCAN_LITERAL_EXPRESSION, NULL); + + va_start(ap, vtype); + + ptr = va_arg(ap, void *); + + if (!g_scan_literal_expression_create(G_SCAN_LITERAL_EXPRESSION(result), vtype, ptr)) + g_clear_object(&result); + + va_end(ap); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance à initialiser pleinement. * +* vtype = type de valeur associée par l'expression. * +* ... = valeur concrête à intégrer. * +* * +* Description : Met en place une expression de valeur concrête. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_literal_expression_create(GScanLiteralExpression *expr, LiteralValueType vtype, ...) +{ + bool result; /* Bilan à retourner */ + va_list ap; /* Liste d'arguements */ + const bool *boolean; /* Valeur booléenne */ + const long long *s_integer; /* Valeur entière 64 bits #1 */ + const unsigned long long *u_integer; /* Valeur entière 64 bits #2 */ + const sized_string_t *string; /* Chaîne de caractères */ + const char *raw; /* Chaîne de caractères brute */ + size_t len; /* Taille de la chaîne */ + int cflags; /* Détails de compilation */ + unsigned int i; /* Boucle de parcours */ + char *tmp; /* Zone de travail temporaire */ + int ret; /* Bilan d'une opération */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(expr), SRS_REDUCED); + if (!result) goto exit; + + va_start(ap, vtype); + + switch (vtype) + { + case LVT_BOOLEAN: + boolean = va_arg(ap, const bool *); + expr->value.boolean = *boolean; + result = true; + break; + + case LVT_SIGNED_INTEGER: + s_integer = va_arg(ap, const long long *); + expr->value.s_integer = *s_integer; + result = true; + break; + + case LVT_UNSIGNED_INTEGER: + u_integer = va_arg(ap, const unsigned long long *); + expr->value.u_integer = *u_integer; + result = true; + break; + + case LVT_STRING: + string = va_arg(ap, const sized_string_t *); + szstrdup(&expr->value.string, string); + result = true; + break; + + case LVT_REG_EXPR: + raw = va_arg(ap, const char *); + len = strlen(raw); + + result = (len > 2 && raw[0] == '/'); + + cflags = REG_EXTENDED | REG_NOSUB; + + for (i = 0; i < 2 && result; i++) + { + result = (len > 2); + + if (raw[len - 1] == 'i') + { + cflags |= REG_ICASE; + len -= 1; + } + + else if (raw[len - 1] == 's') + { + cflags |= REG_NEWLINE; + len -= 1; + } + + else if (raw[len - 1] == '/') + break; + + } + + if (result) + result = (raw[len - 1] == '/'); + + if (result) + { + assert(len > 2); + + tmp = strndup(&raw[1], len - 2); + ret = regcomp(&expr->value.preg, tmp, cflags); + free(tmp); + + result = (ret == 0); + + if (result) + expr->value.regex = strdup(raw); + + } + + break; + + default: + result = false; + break; + + } + + va_end(ap); + + expr->value_type = vtype; + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* * +* Description : Indique le type de valeur portée par une expression. * +* * +* Retour : Type de valeur associée à l'expression. * +* * +* Remarques : - * +* * +******************************************************************************/ + +LiteralValueType g_scan_literal_expression_get_value_type(const GScanLiteralExpression *expr) +{ + LiteralValueType result; /* Type à retourner */ + + result = expr->value_type; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = premier objet à consulter pour une comparaison. * +* value = valeur portée portée par l'expression. [OUT] * +* * +* Description : Indique la valeur portée par une expression booléenne. * +* * +* Retour : true si l'expression est de type booléen, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_literal_expression_get_boolean_value(const GScanLiteralExpression *expr, bool *value) +{ + bool result; /* Etat à retourner */ + + result = (expr->value_type == LVT_BOOLEAN); + + if (result) + *value = expr->value.boolean; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = premier objet à consulter pour une comparaison. * +* value = valeur portée portée par l'expression. [OUT] * +* * +* Description : Indique la valeur portée par une expression d'entier. * +* * +* Retour : true si l'expression est de type entier, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_literal_expression_get_signed_integer_value(const GScanLiteralExpression *expr, long long *value) +{ + bool result; /* Etat à retourner */ + + result = (expr->value_type == LVT_SIGNED_INTEGER); + + if (result) + *value = expr->value.u_integer; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = premier objet à consulter pour une comparaison. * +* value = valeur portée portée par l'expression. [OUT] * +* * +* Description : Indique la valeur portée par une expression d'entier. * +* * +* Retour : true si l'expression est de type entier, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_literal_expression_get_unsigned_integer_value(const GScanLiteralExpression *expr, unsigned long long *value) +{ + bool result; /* Etat à retourner */ + + result = (expr->value_type == LVT_UNSIGNED_INTEGER); + + if (result) + *value = expr->value.u_integer; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = premier objet à consulter pour une comparaison. * +* value = valeur portée portée par l'expression. [OUT] * +* * +* Description : Indique la valeur portée par une expression de chaîne. * +* * +* Retour : true si l'expression est de type entier, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_literal_expression_get_string_value(const GScanLiteralExpression *expr, const sized_string_t **value) +{ + bool result; /* Etat à retourner */ + + result = (expr->value_type == LVT_STRING); + + if (result) + *value = &expr->value.string; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = premier objet à consulter pour une comparaison. * +* value = valeur portée portée par l'expression. [OUT] * +* * +* Description : Indique la valeur portée par une expression rationnelle. * +* * +* Retour : true si l'expression est de type entier, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_literal_expression_get_regex_value(const GScanLiteralExpression *expr, const regex_t **value) +{ + bool result; /* Etat à retourner */ + + result = (expr->value_type == LVT_REG_EXPR); + + if (result) + *value = &expr->value.preg; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = premier objet à consulter pour une comparaison. * +* other = second objet à consulter pour une comparaison. * +* op = opération de comparaison à réaliser. * +* status = bilan des opérations de comparaison. [OUT] * +* * +* Description : Réalise une comparaison entre objets selon un critère précis.* +* * +* Retour : true si la comparaison a pu être effectuée, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_literal_expression_compare_rich(const GScanLiteralExpression *expr, const GScanLiteralExpression *other, RichCmpOperation op, bool *status) +{ + bool result; /* Etat à retourner */ + int cmp; /* Bilan intermédiaire */ + + result = g_type_is_a(G_TYPE_FROM_INSTANCE(other), G_TYPE_SCAN_LITERAL_EXPRESSION); + if (!result) goto done; + + if (expr->value_type != other->value_type) + { + *status = compare_rich_integer_values_unsigned(expr->value_type, other->value_type, op); + goto done; + } + + switch (expr->value_type) + { + case LVT_BOOLEAN: + switch (op) + { + case RCO_EQ: + *status = (expr->value.boolean == other->value.boolean); + result = true; + break; + + case RCO_NE: + *status = (expr->value.boolean != other->value.boolean); + result = true; + break; + + default: + result = false; + break; + + }; + break; + + case LVT_SIGNED_INTEGER: + *status = compare_rich_integer_values_signed(expr->value.s_integer, other->value.s_integer, op); + result = true; + break; + + case LVT_UNSIGNED_INTEGER: + *status = compare_rich_integer_values_unsigned(expr->value.u_integer, other->value.u_integer, op); + result = true; + break; + + case LVT_STRING: + cmp = szstrcmp(&expr->value.string, &other->value.string); + *status = compare_rich_integer_values_signed(cmp, 0, op); + result = true; + break; + + case LVT_REG_EXPR: + cmp = strcmp(expr->value.regex, other->value.regex); + *status = compare_rich_integer_values_signed(cmp, 0, op); + result = true; + break; + + default: + result = false; + break; + + } + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme booléenne. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_literal_expression_reduce_to_boolean(const GScanLiteralExpression *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + + switch (expr->value_type) + { + case LVT_BOOLEAN: + *out = G_SCAN_EXPRESSION(expr); + g_object_ref(G_OBJECT(expr)); + result = true; + break; + + case LVT_SIGNED_INTEGER: + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ expr->value.s_integer != 0 }); + result = true; + break; + + case LVT_UNSIGNED_INTEGER: + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ expr->value.u_integer != 0 }); + result = true; + break; + + case LVT_STRING: + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ expr->value.string.len > 0 }); + result = true; + break; + + default: + result = false; + break; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* count = quantité d'éléments déterminée. [OUT] * +* * +* Description : Dénombre les éléments portés par une expression. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_literal_expression_count(const GScanLiteralExpression *expr, GScanContext *ctx, size_t *count) +{ + bool result; /* Bilan à retourner */ + + switch (expr->value_type) + { + case LVT_STRING: + *count = expr->value.string.len; + result = true; + break; + + default: + result = false; + break; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* index = indice de l'élément à transférer. * +* ctx = contexte de suivi de l'analyse courante. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Fournit un élément donné issu d'un ensemble constitué. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_literal_expression_get_item(const GScanLiteralExpression *expr, size_t index, GScanContext *ctx, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + sized_string_t ch; /* Caractère extrait */ + + switch (expr->value_type) + { + case LVT_STRING: + + result = (index < expr->value.string.len); + + if (result) + { + ch.data = expr->value.string.data + index; + ch.len = 1; + + *out = g_scan_literal_expression_new(LVT_STRING, &ch); + + } + + break; + + default: + result = false; + break; + + } + + return result; + +} diff --git a/src/analysis/scan/exprs/literal.h b/src/analysis/scan/exprs/literal.h new file mode 100644 index 0000000..9352baf --- /dev/null +++ b/src/analysis/scan/exprs/literal.h @@ -0,0 +1,90 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * literal.h - prototypes pour la représentation d'une valeur concrète + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_LITERAL_H +#define _ANALYSIS_SCAN_EXPRS_LITERAL_H + + +#include <regex.h> +#include <stdbool.h> + + +#include "../expr.h" +#include "../../../common/szstr.h" + + + +#define G_TYPE_SCAN_LITERAL_EXPRESSION g_scan_literal_expression_get_type() +#define G_SCAN_LITERAL_EXPRESSION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_LITERAL_EXPRESSION, GScanLiteralExpression)) +#define G_IS_SCAN_LITERAL_EXPRESSION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_LITERAL_EXPRESSION)) +#define G_SCAN_LITERAL_EXPRESSION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_LITERAL_EXPRESSION, GScanLiteralExpressionClass)) +#define G_IS_SCAN_LITERAL_EXPRESSION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_LITERAL_EXPRESSION)) +#define G_SCAN_LITERAL_EXPRESSION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_LITERAL_EXPRESSION, GScanLiteralExpressionClass)) + + +/* Expression portant une valeur concrète (instance) */ +typedef struct _GScanLiteralExpression GScanLiteralExpression; + +/* Expression portant une valeur concrète (classe) */ +typedef struct _GScanLiteralExpressionClass GScanLiteralExpressionClass; + + +/* Types naturel équivalant à l'expression */ +typedef enum _LiteralValueType +{ + LVT_BOOLEAN, /* Valeur booléenne */ + LVT_SIGNED_INTEGER, /* Nombre entier 64 bits #1 */ + LVT_UNSIGNED_INTEGER, /* Nombre entier 64 bits #2 */ + LVT_STRING, /* Chaîne de caractères */ + LVT_REG_EXPR, /* Expression rationnelle */ + +} LiteralValueType; + + +/* Indique le type défini pour un appel de fonction enregistrée. */ +GType g_scan_literal_expression_get_type(void); + +/* Organise un appel de fonction avec ses arguments. */ +GScanExpression *g_scan_literal_expression_new(LiteralValueType, ...); + +/* Indique le type de valeur portée par une expression. */ +LiteralValueType g_scan_literal_expression_get_value_type(const GScanLiteralExpression *); + +/* Indique la valeur portée par une expression booléenne. */ +bool g_scan_literal_expression_get_boolean_value(const GScanLiteralExpression *, bool *); + +/* Indique la valeur portée par une expression d'entier. */ +bool g_scan_literal_expression_get_signed_integer_value(const GScanLiteralExpression *, long long *); + +/* Indique la valeur portée par une expression d'entier. */ +bool g_scan_literal_expression_get_unsigned_integer_value(const GScanLiteralExpression *, unsigned long long *); + +/* Indique la valeur portée par une expression de chaîne. */ +bool g_scan_literal_expression_get_string_value(const GScanLiteralExpression *, const sized_string_t **); + +/* Indique la valeur portée par une expression rationnelle. */ +bool g_scan_literal_expression_get_regex_value(const GScanLiteralExpression *, const regex_t **); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_LITERAL_H */ diff --git a/src/analysis/scan/exprs/logical-int.h b/src/analysis/scan/exprs/logical-int.h new file mode 100644 index 0000000..6df55d0 --- /dev/null +++ b/src/analysis/scan/exprs/logical-int.h @@ -0,0 +1,60 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * logical-int.h - prototypes internes pour la gestion des opérations booléennes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_LOGICAL_INT_H +#define _ANALYSIS_SCAN_EXPRS_LOGICAL_INT_H + + +#include "logical.h" + + +#include "../expr-int.h" + + + +/* Opération booléenne avec un ou deux opérandes (instance) */ +struct _GScanLogicalOperation +{ + GScanExpression parent; /* A laisser en premier */ + + BooleanOperationType type; /* Type d'opération menée */ + + GScanExpression *first; /* Expression impactée #1 */ + GScanExpression *second; /* Expression impactée #2 */ + +}; + +/* Opération booléenne avec un ou deux opérandes (classe) */ +struct _GScanLogicalOperationClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une expression d'opération booléenne. */ +bool g_scan_logical_operation_create(GScanLogicalOperation *, BooleanOperationType, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_LOGICAL_INT_H */ diff --git a/src/analysis/scan/exprs/logical.c b/src/analysis/scan/exprs/logical.c new file mode 100644 index 0000000..3b07843 --- /dev/null +++ b/src/analysis/scan/exprs/logical.c @@ -0,0 +1,518 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * logical.c - gestion des opérations booléennes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "logical.h" + + +#include <assert.h> + + +#include "logical-int.h" +#include "literal.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des opérations booléennes. */ +static void g_scan_logical_operation_class_init(GScanLogicalOperationClass *); + +/* Initialise une instance d'opération booléenne. */ +static void g_scan_logical_operation_init(GScanLogicalOperation *); + +/* Supprime toutes les références externes. */ +static void g_scan_logical_operation_dispose(GScanLogicalOperation *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_logical_operation_finalize(GScanLogicalOperation *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réalise une comparaison entre objets selon un critère précis. */ +static bool g_scan_logical_operation_compare_rich(const GScanLogicalOperation *, const GScanLogicalOperation *, RichCmpOperation, bool *); + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_logical_operation_reduce(const GScanLogicalOperation *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une opération booléenne sur expression(s). */ +G_DEFINE_TYPE(GScanLogicalOperation, g_scan_logical_operation, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des opérations booléennes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_logical_operation_class_init(GScanLogicalOperationClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_logical_operation_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_logical_operation_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)g_scan_logical_operation_compare_rich; + expr->reduce = (reduce_expr_fc)g_scan_logical_operation_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser. * +* * +* Description : Initialise une instance d'opération booléenne. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_logical_operation_init(GScanLogicalOperation *op) +{ + op->first = NULL; + op->second = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_logical_operation_dispose(GScanLogicalOperation *op) +{ + g_clear_object(&op->first); + g_clear_object(&op->second); + + G_OBJECT_CLASS(g_scan_logical_operation_parent_class)->dispose(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_logical_operation_finalize(GScanLogicalOperation *op) +{ + G_OBJECT_CLASS(g_scan_logical_operation_parent_class)->finalize(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : type = type d'opération booléenne à représenter. * +* first = premier opérande concerné. * +* second = éventuel second opérande impliqué ou NULL. * +* * +* Description : Organise un appel de fonction avec ses arguments. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_logical_operation_new(BooleanOperationType type, GScanExpression *first, GScanExpression *second) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_BOOLEAN_OPERATION, NULL); + + if (!g_scan_logical_operation_create(G_SCAN_LOGICAL_OPERATION(result), type, first, second)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = instance à initialiser pleinement. * +* type = type d'opération booléenne à représenter. * +* first = premier opérande concerné. * +* second = éventuel second opérande impliqué ou NULL. * +* * +* Description : Met en place une expression d'opération booléenne. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_logical_operation_create(GScanLogicalOperation *op, BooleanOperationType type, GScanExpression *first, GScanExpression *second) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(op), SRS_PENDING); + if (!result) goto exit; + + op->type = type; + + switch (type) + { + case BOT_AND: + case BOT_OR: + op->first = first; + g_object_ref(G_OBJECT(op->first)); + + op->second = second; + g_object_ref(G_OBJECT(op->second)); + + result = true; + break; + + case BOT_NOT: + op->first = first; + g_object_ref(G_OBJECT(op->first)); + + result = (second == NULL); + assert(second == NULL); + break; + + default: + result = false; + break; + + } + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = premier objet à consulter pour une comparaison. * +* other = second objet à consulter pour une comparaison. * +* op = opération de comparaison à réaliser. * +* status = bilan des opérations de comparaison. [OUT] * +* * +* Description : Réalise une comparaison entre objets selon un critère précis.* +* * +* Retour : true si la comparaison a pu être effectuée, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_logical_operation_compare_rich(const GScanLogicalOperation *item, const GScanLogicalOperation *other, RichCmpOperation op, bool *status) +{ + bool result; /* Etat à retourner */ + + result = g_type_is_a(G_TYPE_FROM_INSTANCE(other), G_TYPE_BOOLEAN_OPERATION); + if (!result) goto done; + + if (item->type != other->type) + { + *status = compare_rich_integer_values_unsigned(item->type, other->type, op); + goto done; + } + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item), G_COMPARABLE_ITEM(other), RCO_EQ, status); + if (!result || STATUS_NOT_EQUAL(*status, op)) goto done; + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item->first), + G_COMPARABLE_ITEM(other->first), + op, status); + if (!result || STATUS_NOT_EQUAL(*status, op)) goto done; + + if (item->second == NULL) + { + assert(other->second == NULL); + + switch (op) + { + case RCO_LT: + case RCO_NE: + case RCO_GT: + *status = false; + break; + + case RCO_LE: + case RCO_EQ: + case RCO_GE: + *status = true; + break; + + } + + } + + else + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item->second), + G_COMPARABLE_ITEM(other->second), + op, status); + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_logical_operation_reduce(const GScanLogicalOperation *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_first; /* Expression réduite (gauche) */ + ScanReductionState state[2]; /* Bilan de sous-réductons */ + GScanExpression *new_second; /* Expression réduite (droite) */ + GScanExpression *bool_operands[2]; /* Expressions booléennes */ + bool values[2]; /* Valeurs des éléments portés */ + bool valid[2]; /* Validité de ces valeurs */ + + /* Réduction des éléments considérés */ + + state[0] = g_scan_expression_reduce(expr->first, ctx, scope, &new_first); + + if (expr->second != NULL) + state[1] = g_scan_expression_reduce(expr->second, ctx, scope, &new_second); + else + { + new_second = NULL; + state[1] = SRS_REDUCED; + } + + /* Récupération des valeurs booléennes */ + + if (new_first != NULL) + { + valid[0] = g_scan_expression_reduce_to_boolean(new_first, ctx, scope, &bool_operands[0]); + + if (valid[0]) + valid[0] = g_scan_literal_expression_get_boolean_value(G_SCAN_LITERAL_EXPRESSION(bool_operands[0]), + &values[0]); + else + bool_operands[0] = NULL; + + } + else + { + bool_operands[0] = NULL; + valid[0] = false; + } + + if (new_second != NULL) + { + valid[1] = g_scan_expression_reduce_to_boolean(new_second, ctx, scope, &bool_operands[1]); + + if (valid[1]) + valid[1] = g_scan_literal_expression_get_boolean_value(G_SCAN_LITERAL_EXPRESSION(bool_operands[1]), + &values[1]); + else + bool_operands[1] = NULL; + + } + else + { + bool_operands[1] = NULL; + valid[1] = false; + } + + /* Construction d'une réduction locale ? */ + + switch (expr->type) + { + case BOT_AND: + if (valid[0] && valid[1]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { values[0] && values[1] }); + result = SRS_REDUCED; + } + + else if (valid[0] && !values[0]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { false }); + result = SRS_REDUCED; + } + + else if (valid[1] && !values[1]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { false }); + result = SRS_REDUCED; + } + + else + { + if (state[0] == SRS_UNRESOLVABLE || state[1] == SRS_UNRESOLVABLE) + result = SRS_UNRESOLVABLE; + else + { + assert(state[0] == SRS_WAIT_FOR_SCAN || state[1] == SRS_WAIT_FOR_SCAN); + result = SRS_WAIT_FOR_SCAN; + } + } + + break; + + case BOT_OR: + if (valid[0] && valid[1]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { values[0] || values[1] }); + result = SRS_REDUCED; + } + + else if (valid[0] && values[0]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { true }); + result = SRS_REDUCED; + } + + else if (valid[1] && values[1]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { true }); + result = SRS_REDUCED; + } + + else + { + if (state[0] == SRS_UNRESOLVABLE || state[1] == SRS_UNRESOLVABLE) + result = SRS_UNRESOLVABLE; + else + { + assert(state[0] == SRS_WAIT_FOR_SCAN || state[1] == SRS_WAIT_FOR_SCAN); + result = SRS_WAIT_FOR_SCAN; + } + } + + break; + + case BOT_NOT: + if (valid[0]) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { !values[0] }); + result = SRS_REDUCED; + } + + else + { + if (state[0] == SRS_UNRESOLVABLE) + result = SRS_UNRESOLVABLE; + else + { + assert(state[0] == SRS_WAIT_FOR_SCAN); + result = SRS_WAIT_FOR_SCAN; + } + } + + break; + + /* Pour GCC... */ + default: + result = SRS_UNRESOLVABLE; + break; + + } + + /* Mise à jour de la progression ? */ + + if (result == SRS_WAIT_FOR_SCAN) + { + if (new_first != expr->first || new_second != expr->second) + { + assert(new_first != NULL); + assert(new_second != NULL || expr->second == NULL); + + *out = g_scan_logical_operation_new(expr->type, new_first, new_second); + + } + + } + + /* Sortie propre */ + + g_clear_object(&bool_operands[0]); + g_clear_object(&bool_operands[1]); + + g_clear_object(&new_first); + g_clear_object(&new_second); + + return result; + +} diff --git a/src/analysis/scan/exprs/logical.h b/src/analysis/scan/exprs/logical.h new file mode 100644 index 0000000..e98bf11 --- /dev/null +++ b/src/analysis/scan/exprs/logical.h @@ -0,0 +1,65 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * logical.h - prototypes pour la gestion des opérations booléennes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_LOGICAL_H +#define _ANALYSIS_SCAN_EXPRS_LOGICAL_H + + +#include "../expr.h" + + + +#define G_TYPE_BOOLEAN_OPERATION g_scan_logical_operation_get_type() +#define G_SCAN_LOGICAL_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_BOOLEAN_OPERATION, GScanLogicalOperation)) +#define G_IS_BOOLEAN_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_BOOLEAN_OPERATION)) +#define G_SCAN_LOGICAL_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_BOOLEAN_OPERATION, GScanLogicalOperationClass)) +#define G_IS_BOOLEAN_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_BOOLEAN_OPERATION)) +#define G_SCAN_LOGICAL_OPERATION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_BOOLEAN_OPERATION, GScanLogicalOperationClass)) + + +/* Opération booléenne avec un ou deux opérandes (instance) */ +typedef struct _GScanLogicalOperation GScanLogicalOperation; + +/* Opération booléenne avec un ou deux opérandes (classe) */ +typedef struct _GScanLogicalOperationClass GScanLogicalOperationClass; + + +/* Types d'opérations booléennes supportées */ +typedef enum _BooleanOperationType +{ + BOT_AND, /* Opérateur binaire "and" */ + BOT_OR, /* Opérateur binaire "or" */ + BOT_NOT, /* Opérateur unaire "not" */ + +} BooleanOperationType; + + +/* Indique le type défini pour une opération booléenne sur expression(s). */ +GType g_scan_logical_operation_get_type(void); + +/* Organise un appel de fonction avec ses arguments. */ +GScanExpression *g_scan_logical_operation_new(BooleanOperationType, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_LOGICAL_H */ diff --git a/src/analysis/scan/exprs/range-int.h b/src/analysis/scan/exprs/range-int.h new file mode 100644 index 0000000..6257874 --- /dev/null +++ b/src/analysis/scan/exprs/range-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * range-int.h - prototypes internes pour la représentation compacte d'un éventail de valeurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_RANGE_INT_H +#define _ANALYSIS_SCAN_EXPRS_RANGE_INT_H + + +#include "range.h" + + +#include "../expr-int.h" + + + +/* Représentation compacte d'un éventail de valeurs (instance) */ +struct _GScanCompactRange +{ + GScanExpression parent; /* A laisser en premier */ + + GScanExpression *start; /* Point de départ */ + GScanExpression *end; /* Point d'arrivée */ + +}; + +/* Représentation compacte d'un éventail de valeurs (classe) */ +struct _GScanCompactRangeClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une réprésentation d'un éventail de valeurs. */ +bool g_scan_compact_range_create(GScanCompactRange *, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_RANGE_INT_H */ diff --git a/src/analysis/scan/exprs/range.c b/src/analysis/scan/exprs/range.c new file mode 100644 index 0000000..9716149 --- /dev/null +++ b/src/analysis/scan/exprs/range.c @@ -0,0 +1,355 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * range.c - représentation compacte d'un éventail de valeurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "range.h" + + +#include "literal.h" +#include "range-int.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des éventail de valeurs. */ +static void g_scan_compact_range_class_init(GScanCompactRangeClass *); + +/* Initialise une instance d'éventail de valeurs. */ +static void g_scan_compact_range_init(GScanCompactRange *); + +/* Supprime toutes les références externes. */ +static void g_scan_compact_range_dispose(GScanCompactRange *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_compact_range_finalize(GScanCompactRange *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_compact_range_reduce(const GScanCompactRange *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réduit une expression à une forme booléenne. */ +static bool g_scan_compact_range_reduce_to_boolean(const GScanCompactRange *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réalise l'intersection entre deux ensembles. */ +static GScanExpression *g_scan_compact_range_intersect(const GScanCompactRange *expr, const GScanExpression *, GScanContext *, GScanScope *); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une représentation compacte d'un éventail de valeurs. */ +G_DEFINE_TYPE(GScanCompactRange, g_scan_compact_range, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des éventail de valeurs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_compact_range_class_init(GScanCompactRangeClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_compact_range_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_compact_range_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->reduce = (reduce_expr_fc)g_scan_compact_range_reduce; + expr->reduce_to_bool = (reduce_expr_to_bool_fc)g_scan_compact_range_reduce_to_boolean; + expr->intersect = (intersect_scan_expr_fc)g_scan_compact_range_intersect; + +} + + +/****************************************************************************** +* * +* Paramètres : range = instance à initialiser. * +* * +* Description : Initialise une instance d'éventail de valeurs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_compact_range_init(GScanCompactRange *range) +{ + range->start = NULL; + range->end = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : range = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_compact_range_dispose(GScanCompactRange *range) +{ + g_clear_object(&range->start); + g_clear_object(&range->end); + + G_OBJECT_CLASS(g_scan_compact_range_parent_class)->dispose(G_OBJECT(range)); + +} + + +/****************************************************************************** +* * +* Paramètres : range = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_compact_range_finalize(GScanCompactRange *range) +{ + G_OBJECT_CLASS(g_scan_compact_range_parent_class)->finalize(G_OBJECT(range)); + +} + + +/****************************************************************************** +* * +* Paramètres : start = point de départ de la plage de valeurs. * +* end = point d'arrivée de la plage de valeurs. * +* * +* Description : Organise une réprésentation d'un éventail de valeurs. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_compact_range_new(GScanExpression *start, GScanExpression *end) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_COMPACT_RANGE, NULL); + + if (!g_scan_compact_range_create(G_SCAN_COMPACT_RANGE(result), start, end)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : range = instance à initialiser pleinement. * +* start = point de départ de la plage de valeurs. * +* end = point d'arrivée de la plage de valeurs. * +* * +* Description : Met en place une réprésentation d'un éventail de valeurs. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_compact_range_create(GScanCompactRange *range, GScanExpression *start, GScanExpression *end) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(range), SRS_PENDING); + if (!result) goto exit; + + range->start = start; + g_object_ref(G_OBJECT(start)); + + range->end = end; + g_object_ref(G_OBJECT(end)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_compact_range_reduce(const GScanCompactRange *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_start; /* Nouvelle réduction #1 */ + GScanExpression *new_end; /* Nouvelle réduction #2 */ + ScanReductionState state_start; /* Etat synthétisé #1 */ + ScanReductionState state_end; /* Etat synthétisé #2 */ + + new_start = NULL; + new_end = NULL; + + state_start = g_scan_expression_reduce(expr->start, ctx, scope, &new_start); + if (state_start == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + state_end = g_scan_expression_reduce(expr->end, ctx, scope, &new_end); + if (state_end == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (state_start == SRS_WAIT_FOR_SCAN || state_end == SRS_WAIT_FOR_SCAN) + result = SRS_WAIT_FOR_SCAN; + else + result = SRS_REDUCED; + + if (new_start != expr->start || new_end != expr->end) + *out = g_scan_compact_range_new(new_start, new_end); + + exit: + + g_clear_object(&new_start); + g_clear_object(&new_end); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme booléenne. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_compact_range_reduce_to_boolean(const GScanCompactRange *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + bool status; /* Bilan d'une comparaison */ + + result = G_IS_SCAN_LITERAL_EXPRESSION(expr->start) && G_IS_SCAN_LITERAL_EXPRESSION(expr->end); + if (!result) goto exit; + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(expr->start), + G_COMPARABLE_ITEM(expr->end), + RCO_LE, &status); + if (!result) goto exit; + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, &status); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à filtrer. * +* other = expression utilisée pour le filtrage. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* * +* Description : Réalise l'intersection entre deux ensembles. * +* * +* Retour : Intersection entre les deux ensembles ou NULL en cas d'échec.* +* * +* Remarques : - * +* * +******************************************************************************/ + +static GScanExpression *g_scan_compact_range_intersect(const GScanCompactRange *expr, const GScanExpression *other, GScanContext *ctx, GScanScope *scope) +{ + GScanExpression *result; /* Instance à retourner */ + + + + + result = true; // TODO + + + + + return result; + +} diff --git a/src/analysis/scan/exprs/range.h b/src/analysis/scan/exprs/range.h new file mode 100644 index 0000000..4b7ad04 --- /dev/null +++ b/src/analysis/scan/exprs/range.h @@ -0,0 +1,55 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * range.h - prototypes pour la représentation compacte d'un éventail de valeurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_SET_H +#define _ANALYSIS_SCAN_EXPRS_SET_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_COMPACT_RANGE g_scan_compact_range_get_type() +#define G_SCAN_COMPACT_RANGE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_COMPACT_RANGE, GScanCompactRange)) +#define G_IS_SCAN_COMPACT_RANGE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_COMPACT_RANGE)) +#define G_SCAN_COMPACT_RANGE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_COMPACT_RANGE, GScanCompactRangeClass)) +#define G_IS_SCAN_COMPACT_RANGE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_COMPACT_RANGE)) +#define G_SCAN_COMPACT_RANGE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_COMPACT_RANGE, GScanCompactRangeClass)) + + +/* Représentation compacte d'un éventail de valeurs (instance) */ +typedef struct _GScanCompactRange GScanCompactRange; + +/* Représentation compacte d'un éventail de valeurs (classe) */ +typedef struct _GScanCompactRangeClass GScanCompactRangeClass; + + +/* Indique le type défini pour une représentation compacte d'un éventail de valeurs. */ +GType g_scan_compact_range_get_type(void); + +/* Organise une réprésentation d'un éventail de valeurs. */ +GScanExpression *g_scan_compact_range_new(GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_SET_H */ diff --git a/src/analysis/scan/exprs/relational-int.h b/src/analysis/scan/exprs/relational-int.h new file mode 100644 index 0000000..813b89d --- /dev/null +++ b/src/analysis/scan/exprs/relational-int.h @@ -0,0 +1,60 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * relational-int.h - prototypes internes pour la gestion des opérations relationnelles + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_RELATIONAL_INT_H +#define _ANALYSIS_SCAN_EXPRS_RELATIONAL_INT_H + + +#include "relational.h" + + +#include "../expr-int.h" + + + +/* Opération relationnelle impliquant deux opérandes (instance) */ +struct _GScanRelationalOperation +{ + GScanExpression parent; /* A laisser en premier */ + + RichCmpOperation rel_type; /* Type de relation étudiée */ + + GScanExpression *left; /* Expression impactée #1 */ + GScanExpression *right; /* Expression impactée #2 */ + +}; + +/* Opération relationnelle impliquant deux opérandes (classe) */ +struct _GScanRelationalOperationClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une opération relationnelle entre expressions. */ +bool g_scan_relational_operation_create(GScanRelationalOperation *, RichCmpOperation, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_RELATIONAL_INT_H */ diff --git a/src/analysis/scan/exprs/relational.c b/src/analysis/scan/exprs/relational.c new file mode 100644 index 0000000..74a972b --- /dev/null +++ b/src/analysis/scan/exprs/relational.c @@ -0,0 +1,411 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * relational.c - gestion des opérations relationnelles + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "relational.h" + + +#include <assert.h> + + +#include "relational-int.h" +#include "literal.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des opérations de relations. */ +static void g_scan_relational_operation_class_init(GScanRelationalOperationClass *); + +/* Initialise une instance d'opération de relation. */ +static void g_scan_relational_operation_init(GScanRelationalOperation *); + +/* Supprime toutes les références externes. */ +static void g_scan_relational_operation_dispose(GScanRelationalOperation *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_relational_operation_finalize(GScanRelationalOperation *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réalise une comparaison entre objets selon un critère précis. */ +static bool g_scan_relational_operation_compare_rich(const GScanRelationalOperation *, const GScanRelationalOperation *, RichCmpOperation, bool *); + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_relational_operation_reduce(const GScanRelationalOperation *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une opération de relation entre expressions. */ +G_DEFINE_TYPE(GScanRelationalOperation, g_scan_relational_operation, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des opérations de relations. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_relational_operation_class_init(GScanRelationalOperationClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_relational_operation_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_relational_operation_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)g_scan_relational_operation_compare_rich; + expr->reduce = (reduce_expr_fc)g_scan_relational_operation_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser. * +* * +* Description : Initialise une instance d'opération de relation. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_relational_operation_init(GScanRelationalOperation *op) +{ + op->left = NULL; + op->right = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_relational_operation_dispose(GScanRelationalOperation *op) +{ + g_clear_object(&op->left); + g_clear_object(&op->right); + + G_OBJECT_CLASS(g_scan_relational_operation_parent_class)->dispose(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_relational_operation_finalize(GScanRelationalOperation *op) +{ + G_OBJECT_CLASS(g_scan_relational_operation_parent_class)->finalize(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : type = type d'opération booléenne à représenter. * +* left = premier opérande concerné. * +* right = éventuel second opérande impliqué ou NULL. * +* * +* Description : Organise une opération relationnelle entre expressions. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_relational_operation_new(RichCmpOperation type, GScanExpression *left, GScanExpression *right) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_RELATIONAL_OPERATION, NULL); + + if (!g_scan_relational_operation_create(G_SCAN_RELATIONAL_OPERATION(result), type, left, right)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser pleinement. * +* type = type d'opération booléenne à représenter. * +* left = premier opérande concerné. * +* right = éventuel second opérande impliqué ou NULL. * +* * +* Description : Met en place une opération relationnelle entre expressions. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_relational_operation_create(GScanRelationalOperation *op, RichCmpOperation type, GScanExpression *left, GScanExpression *right) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(op), SRS_PENDING); + if (!result) goto exit; + + op->rel_type = type; + + op->left = left; + g_object_ref(G_OBJECT(op->left)); + + op->right = right; + g_object_ref(G_OBJECT(op->right)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = premier objet à consulter pour une comparaison. * +* other = second objet à consulter pour une comparaison. * +* op = opération de comparaison à réaliser. * +* status = bilan des opérations de comparaison. [OUT] * +* * +* Description : Réalise une comparaison entre objets selon un critère précis.* +* * +* Retour : true si la comparaison a pu être effectuée, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_relational_operation_compare_rich(const GScanRelationalOperation *item, const GScanRelationalOperation *other, RichCmpOperation op, bool *status) +{ + bool result; /* Etat à retourner */ + + result = g_type_is_a(G_TYPE_FROM_INSTANCE(other), G_TYPE_SCAN_RELATIONAL_OPERATION); + if (!result) goto done; + + if (item->rel_type != other->rel_type) + { + *status = compare_rich_integer_values_unsigned(item->rel_type, other->rel_type, op); + goto done; + } + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item), G_COMPARABLE_ITEM(other), RCO_EQ, status); + if (!result || STATUS_NOT_EQUAL(*status, op)) goto done; + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item->left), + G_COMPARABLE_ITEM(other->left), + op, status); + if (!result || STATUS_NOT_EQUAL(*status, op)) goto done; + + result = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(item->right), + G_COMPARABLE_ITEM(other->right), + op, status); + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_relational_operation_reduce(const GScanRelationalOperation *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_left; /* Expression réduite (gauche) */ + GScanExpression *new_right; /* Expression réduite (droite) */ + ScanReductionState state_left; /* Etat synthétisé #1 */ + ScanReductionState state_right; /* Etat synthétisé #2 */ + LiteralValueType vtype_left; /* Type de valeur portée #1 */ + LiteralValueType vtype_right; /* Type de valeur portée #2 */ + GScanExpression *casted; /* Nouvelle forme en booléen */ + bool status; /* Bilan d'une comparaison */ + bool valid; /* Validité de ce bilan obtenu */ + + /* Réduction des éléments considérés */ + + new_left = NULL; + new_right = NULL; + + state_left = g_scan_expression_reduce(expr->left, ctx, scope, &new_left); + if (state_left == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + state_right = g_scan_expression_reduce(expr->right, ctx, scope, &new_right); + if (state_right == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Transtypage vers des booléens imposé ? */ + + if (expr->rel_type == RCO_EQ || expr->rel_type == RCO_NE) + { + if (G_IS_SCAN_LITERAL_EXPRESSION(new_left)) + { + vtype_left = g_scan_literal_expression_get_value_type(G_SCAN_LITERAL_EXPRESSION(new_left)); + + if (vtype_left == LVT_BOOLEAN) + { + if (g_scan_expression_reduce_to_boolean(new_right, ctx, scope, &casted)) + { + g_object_unref(G_OBJECT(new_right)); + new_right = casted; + } + } + + } + + if (G_IS_SCAN_LITERAL_EXPRESSION(new_right)) + { + vtype_right = g_scan_literal_expression_get_value_type(G_SCAN_LITERAL_EXPRESSION(new_right)); + + if (vtype_right == LVT_BOOLEAN) + { + if (g_scan_expression_reduce_to_boolean(new_left, ctx, scope, &casted)) + { + g_object_unref(G_OBJECT(new_left)); + new_left = casted; + } + } + + } + + } + + /* Construction d'une réduction locale ? */ + + if (G_IS_SCAN_LITERAL_EXPRESSION(new_left) && G_IS_SCAN_LITERAL_EXPRESSION(new_right)) + { + valid = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(new_left), + G_COMPARABLE_ITEM(new_right), + expr->rel_type, &status); + + if (valid) + { + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { status }); + result = SRS_REDUCED; + } + else + result = SRS_UNRESOLVABLE; + + } + + /* Mise à jour de la progression ? */ + + else if (state_left == SRS_WAIT_FOR_SCAN || state_right == SRS_WAIT_FOR_SCAN) + { + if (new_left != expr->left || new_right != expr->right) + *out = g_scan_relational_operation_new(expr->rel_type, new_left, new_right); + + result = SRS_WAIT_FOR_SCAN; + + } + + /* Cas des situations où les expressions ne sont pas exploitables (!) */ + else + { + assert(state_left == SRS_REDUCED && state_right == SRS_REDUCED); + + result = SRS_UNRESOLVABLE; + + } + + /* Sortie propre */ + + exit: + + g_clear_object(&new_left); + g_clear_object(&new_right); + + return result; + +} diff --git a/src/analysis/scan/exprs/relational.h b/src/analysis/scan/exprs/relational.h new file mode 100644 index 0000000..10d58a6 --- /dev/null +++ b/src/analysis/scan/exprs/relational.h @@ -0,0 +1,56 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * relational.h - prototypes pour la gestion des opérations relationnelles + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_RELATIONAL_H +#define _ANALYSIS_SCAN_EXPRS_RELATIONAL_H + + +#include "../expr.h" +#include "../../../glibext/comparison.h" + + + +#define G_TYPE_SCAN_RELATIONAL_OPERATION g_scan_relational_operation_get_type() +#define G_SCAN_RELATIONAL_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_RELATIONAL_OPERATION, GScanRelationalOperation)) +#define G_IS_SCAN_RELATIONAL_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_RELATIONAL_OPERATION)) +#define G_SCAN_RELATIONAL_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_RELATIONAL_OPERATION, GScanRelationalOperationClass)) +#define G_IS_SCAN_RELATIONAL_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_RELATIONAL_OPERATION)) +#define G_SCAN_RELATIONAL_OPERATION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_RELATIONAL_OPERATION, GScanRelationalOperationClass)) + + +/* Opération relationnelle impliquant deux opérandes (instance) */ +typedef struct _GScanRelationalOperation GScanRelationalOperation; + +/* Opération relationnelle impliquant deux opérandes (classe) */ +typedef struct _GScanRelationalOperationClass GScanRelationalOperationClass; + + +/* Indique le type défini pour une opération de relation entre expressions. */ +GType g_scan_relational_operation_get_type(void); + +/* Organise une opération relationnelle entre expressions. */ +GScanExpression *g_scan_relational_operation_new(RichCmpOperation, GScanExpression *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_RELATIONAL_H */ diff --git a/src/analysis/scan/exprs/set-int.h b/src/analysis/scan/exprs/set-int.h new file mode 100644 index 0000000..10ca8d0 --- /dev/null +++ b/src/analysis/scan/exprs/set-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * set-int.h - prototypes internes pour la base d'ensembles de valeurs diverses, de types hétérogènes ou homogènes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_SET_INT_H +#define _ANALYSIS_SCAN_EXPRS_SET_INT_H + + +#include "set.h" + + +#include "../expr-int.h" + + + +/* Base d'un ensemble d'éléments homogènes ou hétérogènes (instance) */ +struct _GScanGenericSet +{ + GScanExpression parent; /* A laisser en premier */ + + GScanExpression **items; /* Liste d'éléments embarqués */ + size_t count; /* Quantité de ces éléments */ + +}; + +/* Base d'un ensemble d'éléments homogènes ou hétérogènes (classe) */ +struct _GScanGenericSetClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un ensemble d'éléments homogènes ou hétérogènes. */ +bool g_scan_generic_set_create(GScanGenericSet *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_SET_INT_H */ diff --git a/src/analysis/scan/exprs/set.c b/src/analysis/scan/exprs/set.c new file mode 100644 index 0000000..438e7e3 --- /dev/null +++ b/src/analysis/scan/exprs/set.c @@ -0,0 +1,407 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * set.c - base d'ensembles de valeurs diverses, de types hétérogènes ou homogènes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "set.h" + + +#include <assert.h> +#include <malloc.h> + + +#include "literal.h" +#include "set-int.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des bases d'ensembles d'éléments. */ +static void g_scan_generic_set_class_init(GScanGenericSetClass *); + +/* Initialise une instance de base d'ensemble d'éléments. */ +static void g_scan_generic_set_init(GScanGenericSet *); + +/* Supprime toutes les références externes. */ +static void g_scan_generic_set_dispose(GScanGenericSet *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_generic_set_finalize(GScanGenericSet *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_generic_set_reduce(const GScanGenericSet *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réduit une expression à une forme booléenne. */ +static bool g_scan_generic_set_reduce_to_boolean(const GScanGenericSet *, GScanContext *, GScanScope *, GScanExpression **); + +/* Dénombre les éléments portés par une expression. */ +static bool g_scan_generic_set_count_items(const GScanGenericSet *, GScanContext *, size_t *); + +/* Fournit un élément donné issu d'un ensemble constitué. */ +static bool g_scan_generic_set_get_item(const GScanGenericSet *, size_t, GScanContext *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une base d'ensembles d'éléments homogènes ou hétérogènes. */ +G_DEFINE_TYPE(GScanGenericSet, g_scan_generic_set, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des bases d'ensembles d'éléments. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_generic_set_class_init(GScanGenericSetClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_generic_set_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_generic_set_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->reduce = (reduce_expr_fc)g_scan_generic_set_reduce; + expr->reduce_to_bool = (reduce_expr_to_bool_fc)g_scan_generic_set_reduce_to_boolean; + expr->count = (count_scan_expr_fc)g_scan_generic_set_count_items; + expr->get = (get_scan_expr_fc)g_scan_generic_set_get_item; + +} + + +/****************************************************************************** +* * +* Paramètres : set = instance à initialiser. * +* * +* Description : Initialise une instance de base d'ensemble d'éléments. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_generic_set_init(GScanGenericSet *set) +{ + set->items = NULL; + set->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : set = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_generic_set_dispose(GScanGenericSet *set) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < set->count; i++) + g_clear_object(&set->items[i]); + + G_OBJECT_CLASS(g_scan_generic_set_parent_class)->dispose(G_OBJECT(set)); + +} + + +/****************************************************************************** +* * +* Paramètres : set = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_generic_set_finalize(GScanGenericSet *set) +{ + if (set->items != NULL) + free(set->items); + + G_OBJECT_CLASS(g_scan_generic_set_parent_class)->finalize(G_OBJECT(set)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue un ensemble d'éléments homogènes ou hétérogènes. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_generic_set_new(void) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_GENERIC_SET, NULL); + + if (!g_scan_generic_set_create(G_SCAN_GENERIC_SET(result))) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : set = instance à initialiser pleinement. * +* * +* Description : Met en place un ensemble d'éléments homogènes ou hétérogènes.* +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_generic_set_create(GScanGenericSet *set) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(set), SRS_PENDING); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : set = ensemble à compléter. * +* item = nouvel élément à intégrer. * +* * +* Description : Ajoute un nouvel élément à un ensemble. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_generic_set_add_item(GScanGenericSet *set, GScanExpression *item) +{ + set->items = realloc(set->items, ++set->count * sizeof(GScanExpression *)); + + set->items[set->count - 1] = item; + g_object_ref(G_OBJECT(item)); + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_generic_set_reduce(const GScanGenericSet *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + size_t i; /* Boucle de parcours #1 */ + GScanExpression *item; /* Elément en cours d'analyse */ + GScanExpression *new; /* Nouvelle réduction obtenue */ + ScanReductionState state; /* Etat synthétisé d'un élément*/ + size_t k; /* Boucle de parcours #2 */ + + result = SRS_REDUCED; + + for (i = 0; i < expr->count; i++) + { + item = expr->items[i]; + + state = g_scan_expression_reduce(item, ctx, scope, &new); + if (state == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + g_clear_object(out); + break; + } + + if (state == SRS_WAIT_FOR_SCAN) + result = SRS_WAIT_FOR_SCAN; + + if (new != item) + { + if (*out == NULL) + { + *out = g_scan_generic_set_new(); + + for (k = 0; k < i; k++) + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET(*out), expr->items[k]); + + } + + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET(*out), new); + + } + + else + { + if (*out != NULL) + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET(*out), item); + } + + g_object_unref(G_OBJECT(new)); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme booléenne. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_generic_set_reduce_to_boolean(const GScanGenericSet *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + + result = true; + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ expr->count > 0 }); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* count = quantité d'éléments déterminée. [OUT] * +* * +* Description : Dénombre les éléments portés par une expression. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_generic_set_count_items(const GScanGenericSet *expr, GScanContext *ctx, size_t *count) +{ + bool result; /* Bilan à retourner */ + + result = true; + + *count = expr->count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* index = indice de l'élément à transférer. * +* ctx = contexte de suivi de l'analyse courante. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Fournit un élément donné issu d'un ensemble constitué. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_generic_set_get_item(const GScanGenericSet *expr, size_t index, GScanContext *ctx, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + + result = (index < expr->count); + + if (result) + *out = expr->items[index]; + + return result; + +} diff --git a/src/analysis/scan/exprs/set.h b/src/analysis/scan/exprs/set.h new file mode 100644 index 0000000..c9fb3b3 --- /dev/null +++ b/src/analysis/scan/exprs/set.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * set.h - prototypes pour la base d'ensembles de valeurs diverses, de types hétérogènes ou homogènes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_SET_H +#define _ANALYSIS_SCAN_EXPRS_SET_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_GENERIC_SET g_scan_generic_set_get_type() +#define G_SCAN_GENERIC_SET(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_GENERIC_SET, GScanGenericSet)) +#define G_IS_SCAN_GENERIC_SET(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_GENERIC_SET)) +#define G_SCAN_GENERIC_SET_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_GENERIC_SET, GScanGenericSetClass)) +#define G_IS_SCAN_GENERIC_SET_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_GENERIC_SET)) +#define G_SCAN_GENERIC_SET_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_GENERIC_SET, GScanGenericSetClass)) + + +/* Base d'un ensemble d'éléments homogènes ou hétérogènes (instance) */ +typedef struct _GScanGenericSet GScanGenericSet; + +/* Base d'un ensemble d'éléments homogènes ou hétérogènes (classe) */ +typedef struct _GScanGenericSetClass GScanGenericSetClass; + + +/* Indique le type défini pour une base d'ensembles d'éléments homogènes ou hétérogènes. */ +GType g_scan_generic_set_get_type(void); + +/* Constitue un ensemble d'éléments homogènes ou hétérogènes. */ +GScanExpression *g_scan_generic_set_new(void); + +/* Ajoute un nouvel élément à un ensemble. */ +void g_scan_generic_set_add_item(GScanGenericSet *, GScanExpression *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_SET_H */ diff --git a/src/analysis/scan/exprs/setcounter-int.h b/src/analysis/scan/exprs/setcounter-int.h new file mode 100644 index 0000000..c9e3da5 --- /dev/null +++ b/src/analysis/scan/exprs/setcounter-int.h @@ -0,0 +1,69 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * setcounter-int.h - prototypes internes pour le décompte global de correspondances locales + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_SETCOUNTER_INT_H +#define _ANALYSIS_SCAN_EXPRS_SETCOUNTER_INT_H + + +#include "setcounter.h" + + +#include "../expr-int.h" + + + +/* Décompte global de correspondances locales (instance) */ +struct _GScanSetMatchCounter +{ + GScanExpression parent; /* A laisser en premier */ + + union + { + const GSearchPattern **patterns; /* Motifs associés */ + GSearchPattern **ref_patterns; /* Motifs associés */ + }; + size_t count; /* Nombre de ces motifs */ + bool shared; /* Définition de propriété */ + + ScanSetCounterType type; /* Type de décompte */ + size_t number; /* Eventuel volume associé */ + +}; + +/* Décompte global de correspondances locales (classe) */ +struct _GScanSetMatchCounterClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un décompte de motifs avec correspondances. */ +bool g_scan_set_match_counter_create_shared(GScanSetMatchCounter *, const GSearchPattern ** const, size_t); + +/* Met en place un décompte de motifs avec correspondances. */ +bool g_scan_set_match_counter_create_and_ref(GScanSetMatchCounter *, GSearchPattern ** const, size_t); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_SETCOUNTER_INT_H */ diff --git a/src/analysis/scan/exprs/setcounter.c b/src/analysis/scan/exprs/setcounter.c new file mode 100644 index 0000000..bed315e --- /dev/null +++ b/src/analysis/scan/exprs/setcounter.c @@ -0,0 +1,477 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * setcounter.c - décompte global de correspondances locales + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "setcounter.h" + + +#include <assert.h> +#include <string.h> + + +#include "setcounter-int.h" +#include "literal.h" + + + +/* --------------------- INSTANCIATION D'UNE FORME DE CONDITION --------------------- */ + + +/* Initialise la classe des opérations booléennes. */ +static void g_scan_set_match_counter_class_init(GScanSetMatchCounterClass *); + +/* Initialise une instance d'opération booléenne. */ +static void g_scan_set_match_counter_init(GScanSetMatchCounter *); + +/* Supprime toutes les références externes. */ +static void g_scan_set_match_counter_dispose(GScanSetMatchCounter *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_set_match_counter_finalize(GScanSetMatchCounter *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_set_match_counter_reduce(const GScanSetMatchCounter *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INSTANCIATION D'UNE FORME DE CONDITION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un décompte de résultats lors d'une recherche de motifs. */ +G_DEFINE_TYPE(GScanSetMatchCounter, g_scan_set_match_counter, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des opérations booléennes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_match_counter_class_init(GScanSetMatchCounterClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_set_match_counter_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_set_match_counter_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)NULL; + expr->reduce = (reduce_expr_fc)g_scan_set_match_counter_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser. * +* * +* Description : Initialise une instance d'opération booléenne. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_match_counter_init(GScanSetMatchCounter *counter) +{ + counter->patterns = NULL; + counter->count = 0; + counter->shared = true; + + counter->type = SSCT_NONE; + counter->number = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_match_counter_dispose(GScanSetMatchCounter *counter) +{ + size_t i; /* Boucle de parcours */ + + if (!counter->shared) + for (i = 0; i < counter->count; i++) + g_clear_object(&counter->ref_patterns[i]); + + G_OBJECT_CLASS(g_scan_set_match_counter_parent_class)->dispose(G_OBJECT(counter)); + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_set_match_counter_finalize(GScanSetMatchCounter *counter) +{ + if (counter->patterns != NULL) + free(counter->patterns); + + G_OBJECT_CLASS(g_scan_set_match_counter_parent_class)->finalize(G_OBJECT(counter)); + +} + + +/****************************************************************************** +* * +* Paramètres : patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* * +* Description : Constitue un décompte de motifs avec correspondances. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_set_match_counter_new_shared(const GSearchPattern ** const patterns, size_t count) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_SET_MATCH_COUNTER, NULL); + + if (!g_scan_set_match_counter_create_shared(G_SCAN_SET_MATCH_COUNTER(result), patterns, count)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : counter = instance à initialiser pleinement. * +* patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* * +* Description : Met en place un décompte de motifs avec correspondances. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_set_match_counter_create_shared(GScanSetMatchCounter *counter, const GSearchPattern ** const patterns, size_t count) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(counter), SRS_WAIT_FOR_SCAN); + if (!result) goto exit; + + counter->patterns = malloc(count * sizeof(GSearchPattern *)); + counter->count = count; + + memcpy(counter->patterns, patterns, count * sizeof(GSearchPattern *)); + + counter->shared = true; + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* * +* Description : Constitue un décompte de motifs avec correspondances. * +* * +* Retour : Expression mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_set_match_counter_new(GSearchPattern ** const patterns, size_t count) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_SET_MATCH_COUNTER, NULL); + + if (!g_scan_set_match_counter_create_and_ref(G_SCAN_SET_MATCH_COUNTER(result), patterns, count)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : counter = instance à initialiser pleinement. * +* patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* * +* Description : Met en place un décompte de motifs avec correspondances. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_set_match_counter_create_and_ref(GScanSetMatchCounter *counter, GSearchPattern ** const patterns, size_t count) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(counter), SRS_WAIT_FOR_SCAN); + if (!result) goto exit; + + counter->patterns = malloc(count * sizeof(GSearchPattern *)); + counter->count = count; + + memcpy(counter->patterns, patterns, count * sizeof(GSearchPattern *)); + + for (i = 0; i < count; i++) + g_object_ref(G_OBJECT(patterns[i])); + + counter->shared = false; + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : counter = décompte à compléter. * +* patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* * +* Description : Ajoute de nouveaux motifs à un ensemble à décompter. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_set_match_counter_add_extra_shared_patterns(GScanSetMatchCounter *counter, const GSearchPattern ** const patterns, size_t count) +{ + size_t first; /* Premier emplacement libre */ + + assert(counter->shared); + + first = counter->count; + + counter->count += count; + counter->patterns = realloc(counter->patterns, counter->count * sizeof(GSearchPattern *)); + + memcpy(counter->patterns + first, patterns, count * sizeof(GSearchPattern *)); + +} + + +/****************************************************************************** +* * +* Paramètres : counter = décompte à compléter. * +* patterns = motifs à impliquer. * +* count = quantité de ces motifs. * +* * +* Description : Ajoute de nouveaux motifs à un ensemble à décompter. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_set_match_counter_add_and_ref_extra_patterns(GScanSetMatchCounter *counter, GSearchPattern ** const patterns, size_t count) +{ + size_t first; /* Premier emplacement libre */ + size_t i; /* Boucle de parcours */ + + assert(!counter->shared); + + first = counter->count; + + counter->count += count; + counter->patterns = realloc(counter->patterns, counter->count * sizeof(GSearchPattern *)); + + memcpy(counter->patterns + first, patterns, count * sizeof(GSearchPattern *)); + + for (i = 0; i < count; i++) + g_object_ref(G_OBJECT(patterns[i])); + +} + + +/****************************************************************************** +* * +* Paramètres : counter = décompte à configurer. * +* type = type de décompte à considérer. * +* number = volume minimal de motifs avec correspondances. * +* * +* Description : Précise le volume de motifs avec correspondances à retrouver.* +* * +* Retour : Bilan de validité des arguments fournis. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_set_match_counter_define_expected_matches(GScanSetMatchCounter *counter, ScanSetCounterType type, size_t *number) +{ + bool result; /* Bilan à retourner */ + + counter->type = type; + + if (type == SSCT_NUMBER) + { + counter->number = *number; + result = (counter->number <= counter->count); + } + else + result = true; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_set_match_counter_reduce(const GScanSetMatchCounter *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + size_t matched; /* Qté de motifs avec résultats*/ + size_t i; /* Boucle de parcours */ + GScanMatches *matches; /* Série de correspondances */ + size_t count; /* Quantité de correspondances */ + bool status; /* Bilan d'évaluation finale */ + + if (g_scan_context_is_scan_done(ctx)) + { + matched = 0; + + for (i = 0; i < expr->count; i++) + { + matches = g_scan_context_get_full_matches(ctx, expr->patterns[i]); + + if (matches != NULL) + { + count = g_scan_matches_count(matches); + + if (count > 0) + matched++; + + g_object_unref(G_OBJECT(matches)); + + } + + } + + switch (expr->type) + { + case SSCT_NONE: + status = (matched == 0); + break; + + case SSCT_ANY: + status = (matched >= 1); + break; + + case SSCT_ALL: + status = (matched == expr->count); + break; + + case SSCT_NUMBER: + status = (matched >= expr->number); + break; + + } + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, &status); + + result = SRS_REDUCED; + + } + else + result = SRS_WAIT_FOR_SCAN; + + return result; + +} diff --git a/src/analysis/scan/exprs/setcounter.h b/src/analysis/scan/exprs/setcounter.h new file mode 100644 index 0000000..28c92b4 --- /dev/null +++ b/src/analysis/scan/exprs/setcounter.h @@ -0,0 +1,81 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * setcounter.h - prototypes pour le décompte global de correspondances locales + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_SETCOUNTER_H +#define _ANALYSIS_SCAN_EXPRS_SETCOUNTER_H + + +#include <glib-object.h> + + +#include "../expr.h" +#include "../pattern.h" + + + +#define G_TYPE_SCAN_SET_MATCH_COUNTER g_scan_set_match_counter_get_type() +#define G_SCAN_SET_MATCH_COUNTER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_SET_MATCH_COUNTER, GScanSetMatchCounter)) +#define G_IS_SCAN_SET_MATCH_COUNTER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_SET_MATCH_COUNTER)) +#define G_SCAN_SET_MATCH_COUNTER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_SET_MATCH_COUNTER, GScanSetMatchCounterClass)) +#define G_IS_SCAN_SET_MATCH_COUNTER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_SET_MATCH_COUNTER)) +#define G_SCAN_SET_MATCH_COUNTER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_SET_MATCH_COUNTER, GScanSetMatchCounterClass)) + + +/* Décompte global de correspondances locales (instance) */ +typedef struct _GScanSetMatchCounter GScanSetMatchCounter; + +/* Décompte global de correspondances locales (classe) */ +typedef struct _GScanSetMatchCounterClass GScanSetMatchCounterClass; + + +/* Indique le type défini pour un décompte de résultats lors d'une recherche de motifs. */ +GType g_scan_set_match_counter_get_type(void); + +/* Met en place un décompte de correspondances obtenues. */ +GScanExpression *g_scan_set_match_counter_new_shared(const GSearchPattern ** const, size_t); + +/* Met en place un décompte de correspondances obtenues. */ +GScanExpression *g_scan_set_match_counter_new(GSearchPattern ** const, size_t); + +/* Ajoute de nouveaux motifs à un ensemble à décompter. */ +void g_scan_set_match_counter_add_extra_shared_patterns(GScanSetMatchCounter *, const GSearchPattern ** const, size_t); + +/* Ajoute de nouveaux motifs à un ensemble à décompter. */ +void g_scan_set_match_counter_add_and_ref_extra_patterns(GScanSetMatchCounter *, GSearchPattern ** const, size_t); + +/* Formes de volume de correspondances */ +typedef enum _ScanSetCounterType +{ + SSCT_NONE, /* Aucun motif avec résultats */ + SSCT_ANY, /* Au moins un motif trouvé */ + SSCT_ALL, /* Tous les motifs présents */ + SSCT_NUMBER, /* Au moins n motifs avec rés. */ + +} ScanSetCounterType; + +/* Précise le volume de motifs avec correspondances à retrouver. */ +bool g_scan_set_match_counter_define_expected_matches(GScanSetMatchCounter *, ScanSetCounterType, size_t *); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_SETCOUNTER_H */ diff --git a/src/analysis/scan/exprs/strop-int.h b/src/analysis/scan/exprs/strop-int.h new file mode 100644 index 0000000..c2b40cf --- /dev/null +++ b/src/analysis/scan/exprs/strop-int.h @@ -0,0 +1,62 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * strop-int.h - prototypes internes pour la gestion des opérations booléennes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_STROP_INT_H +#define _ANALYSIS_SCAN_EXPRS_STROP_INT_H + + +#include "strop.h" + + +#include "../expr-int.h" +#include "../../../common/extstr.h" + + + +/* Opération booléenne avec un ou deux opérandes (instance) */ +struct _GScanStringOperation +{ + GScanExpression parent; /* A laisser en premier */ + + StringOperationType type; /* Type d'opération menée */ + bool case_sensitive; /* Respect de la casse ? */ + + GScanExpression *left; /* Expression impactée #1 */ + GScanExpression *right; /* Expression impactée #2 */ + +}; + +/* Opération booléenne avec un ou deux opérandes (classe) */ +struct _GScanStringOperationClass +{ + GScanExpressionClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une expression d'opération traite une chaîne. */ +bool g_scan_string_operation_create(GScanStringOperation *, StringOperationType, GScanExpression *, GScanExpression *, bool); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_STROP_INT_H */ diff --git a/src/analysis/scan/exprs/strop.c b/src/analysis/scan/exprs/strop.c new file mode 100644 index 0000000..c188c36 --- /dev/null +++ b/src/analysis/scan/exprs/strop.c @@ -0,0 +1,455 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * strop.c - gestion des opérations booléennes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "strop.h" + + +#include <assert.h> +#include <string.h> +#include <strings.h> + + +#include "strop-int.h" +#include "literal.h" + + + +/* --------------------- INTRODUCTION D'UNE NOUVELLE EXPRESSION --------------------- */ + + +/* Initialise la classe des opérations visant des chaînes. */ +static void g_scan_string_operation_class_init(GScanStringOperationClass *); + +/* Initialise une instance d'opération visant une chaîne. */ +static void g_scan_string_operation_init(GScanStringOperation *); + +/* Supprime toutes les références externes. */ +static void g_scan_string_operation_dispose(GScanStringOperation *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_string_operation_finalize(GScanStringOperation *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Réduit une expression à une forme plus simple. */ +static ScanReductionState g_scan_string_operation_reduce(const GScanStringOperation *, GScanContext *, GScanScope *, GScanExpression **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE EXPRESSION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une opération traitant une chaîne de caractères. */ +G_DEFINE_TYPE(GScanStringOperation, g_scan_string_operation, G_TYPE_SCAN_EXPRESSION); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des opérations visant des chaînes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_operation_class_init(GScanStringOperationClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanExpressionClass *expr; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_string_operation_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_string_operation_finalize; + + expr = G_SCAN_EXPRESSION_CLASS(klass); + + expr->cmp_rich = (compare_expr_rich_fc)NULL; + expr->reduce = (reduce_expr_fc)g_scan_string_operation_reduce; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser. * +* * +* Description : Initialise une instance d'opération visant une chaîne. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_operation_init(GScanStringOperation *op) +{ + op->left = NULL; + op->right = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_operation_dispose(GScanStringOperation *op) +{ + g_clear_object(&op->left); + g_clear_object(&op->right); + + G_OBJECT_CLASS(g_scan_string_operation_parent_class)->dispose(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_operation_finalize(GScanStringOperation *op) +{ + G_OBJECT_CLASS(g_scan_string_operation_parent_class)->finalize(G_OBJECT(op)); + +} + + +/****************************************************************************** +* * +* Paramètres : type = type d'opération booléenne à représenter. * +* first = premier opérande concerné. * +* second = éventuel second opérande impliqué ou NULL. * +* sensitive = détermine la prise en compte de la casse. * +* * +* Description : Organise un appel de fonction avec ses arguments. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanExpression *g_scan_string_operation_new(StringOperationType type, GScanExpression *first, GScanExpression *second, bool sensitive) +{ + GScanExpression *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_STRING_OPERATION, NULL); + + if (!g_scan_string_operation_create(G_SCAN_STRING_OPERATION(result), type, first, second, sensitive)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : op = instance à initialiser pleinement. * +* type = type d'opération booléenne à représenter. * +* left = premier opérande concerné. * +* right = éventuel second opérande impliqué ou NULL. * +* sensitive = détermine la prise en compte de la casse. * +* * +* Description : Met en place une expression d'opération traite une chaîne. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_string_operation_create(GScanStringOperation *op, StringOperationType type, GScanExpression *left, GScanExpression *right, bool sensitive) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_expression_create(G_SCAN_EXPRESSION(op), SRS_PENDING); + if (!result) goto exit; + + op->type = type; + + switch (type) + { + case SOT_CONTAINS: + case SOT_STARTSWITH: + case SOT_ENDSWITH: + op->case_sensitive = sensitive; + break; + + case SOT_MATCHES: + break; + + case SOT_IEQUALS: + assert(!sensitive); + op->case_sensitive = false; + break; + + } + + op->left = left; + g_object_ref(G_OBJECT(op->left)); + + op->right = right; + g_object_ref(G_OBJECT(op->right)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : expr = expression à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static ScanReductionState g_scan_string_operation_reduce(const GScanStringOperation *expr, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + ScanReductionState result; /* Etat synthétisé à retourner */ + GScanExpression *new_left; /* Expression réduite (gauche) */ + GScanExpression *new_right; /* Expression réduite (droite) */ + ScanReductionState state_left; /* Etat synthétisé #1 */ + ScanReductionState state_right; /* Etat synthétisé #2 */ + GScanLiteralExpression *op_left; /* Opérande gauche final */ + GScanLiteralExpression *op_right; /* Opérande droite final */ + const sized_string_t *strings[2]; /* Chaînes en jeu */ + const void *found; /* Présence d'une bribe ? */ + bool status; /* Bilan de comparaison #1 */ + int ret; /* Bilan de comparaison #2 */ + size_t offset; /* Point de départ d'analyse */ + const regex_t *preg; /* Expression rationnelle */ + + /* Réduction des éléments considérés */ + + new_left = NULL; + new_right = NULL; + + state_left = g_scan_expression_reduce(expr->left, ctx, scope, &new_left); + if (state_left == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + state_right = g_scan_expression_reduce(expr->right, ctx, scope, &new_right); + if (state_right == SRS_UNRESOLVABLE) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + /* Construction d'une réduction locale ? */ + + if (G_IS_SCAN_LITERAL_EXPRESSION(new_left) && G_IS_SCAN_LITERAL_EXPRESSION(new_right)) + { + op_left = G_SCAN_LITERAL_EXPRESSION(new_left); + op_right = G_SCAN_LITERAL_EXPRESSION(new_right); + + if (!g_scan_literal_expression_get_string_value(op_left, &strings[0])) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + result = SRS_REDUCED; + + switch (expr->type) + { + case SOT_CONTAINS: + + if (!g_scan_literal_expression_get_string_value(op_right, &strings[1])) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (expr->case_sensitive) + found = memmem(strings[0]->data, strings[0]->len, strings[1]->data, strings[1]->len); + + else + found = memcasemem(strings[0]->data, strings[0]->len, strings[1]->data, strings[1]->len); + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { found != NULL }); + break; + + case SOT_STARTSWITH: + + if (!g_scan_literal_expression_get_string_value(op_right, &strings[1])) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (strings[0]->len < strings[1]->len) + status = false; + + else + { + if (expr->case_sensitive) + ret = memcmp(strings[0]->data, strings[1]->data, strings[1]->len); + else + ret = memcasecmp(strings[0]->data, strings[1]->data, strings[1]->len); + + status = (ret == 0); + + } + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, &status); + break; + + case SOT_ENDSWITH: + + if (!g_scan_literal_expression_get_string_value(op_right, &strings[1])) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (strings[0]->len < strings[1]->len) + status = false; + + else + { + offset = strings[0]->len - strings[1]->len; + + if (expr->case_sensitive) + ret = memcmp(strings[0]->data + offset, strings[1]->data, strings[1]->len); + else + ret = memcasecmp(strings[0]->data + offset, strings[1]->data, strings[1]->len); + + status = (ret == 0); + + } + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, &status); + break; + + case SOT_MATCHES: + + if (!g_scan_literal_expression_get_regex_value(op_right, &preg)) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + ret = regexec(preg, strings[0]->data, 0, NULL, 0); + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []) { ret != REG_NOMATCH }); + break; + + case SOT_IEQUALS: + + if (!g_scan_literal_expression_get_string_value(op_right, &strings[1])) + { + result = SRS_UNRESOLVABLE; + goto exit; + } + + if (strings[0]->len != strings[1]->len) + status = false; + + else + { + ret = memcasecmp(strings[0]->data, strings[1]->data, strings[1]->len); + status = (ret == 0); + } + + *out = g_scan_literal_expression_new(LVT_BOOLEAN, &status); + break; + + } + + } + + /* Mise à jour de la progression ? */ + + else if (state_left == SRS_WAIT_FOR_SCAN || state_right == SRS_WAIT_FOR_SCAN) + { + if (new_left != expr->left || new_right != expr->right) + *out = g_scan_string_operation_new(expr->type, new_left, new_right, expr->case_sensitive); + + result = SRS_WAIT_FOR_SCAN; + + } + + /* Cas des situations où les expressions ne sont pas exploitables (!) */ + else + { + assert(state_left == SRS_REDUCED && state_right == SRS_REDUCED); + + result = SRS_UNRESOLVABLE; + + } + + /* Sortie propre */ + + exit: + + g_clear_object(&new_left); + g_clear_object(&new_right); + + return result; + +} diff --git a/src/analysis/scan/exprs/strop.h b/src/analysis/scan/exprs/strop.h new file mode 100644 index 0000000..0a32269 --- /dev/null +++ b/src/analysis/scan/exprs/strop.h @@ -0,0 +1,67 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * strop.h - prototypes pour la gestion des opérations booléennes + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_EXPRS_STROP_H +#define _ANALYSIS_SCAN_EXPRS_STROP_H + + +#include "../expr.h" + + + +#define G_TYPE_SCAN_STRING_OPERATION g_scan_string_operation_get_type() +#define G_SCAN_STRING_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_STRING_OPERATION, GScanStringOperation)) +#define G_IS_SCAN_STRING_OPERATION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_STRING_OPERATION)) +#define G_SCAN_STRING_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_STRING_OPERATION, GScanStringOperationClass)) +#define G_IS_SCAN_STRING_OPERATION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_STRING_OPERATION)) +#define G_SCAN_STRING_OPERATION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_STRING_OPERATION, GScanStringOperationClass)) + + +/* Opération booléenne avec un ou deux opérandes (instance) */ +typedef struct _GScanStringOperation GScanStringOperation; + +/* Opération booléenne avec un ou deux opérandes (classe) */ +typedef struct _GScanStringOperationClass GScanStringOperationClass; + + +/* Types d'opérations booléennes supportées */ +typedef enum _StringOperationType +{ + SOT_CONTAINS, /* Opérateurs "[i]contains" */ + SOT_STARTSWITH, /* Opérateurs "[i]startswith" */ + SOT_ENDSWITH, /* Opérateurs "[i]endswith" */ + SOT_MATCHES, /* Opérateur "matches" */ + SOT_IEQUALS, /* Opérateur "iequals" */ + +} StringOperationType; + + +/* Indique le type défini pour une opération traitant une chaîne de caractères. */ +GType g_scan_string_operation_get_type(void); + +/* Organise un appel de fonction avec ses arguments. */ +GScanExpression *g_scan_string_operation_new(StringOperationType, GScanExpression *, GScanExpression *, bool); + + + +#endif /* _ANALYSIS_SCAN_EXPRS_STROP_H */ diff --git a/src/analysis/scan/grammar.y b/src/analysis/scan/grammar.y new file mode 100644 index 0000000..2d985a7 --- /dev/null +++ b/src/analysis/scan/grammar.y @@ -0,0 +1,1905 @@ + +%{ + +#include "decl.h" +#include "tokens.h" + + +/* Affiche un message d'erreur suite à l'analyse en échec. */ +static int yyerror(GContentScanner *, yyscan_t, GScanRule **, sized_string_t *, sized_string_t *, char *); + +#define raise_error(msg) \ + yyerror(scanner, yyscanner, built_rule, tmp_0, tmp_1, msg) + +%} + + +%code requires { + +#define YY_TYPEDEF_YY_SCANNER_T +typedef void *yyscan_t; + +#include <assert.h> +#include <malloc.h> +#include <stdio.h> + +#include <i18n.h> + +#include "core.h" +#include "scanner.h" +#include "exprs/access.h" +#include "exprs/arithmetic.h" +#include "exprs/call.h" +#include "exprs/extract.h" +#include "exprs/handler.h" +#include "exprs/intersect.h" +#include "exprs/item.h" +#include "exprs/literal.h" +#include "exprs/logical.h" +#include "exprs/set.h" +#include "exprs/setcounter.h" +#include "exprs/relational.h" +#include "exprs/strop.h" +#include "patterns/customizer.h" +#include "patterns/modifier.h" +#include "patterns/modifiers/list.h" +#include "patterns/modifiers/pipe.h" +#include "patterns/tokens/hex.h" +#include "patterns/tokens/plain.h" +#include "patterns/tokens/nodes/any.h" +#include "patterns/tokens/nodes/choice.h" +#include "patterns/tokens/nodes/masked.h" +#include "patterns/tokens/nodes/not.h" +#include "patterns/tokens/nodes/plain.h" +#include "patterns/tokens/nodes/sequence.h" +#include "../../core/logs.h" + +} + +%union { + + unsigned long long unsigned_integer; /* Valeur entière #1 */ + signed long long signed_integer; /* Valeur entière #2 */ + //double floating_number; /* Valeur à virgule flottante */ + sized_string_t sized_cstring; /* Chaîne de caractères */ + //char byte; /* Octet unique */ + + + + + sized_string_t *tmp_cstring; /* Série d'octets reconstituée */ + + struct + { + sized_string_t *tmp_values; /* Série d'octets partiels */ + sized_string_t *tmp_masks; /* Masques associés */ + } masked; + + ScanRuleFlags rule_flags; /* Fanions pour règle */ + + GScanTokenNode *node; /* Bribe de motif à intégrer */ + GSearchPattern *pattern; /* Nouveau motif à considérer */ + + GScanTokenModifier *modifier; /* Modificateur pour texte */ + modifier_arg_t mod_arg; /* Argument pour modificateur */ + ScanPlainNodeFlags str_flags; /* Fanions pour texte */ + + GScanExpression *expr; /* Expression de condition */ + + struct { + GScanExpression **args; /* Liste d'arguments à fournir */ + size_t count; /* Quantité de ces arguments */ + } args_list; + +} + + +/** + * Cf. + * http://stackoverflow.com/questions/34418381/how-to-reference-lex-or-parse-parameters-in-flex-rules/34420950 + */ + +%define api.pure full + +%parse-param { GContentScanner *scanner } { yyscan_t yyscanner } { GScanRule **built_rule } { sized_string_t *tmp_0} { sized_string_t *tmp_1} +%lex-param { yyscan_t yyscanner } { sized_string_t *tmp_0} { sized_string_t *tmp_1} + +%code provides { + +#define YY_DECL \ + int rost_lex(YYSTYPE *yylval_param, yyscan_t yyscanner, sized_string_t *tmp_0, sized_string_t *tmp_1) + +YY_DECL; + +} + + +%token INCLUDE "include" + +%token RAW_RULE "rule" +%token RULE_IDENTIFIER + +%token META "meta" +%token BYTES "bytes" +%token CONDITION "condition" + +%token INFO_KEY + + + +%token BYTES_ID +%token BYTES_FUZZY_ID +%token BYTES_ID_COUNTER +%token BYTES_FUZZY_ID_COUNTER +%token BYTES_ID_START +%token BYTES_FUZZY_ID_START +%token BYTES_ID_LENGTH +%token BYTES_FUZZY_ID_LENGTH +%token BYTES_ID_END +%token BYTES_FUZZY_ID_END +%token NAME + + +%token NOCASE "nocase" +%token FULLWORD "fullword" +%token PRIVATE "private" +%token GLOBAL "global" + + +%token HEX_BYTES +%token FULL_MASK +%token SEMI_MASK + + +%token REGEX_BYTES +%token REGEX_CLASSES +%token REGEX_RANGE + + + +%token BRACE_IN "{" +%token BRACE_OUT "}" +%token ASSIGN "=" +%token COLON ":" + + +%token PLAIN_TEXT +%token ESCAPED_TEXT + +%token TRUE_ "true" +%token FALSE_ "false" +%token SIGNED_INTEGER +%token UNSIGNED_INTEGER + +%token KB MB GB + +%token AND "and" +%token OR "or" +%token NOT "not" + +%token LT "<" +%token LE "<=" +%token EQ "==" +%token NE "!=" +%token GT ">" +%token GE ">=" + +%token CONTAINS "contains" +%token STARTSWITH "startswith" +%token ENDSWITH "endswith" +%token MATCHES "matches" +%token ICONTAINS "icontains" +%token ISTARTSWITH "istartswith" +%token IENDSWITH "iendswith" +%token IEQUALS "iequals" + +%token PLUS "+" +%token MINUS "-" +%token MUL "*" +%token DIV "/" +%token MOD "%" +%token TILDE "~" + +%token HOOK_O "[" +%token HOOK_C "]" + +%token QUESTION "?" + +%token PAREN_O "(" +%token PAREN_C ")" +%token COMMA "," +%token DOT "." +%token PIPE "|" + +%token MOD_GROUP_O "((" +%token MOD_GROUP_C "))" + +%token NONE "none" +%token ANY "any" +%token ALL "all" +%token OF "of" +%token THEM "them" +%token IN "in" + + +%type <sized_cstring> RULE_IDENTIFIER + +%type <sized_cstring> INFO_KEY + +%type <sized_cstring> BYTES_ID +%type <sized_cstring> BYTES_FUZZY_ID +%type <sized_cstring> BYTES_ID_COUNTER +%type <sized_cstring> BYTES_FUZZY_ID_COUNTER +%type <sized_cstring> BYTES_ID_START +%type <sized_cstring> BYTES_FUZZY_ID_START +%type <sized_cstring> BYTES_ID_LENGTH +%type <sized_cstring> BYTES_FUZZY_ID_LENGTH +%type <sized_cstring> BYTES_ID_END +%type <sized_cstring> BYTES_FUZZY_ID_END +%type <sized_cstring> NAME + + +%type <signed_integer> SIGNED_INTEGER +%type <unsigned_integer> UNSIGNED_INTEGER + +%type <rule_flags> rule_flags +%type <rule_flags> rule_flag + +%type <sized_cstring> PLAIN_TEXT +%type <tmp_cstring> ESCAPED_TEXT + +%type <tmp_cstring> HEX_BYTES +%type <unsigned_integer> FULL_MASK +%type <masked> SEMI_MASK + +%type <tmp_cstring> REGEX_BYTES + + + +%type <pattern> str_pattern + +%type <modifier> modifiers +%type <modifier> _modifiers + //%type <modifier> chained_modifiers +%type <modifier> mod_stage +%type <modifier> modifier +%type <modifier> modifier_args +%type <mod_arg> modifier_arg + +%type <str_flags> str_flags + + +%type <pattern> hex_pattern +%type <node> hex_tokens +%type <node> _hex_tokens +%type <node> hex_token +%type <node> hex_range +%type <node> hex_choices + + + +%type <expr> cexpression _cexpression + +%type <expr> literal +%type <expr> chain_items +%type <expr> chain_item +%type <args_list> call_args +%type <expr> logical_expr +%type <expr> relational_expr +%type <expr> string_op +%type <expr> arithm_expr +%type <expr> set_match_counter +%type <expr> pattern_set +%type <expr> pattern_set_items +%type <expr> set +%type <expr> set_items +%type <expr> intersection +%type <expr> pattern_handler +%type <expr> _pattern_handler + + + + + +%left PIPE + + + +%left OR +%left AND +%left EQ NE +%left CONTAINS STARTSWITH ENDSWITH MATCHES ICONTAINS ISTARTSWITH IENDSWITH IEQUALS +%left LT LE GT GE +%left PLUS MINUS +%left MUL DIV MOD +%left IN +%right NOT + + + +%left HOOK_O HOOK_C + + + %destructor { g_object_unref(G_OBJECT($$)); } <node> + + %destructor { g_object_unref(G_OBJECT($$)); } <pattern> + + %destructor { g_object_unref(G_OBJECT($$)); } <modifier> + + %destructor { g_object_unref(G_OBJECT($$)); } <expr> + + %destructor { + size_t __i; + + for (__i = 0; __i < $$.count; __i++) + g_object_unref(G_OBJECT($$.args[__i])); + + if ($$.args != NULL) + free($$.args); + + } <args_list> + + +%% + + rules : /* empty */ + | external rules + | rule + { + g_content_scanner_add_rule(scanner, *built_rule); + g_clear_object(built_rule); + } + rules + ; + + +/** + * Inclusion d'une règle externe. + */ + + external : "include" PLAIN_TEXT + { + bool __status; + __status = g_content_scanner_include_resource(scanner, $2.data); + if (!__status) + YYERROR; + } + | "include" ESCAPED_TEXT + { + bool __status; + __status = g_content_scanner_include_resource(scanner, $2->data); + if (!__status) + YYERROR; + } + ; + + +/** + * Définition de règle. + */ + + rule : rule_flags "rule" RULE_IDENTIFIER + { + *built_rule = g_scan_rule_new($1, $3.data); + } + tags "{" meta bytes condition "}" + ; + + + rule_flags : /* empty */ + { + $$ = SRF_NONE; + } + | rule_flags rule_flag + { + $$ = $1 | $2; + } + ; + + rule_flag : "private" + { + $$ = SRF_PRIVATE; + } + | "global" + { + $$ = SRF_GLOBAL; + } + ; + + + tags : /* empty */ + | ":" tag_list + ; + + tag_list : RULE_IDENTIFIER + { + g_scan_rule_add_tag(*built_rule, $1.data); + } + | tag_list RULE_IDENTIFIER + { + g_scan_rule_add_tag(*built_rule, $2.data); + } + ; + + +/** + * Section "meta:" d'une définition de règle. + */ + + meta : /* empty */ + | "meta" ":" + | "meta" ":" meta_list + ; + + meta_list : meta_info + | meta_list meta_info + ; + + meta_info : INFO_KEY "=" "true" + | INFO_KEY "=" "false" + | INFO_KEY "=" SIGNED_INTEGER + | INFO_KEY "=" UNSIGNED_INTEGER + | INFO_KEY "=" PLAIN_TEXT + | INFO_KEY "=" ESCAPED_TEXT + ; + + +/** + * Section "bytes:" d'une définition de règle. + */ + + bytes : /* empty */ + | "bytes" ":" + | "bytes" ":" bytes_decls + ; + + bytes_decls : str_pattern + { + if ($1 == NULL) YYERROR; + g_scan_rule_add_local_variable(*built_rule, $1); + g_object_unref(G_OBJECT($1)); + } + | hex_pattern + { + if ($1 == NULL) YYERROR; + g_scan_rule_add_local_variable(*built_rule, $1); + g_object_unref(G_OBJECT($1)); + } + | regex_pattern + { + // TODO + } + | bytes_decls str_pattern + { + if ($2 == NULL) YYERROR; + g_scan_rule_add_local_variable(*built_rule, $2); + g_object_unref(G_OBJECT($2)); + } + | bytes_decls hex_pattern + { + if ($2 == NULL) YYERROR; + g_scan_rule_add_local_variable(*built_rule, $2); + g_object_unref(G_OBJECT($2)); + } + | bytes_decls regex_pattern + { + // TODO + } + ; + + +/** + * Définition de motif en texte brut. + */ + + str_pattern : BYTES_ID "=" PLAIN_TEXT modifiers str_flags + { + GScanTokenNode *node; + + node = g_scan_token_node_plain_new(&$3, $4, $5); + + $$ = g_scan_plain_bytes_new(node); + g_search_pattern_set_name($$, $1.data, $1.len); + + g_object_unref(G_OBJECT(node)); + + } + | BYTES_ID "=" ESCAPED_TEXT modifiers str_flags + { + GScanTokenNode *node; + + node = g_scan_token_node_plain_new($3, $4, $5); + + $$ = g_scan_plain_bytes_new(node); + g_search_pattern_set_name($$, $1.data, $1.len); + + g_object_unref(G_OBJECT(node)); + + } + ; + + +/** + * Prise en charge des modificateurs. + */ + + modifiers : /* empty */ + { + $$ = NULL; + } + | _modifiers + { + $$ = $1; + + + // if (...) useless + // ex : xxx | { yyy zzz } + + } + ; + + _modifiers : mod_stage + { + $$ = $1; + } + | _modifiers "|" mod_stage + { + bool status; + + if (G_IS_SCAN_MODIFIER_PIPE($1)) + $$ = $1; + else + { + $$ = g_scan_modifier_pipe_new(); + g_scan_modifier_pipe_add(G_SCAN_MODIFIER_PIPE($$), $1); + g_object_unref(G_OBJECT($1)); + } + + g_scan_modifier_pipe_add(G_SCAN_MODIFIER_PIPE($$), $3); + g_object_unref(G_OBJECT($3)); + + } + ; + +/* + chained_modifiers : modifiers "|" modifiers + { + printf("need chains....\n"); + + $$ = NULL; + + } + ; +*/ + + mod_stage : modifier + { + $$ = $1; + } + | "((" _modifiers "))" + { + $$ = NULL; + YYERROR; /* TODO */ + } + | mod_stage modifier + { + bool status; + + if (G_IS_SCAN_MODIFIER_LIST($1)) + $$ = $1; + else + { + $$ = g_scan_modifier_list_new(); + g_scan_modifier_list_add(G_SCAN_MODIFIER_LIST($$), $1); + g_object_unref(G_OBJECT($1)); + } + + status = g_scan_modifier_list_add(G_SCAN_MODIFIER_LIST($$), $2); + if (!status) + { + if (1) + log_simple_message(LMT_WARNING, "modifier already taken into account!"); + } + + g_object_unref(G_OBJECT($2)); + + } + ; + + modifier : NAME + { + $$ = find_scan_token_modifiers_for_name(&$1); + if ($$ == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Unknown modifier: \"%.*s\""), (int)$1.len, $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + } + | NAME "(" modifier_args ")" + { + GScanTokenModifier *_mod; + bool _status; + + $$ = $3; + + _mod = find_scan_token_modifiers_for_name(&$1); + if (_mod == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Unknown modifier: \"%.*s\""), (int)$1.len, $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + g_object_unref(G_OBJECT($$)); + + YYERROR; + } + + _status = g_scan_token_customizer_attach_modifier(G_SCAN_TOKEN_CUSTOMIZER($$), _mod); + + g_object_unref(G_OBJECT(_mod)); + + if (!_status) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, + _("Unsupported argument for modifier: \"%.*s\""), + (int)$1.len, $1.data); + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + g_object_unref(G_OBJECT($$)); + + YYERROR; + } + + } + ; + + + modifier_args : modifier_arg + { + $$ = g_scan_token_customizer_new(&$1); + } + | modifier_args "," modifier_arg + { + $$ = $1; + g_scan_token_customizer_add_extra_arg(G_SCAN_TOKEN_CUSTOMIZER($$), &$3); + } + ; + + modifier_arg : PLAIN_TEXT + { + $$.type = MAT_STRING; + $$.value.string = $1; + } + ; + + +/** + * Prise en charge des fanions pour texte. + */ + + str_flags : /* empty */ + { + $$ = SPNF_NONE; + } + | str_flags "nocase" + { + $$ = $1 | SPNF_CASE_INSENSITIVE; + } + | str_flags "fullword" + { + $$ = $1 | SPNF_FULLWORD; + } + | str_flags "private" + { + $$ = $1 | SPNF_PRIVATE; + } + ; + + +/** + * Définition de motif en hexadécimal. + */ + + hex_pattern : BYTES_ID "=" hex_tokens + { + $$ = g_scan_hex_bytes_new($3, false); + g_search_pattern_set_name($$, $1.data, $1.len); + } + | BYTES_ID "=" hex_tokens "private" + { + $$ = g_scan_hex_bytes_new($3, true); + g_search_pattern_set_name($$, $1.data, $1.len); + } + ; + + hex_tokens : _hex_tokens + { + $$ = $1; + + if (G_IS_SCAN_TOKEN_NODE_SEQUENCE($$)) + { + if (g_scan_token_node_sequence_count(G_SCAN_TOKEN_NODE_SEQUENCE($$)) == 1) + { + GScanTokenNode *node; + + node = g_scan_token_node_sequence_get(G_SCAN_TOKEN_NODE_SEQUENCE($$), 0); + + g_object_unref(G_OBJECT($$)); + + $$ = node; + + } + + } + + } + ; + + _hex_tokens : hex_token + { + if ($1 == NULL) YYERROR; + + $$ = $1; + + } + | _hex_tokens hex_token + { + if ($2 == NULL) YYERROR; + + if (!G_IS_SCAN_TOKEN_NODE_SEQUENCE($1)) + { + $$ = g_scan_token_node_sequence_new($1); + g_object_unref(G_OBJECT($1)); + g_scan_token_node_sequence_add(G_SCAN_TOKEN_NODE_SEQUENCE($$), $2); + g_object_unref(G_OBJECT($2)); + } + else + { + $$ = $1; + g_scan_token_node_sequence_add(G_SCAN_TOKEN_NODE_SEQUENCE($$), $2); + g_object_unref(G_OBJECT($2)); + } + + } + ; + + hex_token : HEX_BYTES + { + $$ = g_scan_token_node_plain_new($1, NULL, SPNF_NONE); + } + | FULL_MASK + { + phys_t min; + phys_t max; + + min = $1; + max = $1; + + $$ = g_scan_token_node_any_new(&min, &max); + + } + | SEMI_MASK + { + size_t i; + masked_byte_t byte; + + assert($1.tmp_values->len == $1.tmp_masks->len); + + byte.value = $1.tmp_values->data[0]; + byte.mask = $1.tmp_masks->data[0]; + + $$ = g_scan_token_node_masked_new(&byte); + + for (i = 1; i < $1.tmp_values->len; i++) + { + byte.value = $1.tmp_values->data[i]; + byte.mask = $1.tmp_masks->data[i]; + + g_scan_token_node_masked_add(G_SCAN_TOKEN_NODE_MASKED($$), &byte); + + } + + } + | hex_range + { + if ($1 == NULL) + { + raise_error(_("Unable to build hexadecimal range")); + YYERROR; + } + + $$ = $1; + + } + | "~" hex_token + { + if ($2 == NULL) YYERROR; + $$ = g_scan_token_node_not_new($2); + + } + | "(" hex_choices ")" + { + $$ = $2; + } + ; + + hex_range : "[" "-" "]" + { + $$ = g_scan_token_node_any_new(NULL, NULL); + } + | "[" UNSIGNED_INTEGER "]" + { + phys_t min; + phys_t max; + + min = $2; + max = $2; + + $$ = g_scan_token_node_any_new(&min, &max); + + } + | "[" UNSIGNED_INTEGER "-" "]" + { + phys_t min; + + min = $2; + + $$ = g_scan_token_node_any_new(&min, NULL); + + } + | "[" "-" UNSIGNED_INTEGER "]" + { + phys_t max; + + max = $3; + + $$ = g_scan_token_node_any_new(NULL, &max); + + } + | "[" UNSIGNED_INTEGER "-" UNSIGNED_INTEGER "]" + { + phys_t min; + phys_t max; + + min = $2; + max = $4; + + $$ = g_scan_token_node_any_new(&min, &max); + + } + ; + + hex_choices : hex_token "|" hex_token + { + if ($1 == NULL) YYERROR; + if ($3 == NULL) YYERROR; + + $$ = g_scan_token_node_choice_new(); + g_scan_token_node_choice_add(G_SCAN_TOKEN_NODE_CHOICE($$), $1); + g_object_unref(G_OBJECT($1)); + g_scan_token_node_choice_add(G_SCAN_TOKEN_NODE_CHOICE($$), $3); + g_object_unref(G_OBJECT($3)); + } + | hex_choices "|" hex_token + { + if ($3 == NULL) YYERROR; + + $$ = $1; + g_scan_token_node_choice_add(G_SCAN_TOKEN_NODE_CHOICE($$), $3); + g_object_unref(G_OBJECT($3)); + } + ; + + +/** + * Définition de motif sous forme d'expression régulière + */ + + regex_pattern : BYTES_ID "=" regex_tokens + { + + } + ; + + regex_tokens : regex_token + { + + } + | regex_tokens regex_token + { + + } + | "(" regex_tokens_list ")" + { + + printf("regex -- OR --\n"); + + } + | regex_tokens "(" regex_tokens_list ")" + { + + printf("regex -- OR --\n"); + + } + ; + + + regex_tokens_list : regex_tokens + | regex_tokens_list "|" regex_tokens + ; + + + regex_token : _regex_token + { + + } + | _regex_token regex_repeat + { + + } + ; + + _regex_token : "." + { + printf("reg dot!\n"); + } + | REGEX_BYTES + { + printf("reg bytes: '%s' (l=%zu)\n", $1->data, $1->len); + } + | REGEX_CLASSES + { + printf("reg class!\n"); + } + | "[" REGEX_RANGE "]" + { + printf("reg range!\n"); + } + ; + + regex_repeat : "*" + { + printf(" .. repeat: *\n"); + } + | "+" + { + printf(" .. repeat: +\n"); + } + | "?" + { + printf(" .. repeat: ?\n"); + } + | "{" UNSIGNED_INTEGER "}" + { + + printf(" .. repeat {%llu}\n", $2); + + } + | "{" UNSIGNED_INTEGER "," "}" + { + + printf(" .. repeat {%llu,}\n", $2); + + } + | "{" "," UNSIGNED_INTEGER "}" + { + + printf(" .. repeat {,%llu}\n", $3); + + } + | "{" UNSIGNED_INTEGER "," UNSIGNED_INTEGER "}" + { + + printf(" .. repeat {%llu,%llu}\n", $2, $4); + + } + ; + + + +/** + * Définition des conditions. + */ + + condition : "condition" ":" cexpression + { + g_scan_rule_set_match_condition(*built_rule, $3); + g_object_unref(G_OBJECT($3)); + } + ; + + cexpression : _cexpression { $$ = $1; if ($$ == NULL) { printf("ERROR !!!\n"); YYERROR; } } + ; + + _cexpression : literal { $$ = $1; } + | chain_items { $$ = $1; } + | logical_expr { $$ = $1; } + | relational_expr { $$ = $1; } + | string_op { $$ = $1; } + | arithm_expr { $$ = $1; } + | set_match_counter { $$ = $1; } + | set { $$ = $1; } + | intersection { $$ = $1; } + | pattern_handler { $$ = $1; } + | "(" cexpression ")" { $$ = $2; } + ; + + literal : "true" + { + $$ = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ true }); + } + | "false" + { + $$ = g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ false }); + } + | SIGNED_INTEGER + { + $$ = g_scan_literal_expression_new(LVT_SIGNED_INTEGER, &$1); + } + | UNSIGNED_INTEGER + { + $$ = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, &$1); + } + | UNSIGNED_INTEGER KB + { + unsigned long long __converted; + __converted = $1 * 1024; + $$ = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, &__converted); + } + | UNSIGNED_INTEGER MB + { + unsigned long long __converted; + __converted = $1 * 1048576; + $$ = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, &__converted); + } + | UNSIGNED_INTEGER GB + { + unsigned long long __converted; + __converted = $1 * 1073741824; + $$ = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, &__converted); + } + | PLAIN_TEXT + { + $$ = g_scan_literal_expression_new(LVT_STRING, &$1); + } + | PLAIN_TEXT "[" cexpression "]" + { + GScanExpression *__src; + __src = g_scan_literal_expression_new(LVT_STRING, &$1); + $$ = g_scan_set_item_new(__src, $3); + g_object_unref(G_OBJECT(__src)); + g_object_unref(G_OBJECT($3)); + } + | ESCAPED_TEXT + { + $$ = g_scan_literal_expression_new(LVT_STRING, $1); + } + | ESCAPED_TEXT "[" cexpression "]" + { + GScanExpression *__src; + __src = g_scan_literal_expression_new(LVT_STRING, $1); + $$ = g_scan_set_item_new(__src, $3); + g_object_unref(G_OBJECT(__src)); + g_object_unref(G_OBJECT($3)); + } + ; + + + chain_items : chain_item + { + $$ = $1; + } + | chain_items "." chain_item + { + g_scan_named_access_attach_next(G_SCAN_NAMED_ACCESS($1), G_SCAN_NAMED_ACCESS($3)); + g_object_unref(G_OBJECT($3)); + $$ = $1; + } + ; + + chain_item : NAME + { + $$ = g_scan_named_access_new(&$1); + } + | NAME "(" ")" + { + $$ = g_scan_pending_call_new(&$1, NULL, 0); + } + | NAME "(" call_args ")" + { + size_t __i; + $$ = g_scan_pending_call_new(&$1, $3.args, $3.count); + for (__i = 0; __i < $3.count; __i++) + g_object_unref(G_OBJECT($3.args[__i])); + free($3.args); + } + | NAME "[" cexpression "]" + { + $$ = g_scan_pending_extraction_new(&$1, $3); + g_object_unref(G_OBJECT($3)); + } + ; + + call_args : cexpression + { + $$.count = 1; + $$.args = malloc(sizeof(GScanExpression *)); + $$.args[0] = $1; + } + | call_args "," cexpression + { + $1.count++; + $1.args = realloc($1.args, $1.count * sizeof(GScanExpression *)); + $1.args[$1.count - 1] = $3; + $$ = $1; + } + ; + + logical_expr : cexpression "and" cexpression + { + $$ = g_scan_logical_operation_new(BOT_AND, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "or" cexpression + { + $$ = g_scan_logical_operation_new(BOT_OR, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | "not" "(" cexpression ")" + { + $$ = g_scan_logical_operation_new(BOT_NOT, $3, NULL); + g_object_unref(G_OBJECT($3)); + } + ; + +relational_expr : cexpression "<" cexpression + { + $$ = g_scan_relational_operation_new(RCO_LT, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "<=" cexpression + { + $$ = g_scan_relational_operation_new(RCO_LE, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "==" cexpression + { + $$ = g_scan_relational_operation_new(RCO_EQ, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "!=" cexpression + { + $$ = g_scan_relational_operation_new(RCO_NE, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression ">" cexpression + { + $$ = g_scan_relational_operation_new(RCO_GT, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression ">=" cexpression + { + $$ = g_scan_relational_operation_new(RCO_GE, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + ; + + string_op : cexpression "contains" cexpression + { + $$ = g_scan_string_operation_new(SOT_CONTAINS, $1, $3, true); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "startswith" cexpression + { + $$ = g_scan_string_operation_new(SOT_STARTSWITH, $1, $3, true); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "endswith" cexpression + { + $$ = g_scan_string_operation_new(SOT_ENDSWITH, $1, $3, true); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "matches" cexpression + { + $$ = g_scan_string_operation_new(SOT_MATCHES, $1, $3, true); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "icontains" cexpression + { + $$ = g_scan_string_operation_new(SOT_CONTAINS, $1, $3, false); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "istartswith" cexpression + { + $$ = g_scan_string_operation_new(SOT_STARTSWITH, $1, $3, false); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "iendswith" cexpression + { + $$ = g_scan_string_operation_new(SOT_ENDSWITH, $1, $3, false); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "iequals" cexpression + { + $$ = g_scan_string_operation_new(SOT_IEQUALS, $1, $3, false); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + ; + + arithm_expr : cexpression "+" cexpression + { + $$ = g_scan_arithmetic_operation_new(AEO_PLUS, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "-" cexpression + { + $$ = g_scan_arithmetic_operation_new(AEO_MINUS, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "*" cexpression + { + $$ = g_scan_arithmetic_operation_new(AEO_MUL, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "/" cexpression + { + $$ = g_scan_arithmetic_operation_new(AEO_DIV, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + | cexpression "%" cexpression + { + $$ = g_scan_arithmetic_operation_new(AEO_MOD, $1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + ; + + + set_match_counter : "none" "of" pattern_set + { + GScanSetMatchCounter *__counter; + __counter = G_SCAN_SET_MATCH_COUNTER($3); + g_scan_set_match_counter_define_expected_matches(__counter, SSCT_NONE, NULL); + $$ = $3; + } + | "any" "of" pattern_set + { + GScanSetMatchCounter *__counter; + __counter = G_SCAN_SET_MATCH_COUNTER($3); + g_scan_set_match_counter_define_expected_matches(__counter, SSCT_ANY, NULL); + $$ = $3; + } + | "all" "of" pattern_set + { + GScanSetMatchCounter *__counter; + __counter = G_SCAN_SET_MATCH_COUNTER($3); + g_scan_set_match_counter_define_expected_matches(__counter, SSCT_ALL, NULL); + $$ = $3; + } + | UNSIGNED_INTEGER "of" pattern_set + { + GScanSetMatchCounter *__counter; + size_t __number; + bool __status; + + __counter = G_SCAN_SET_MATCH_COUNTER($3); + __number = $1; + + __status = g_scan_set_match_counter_define_expected_matches(__counter, + SSCT_NUMBER, &__number); + + if (!__status) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Expected matches counter too high: %zu"), __number); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = $3; + + } + ; + + pattern_set : "them" + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, NULL, &__count); + + if (__patterns == NULL) + { + raise_error(_("No pattern found for \"them\"")); + YYERROR; + } + + $$ = g_scan_set_match_counter_new_shared(__patterns, __count); + + free(__patterns); + + } + | "(" pattern_set_items ")" + { + $$ = $2; + } + ; + + pattern_set_items : BYTES_ID + { + const GSearchPattern *__pat; + + __pat = g_scan_rule_get_local_variable(*built_rule, $1.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_set_match_counter_new_shared((const GSearchPattern *[]) { __pat }, 1); + + } + | BYTES_FUZZY_ID + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $1.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_set_match_counter_new_shared(__patterns, __count); + + free(__patterns); + + } + | pattern_set_items "," BYTES_ID + { + const GSearchPattern *__pat; + GScanSetMatchCounter *__counter; + + __pat = g_scan_rule_get_local_variable(*built_rule, $3.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $3.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + __counter = G_SCAN_SET_MATCH_COUNTER($1); + g_scan_set_match_counter_add_extra_shared_patterns(__counter, + (const GSearchPattern *[]) { __pat }, 1); + + $$ = $1; + + } + | pattern_set_items "," BYTES_FUZZY_ID + { + size_t __count; + const GSearchPattern **__patterns; + GScanSetMatchCounter *__counter; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $3.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $3.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + __counter = G_SCAN_SET_MATCH_COUNTER($1); + g_scan_set_match_counter_add_extra_shared_patterns(__counter, __patterns, __count); + + free(__patterns); + + $$ = $1; + + } + ; + + + set : "(" ")" + { + $$ = g_scan_generic_set_new(); + } + | "(" cexpression "," ")" + { + $$ = g_scan_generic_set_new(); + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET($$), $2); + g_object_unref(G_OBJECT($2)); + } + | "(" set_items ")" + { + $$ = $2; + } + ; + + set_items : cexpression "," cexpression + { + $$ = g_scan_generic_set_new(); + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET($$), $1); + g_object_unref(G_OBJECT($1)); + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET($$), $3); + g_object_unref(G_OBJECT($3)); + } + | set_items "," cexpression + { + $$ = $1; + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET($$), $3); + g_object_unref(G_OBJECT($3)); + } + ; + + + intersection : cexpression "in" cexpression + { + $$ = g_scan_sets_intersection_new($1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + } + ; + + + pattern_handler : _pattern_handler + { + $$ = $1; + } + | _pattern_handler "[" cexpression "]" + { + if (g_scan_pattern_handler_get_handler_type(G_SCAN_PATTERN_HANDLER($1)) == SHT_COUNTER) + { + raise_error("Match counts can not get indexed"); + YYERROR; + } + + $$ = g_scan_set_item_new($1, $3); + g_object_unref(G_OBJECT($1)); + g_object_unref(G_OBJECT($3)); + + } + ; + + _pattern_handler : BYTES_ID + { + const GSearchPattern *__pat; + + __pat = g_scan_rule_get_local_variable(*built_rule, $1.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared((const GSearchPattern *[]) { __pat }, 1, SHT_RAW); + + } + | BYTES_FUZZY_ID + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $1.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared(__patterns, __count, SHT_RAW); + + free(__patterns); + + } + | BYTES_ID_COUNTER + { + const GSearchPattern *__pat; + + __pat = g_scan_rule_get_local_variable(*built_rule, $1.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared((const GSearchPattern *[]) { __pat }, 1, SHT_COUNTER); + + } + | BYTES_FUZZY_ID_COUNTER + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $1.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared(__patterns, __count, SHT_COUNTER); + + free(__patterns); + + } + | BYTES_ID_START + { + const GSearchPattern *__pat; + + __pat = g_scan_rule_get_local_variable(*built_rule, $1.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared((const GSearchPattern *[]) { __pat }, 1, SHT_START); + + } + | BYTES_FUZZY_ID_START + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $1.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared(__patterns, __count, SHT_START); + + free(__patterns); + + } + | BYTES_ID_LENGTH + { + const GSearchPattern *__pat; + + __pat = g_scan_rule_get_local_variable(*built_rule, $1.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared((const GSearchPattern *[]) { __pat }, 1, SHT_LENGTH); + + } + | BYTES_FUZZY_ID_LENGTH + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $1.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared(__patterns, __count, SHT_LENGTH); + + free(__patterns); + + } + | BYTES_ID_END + { + const GSearchPattern *__pat; + + __pat = g_scan_rule_get_local_variable(*built_rule, $1.data); + + if (__pat == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Pattern not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared((const GSearchPattern *[]) { __pat }, 1, SHT_END); + + } + | BYTES_FUZZY_ID_END + { + size_t __count; + const GSearchPattern **__patterns; + + __patterns = g_scan_rule_get_local_variables(*built_rule, $1.data, &__count); + + if (__patterns == NULL) + { + char *_msg; + int _ret; + + _ret = asprintf(&_msg, _("Patterns not found: \"%s\""), $1.data); + + if (_ret != -1) + { + raise_error(_msg); + free(_msg); + } + + YYERROR; + } + + $$ = g_scan_pattern_handler_new_shared(__patterns, __count, SHT_END); + + free(__patterns); + + } + ; + +%% + + +/****************************************************************************** +* * +* Paramètres : scanner = décodeur impliqué dans le processus. * +* temp = zone de travail à destination des lectures. * +* msg = message d'erreur. * +* * +* Description : Affiche un message d'erreur suite à l'analyse en échec. * +* * +* Retour : 0 * +* * +* Remarques : - * +* * +******************************************************************************/ + +static int yyerror(GContentScanner *scanner, yyscan_t yyscanner, GScanRule **built_rule, sized_string_t *tmp_0, sized_string_t *tmp_1, char *msg) +{ + //printf("YYERROR line %d: %s\n", yyget_lineno(yyscanner), msg); + + return 0; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = chercheur de motifs à préparer. * +* text = définitions des règles à charger. * +* length = longueur de ces définitions. * +* * +* Description : Complète une recherche de motifs avec des règles. * +* * +* Retour : Bilan à retourner. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool process_rules_definitions(GContentScanner *scanner, const char *text, size_t length) +{ + bool result; /* Bilan à renvoyer */ + GScanRule *built_rule; /* Règle en construction */ + sized_string_t tmp_0; /* Zone tampon #1 */ + sized_string_t tmp_1; /* Zone tampon #2 */ + yyscan_t lexstate; /* Gestion d'analyse lexicale */ + YY_BUFFER_STATE state; /* Contexte d'analyse */ + int status; /* Bilan d'une analyse */ + + result = false; + + built_rule = NULL; + + tmp_0.data = malloc((length + 1) * sizeof(bin_t)); + tmp_0.len = 0; + + tmp_1.data = malloc((length + 1) * sizeof(bin_t)); + tmp_1.len = 0; + + rost_lex_init(&lexstate); + + state = rost__scan_bytes(text, length, lexstate); + + status = yyparse(scanner, lexstate, &built_rule, &tmp_0, &tmp_1); + + result = (status == EXIT_SUCCESS); + + yy_delete_buffer(state, lexstate); + + rost_lex_destroy(lexstate); + + exit_szstr(&tmp_0); + exit_szstr(&tmp_1); + + g_clear_object(&built_rule); + + return result; + +} diff --git a/src/analysis/scan/item-int.h b/src/analysis/scan/item-int.h new file mode 100644 index 0000000..a04b861 --- /dev/null +++ b/src/analysis/scan/item-int.h @@ -0,0 +1,74 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * item-int.h - prototypes internes pour la définition d'un élément appelable lors de l'exécution d'une règle + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEM_INT_H +#define _ANALYSIS_SCAN_ITEM_INT_H + + +#include "item.h" + + +#include <stdbool.h> + + + +/* Indique le nom associé à une expression d'évaluation. */ +typedef char * (* get_registered_item_name_fc) (const GScanRegisteredItem *); + +/* Lance une résolution d'élément à solliciter. */ +typedef bool (* resolve_registered_item_fc) (GScanRegisteredItem *, const char *, GScanContext *, GScanScope *, GScanRegisteredItem **); + +/* Réduit une expression à une forme plus simple. */ +typedef bool (* reduce_registered_item_fc) (GScanRegisteredItem *, GScanContext *, GScanScope *, GScanExpression **); + +/* Effectue un appel à une fonction enregistrée. */ +typedef bool (* run_registered_item_call_fc) (GScanRegisteredItem *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + +/* Effectue une extraction d'élément à partir d'une série. */ +typedef GObject * (* extract_registered_item_at) (GScanRegisteredItem *, GScanExpression *, GScanContext *, GScanScope *); + + +/* Expression d'évaluation généraliste (instance) */ +struct _GScanRegisteredItem +{ + GObject parent; /* A laisser en premier */ + +}; + +/* Expression d'évaluation généraliste (classe) */ +struct _GScanRegisteredItemClass +{ + GObjectClass parent; /* A laisser en premier */ + + get_registered_item_name_fc get_name; /* Obtention du nom associé */ + + resolve_registered_item_fc resolve; /* Opération de résolution */ + reduce_registered_item_fc reduce; /* Opération de réduction */ + run_registered_item_call_fc run_call; /* Appel à une fonction connue */ + extract_registered_item_at extract; /* Extraction d'un élément */ + +}; + + + +#endif /* _ANALYSIS_SCAN_ITEM_INT_H */ diff --git a/src/analysis/scan/item.c b/src/analysis/scan/item.c new file mode 100644 index 0000000..509ad28 --- /dev/null +++ b/src/analysis/scan/item.c @@ -0,0 +1,325 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * item.c - définition d'un élément appelable lors de l'exécution d'une règle + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "item.h" + + +#include <assert.h> + + +#include "item-int.h" + + + +/* ----------------------- BASES D'OBJET POUR LE SYSTEME GLIB ----------------------- */ + + +/* Initialise la classe des éléments appelables enregistrés. */ +static void g_scan_registered_item_class_init(GScanRegisteredItemClass *); + +/* Initialise une instance d'élément appelable enregistré. */ +static void g_scan_registered_item_init(GScanRegisteredItem *); + +/* Supprime toutes les références externes. */ +static void g_scan_registered_item_dispose(GScanRegisteredItem *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_registered_item_finalize(GScanRegisteredItem *); + + + +/* ---------------------------------------------------------------------------------- */ +/* BASES D'OBJET POUR LE SYSTEME GLIB */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un élément appelable et enregistré. */ +G_DEFINE_TYPE(GScanRegisteredItem, g_scan_registered_item, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des éléments appelables enregistrés. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_registered_item_class_init(GScanRegisteredItemClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_registered_item_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_registered_item_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance à initialiser. * +* * +* Description : Initialise une instance d'élément appelable enregistré. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_registered_item_init(GScanRegisteredItem *item) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_registered_item_dispose(GScanRegisteredItem *item) +{ + G_OBJECT_CLASS(g_scan_registered_item_parent_class)->dispose(G_OBJECT(item)); + +} + + +/****************************************************************************** +* * +* Paramètres : item = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_registered_item_finalize(GScanRegisteredItem *item) +{ + G_OBJECT_CLASS(g_scan_registered_item_parent_class)->finalize(G_OBJECT(item)); + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_registered_item_get_name(const GScanRegisteredItem *item) +{ + char *result; /* Désignation à retourner */ + GScanRegisteredItemClass *class; /* Classe à activer */ + + class = G_SCAN_REGISTERED_ITEM_GET_CLASS(item); + + result = class->get_name(item); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* target = désignation de l'objet d'appel à identifier. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT]* +* * +* Description : Lance une résolution d'élément à solliciter. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_registered_item_resolve(GScanRegisteredItem *item, const char *target, GScanContext *ctx, GScanScope *scope, GScanRegisteredItem **out) +{ + bool result; /* Bilan à retourner */ + GScanRegisteredItemClass *class; /* Classe à activer */ + + *out = NULL; + + class = G_SCAN_REGISTERED_ITEM_GET_CLASS(item); + + if (class->resolve == NULL) + result = false; + else + { + result = class->resolve(item, target, ctx, scope, out); + +#ifndef NDEBUG + if (*out != NULL) + assert(result); +#endif + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_registered_item_reduce(GScanRegisteredItem *item, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + GScanRegisteredItemClass *class; /* Classe à activer */ + + *out = NULL; + + class = G_SCAN_REGISTERED_ITEM_GET_CLASS(item); + + if (class->reduce == NULL) + result = false; + else + { + result = class->reduce(item, ctx, scope, out); + +#ifndef NDEBUG + if (*out != NULL) + assert(result); +#endif + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Effectue un appel à une fonction enregistrée. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_registered_item_run_call(GScanRegisteredItem *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + GScanRegisteredItemClass *class; /* Classe à activer */ + + *out = NULL; + + class = G_SCAN_REGISTERED_ITEM_GET_CLASS(item); + + if (class->run_call == NULL) + result = false; + else + { + result = class->run_call(item, args, count, ctx, scope, out); + +#ifndef NDEBUG + if (*out != NULL) + assert(result); +#endif + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* index = indice de l'élément à cibler. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* * +* Description : Effectue une extraction d'élément à partir d'une série. * +* * +* Retour : Elément de série obtenu ou NULL si erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GObject *g_scan_registered_item_extract_at(GScanRegisteredItem *item, GScanExpression *index, GScanContext *ctx, GScanScope *scope) +{ + GObject *result; /* Elément récupéré à renvoyer */ + GScanRegisteredItemClass *class; /* Classe à activer */ + + class = G_SCAN_REGISTERED_ITEM_GET_CLASS(item); + + if (class->extract == NULL) + result = NULL; + + else + result = class->extract(item, index, ctx, scope); + + return result; + +} diff --git a/src/analysis/scan/item.h b/src/analysis/scan/item.h new file mode 100644 index 0000000..a6c56c3 --- /dev/null +++ b/src/analysis/scan/item.h @@ -0,0 +1,72 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * item.h - prototypes pour la définition d'un élément appelable lors de l'exécution d'une règle + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEM_H +#define _ANALYSIS_SCAN_ITEM_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "context.h" +#include "expr.h" + + + +#define G_TYPE_SCAN_REGISTERED_ITEM g_scan_registered_item_get_type() +#define G_SCAN_REGISTERED_ITEM(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_REGISTERED_ITEM, GScanRegisteredItem)) +#define G_IS_SCAN_REGISTERED_ITEM(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_REGISTERED_ITEM)) +#define G_SCAN_REGISTERED_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_REGISTERED_ITEM, GScanRegisteredItemClass)) +#define G_IS_SCAN_REGISTERED_ITEM_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_REGISTERED_ITEM)) +#define G_SCAN_REGISTERED_ITEM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_REGISTERED_ITEM, GScanRegisteredItemClass)) + + +/* Expression d'évaluation généraliste (instance) */ +typedef struct _GScanRegisteredItem GScanRegisteredItem; + +/* Expression d'évaluation généraliste (classe) */ +typedef struct _GScanRegisteredItemClass GScanRegisteredItemClass; + + +/* Indique le type défini pour un élément appelable et enregistré. */ +GType g_scan_registered_item_get_type(void); + +/* Indique le nom associé à une expression d'évaluation. */ +char *g_scan_registered_item_get_name(const GScanRegisteredItem *); + +/* Lance une résolution d'élément à solliciter. */ +bool g_scan_registered_item_resolve(GScanRegisteredItem *, const char *, GScanContext *, GScanScope *, GScanRegisteredItem **); + +/* Réduit une expression à une forme plus simple. */ +bool g_scan_registered_item_reduce(GScanRegisteredItem *, GScanContext *, GScanScope *, GScanExpression **); + +/* Effectue un appel à une fonction enregistrée. */ +bool g_scan_registered_item_run_call(GScanRegisteredItem *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + +/* Effectue une extraction d'élément à partir d'une série. */ +GObject *g_scan_registered_item_extract_at(GScanRegisteredItem *, GScanExpression *, GScanContext *, GScanScope *); + + + +#endif /* _ANALYSIS_SCAN_ITEM_H */ diff --git a/src/analysis/scan/items/Makefile.am b/src/analysis/scan/items/Makefile.am new file mode 100644 index 0000000..9263c7b --- /dev/null +++ b/src/analysis/scan/items/Makefile.am @@ -0,0 +1,37 @@ + +noinst_LTLIBRARIES = libanalysisscanitems.la + + +if BUILD_MAGIC_SUPPORT + +MAGIC_LIBADD = magic/libanalysisscanitemsmagic.la + +MAGIC_SUBDIRS = magic + +endif + + +libanalysisscanitems_la_SOURCES = \ + count.h count.c \ + datasize.h datasize.c \ + maxcommon.h maxcommon.c \ + modpath.h modpath.c \ + uint-int.h \ + uint.h uint.c + +libanalysisscanitems_la_LIBADD = \ + console/libanalysisscanitemsconsole.la \ + $(MAGIC_LIBADD) \ + math/libanalysisscanitemsmath.la \ + string/libanalysisscanitemsstring.la \ + time/libanalysisscanitemstime.la + +libanalysisscanitems_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanitems_la_SOURCES:%c=) + + +SUBDIRS = console $(MAGIC_SUBDIRS) math string time diff --git a/src/analysis/scan/items/console/Makefile.am b/src/analysis/scan/items/console/Makefile.am new file mode 100644 index 0000000..4433789 --- /dev/null +++ b/src/analysis/scan/items/console/Makefile.am @@ -0,0 +1,13 @@ + +noinst_LTLIBRARIES = libanalysisscanitemsconsole.la + + +libanalysisscanitemsconsole_la_SOURCES = \ + log.h log.c + +libanalysisscanitemsconsole_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanitemsconsole_la_SOURCES:%c=) diff --git a/src/analysis/scan/items/console/log.c b/src/analysis/scan/items/console/log.c new file mode 100644 index 0000000..90e8f03 --- /dev/null +++ b/src/analysis/scan/items/console/log.c @@ -0,0 +1,304 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * log.c - affichage de message à partir des conditions d'une règle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "log.h" + + +#include <ctype.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des affichages de messages. */ +static void g_scan_console_log_function_class_init(GScanConsoleLogFunctionClass *); + +/* Initialise une instance d'affichage de message. */ +static void g_scan_console_log_function_init(GScanConsoleLogFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_console_log_function_dispose(GScanConsoleLogFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_console_log_function_finalize(GScanConsoleLogFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_console_log_function_get_name(const GScanConsoleLogFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_console_log_function_run_call(GScanConsoleLogFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un afficheur de messages arbitraires. */ +G_DEFINE_TYPE(GScanConsoleLogFunction, g_scan_console_log_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des affichages de messages. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_console_log_function_class_init(GScanConsoleLogFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_console_log_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_console_log_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_console_log_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_console_log_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance d'affichage de message. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_console_log_function_init(GScanConsoleLogFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_console_log_function_dispose(GScanConsoleLogFunction *func) +{ + G_OBJECT_CLASS(g_scan_console_log_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_console_log_function_finalize(GScanConsoleLogFunction *func) +{ + G_OBJECT_CLASS(g_scan_console_log_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction d'affichage de messages quelconques. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanConsoleLogFunction *g_scan_console_log_function_new(void) +{ + GScanConsoleLogFunction *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_CONSOLE_LOG_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_console_log_function_get_name(const GScanConsoleLogFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("log"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_console_log_function_run_call(GScanConsoleLogFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours #1 */ + GScanLiteralExpression *literal; /* Version plus accessible */ + LiteralValueType vtype; /* Type de valeur portée */ + bool boolean; /* Valeur booléenne */ + long long sinteger; /* Valeur entière signée */ + unsigned long long uinteger; /* Valeur entière non signée */ + const sized_string_t *string; /* Description du chaîne */ + size_t k; /* Boucle de parcours #2 */ + + result = true; + + if (count == 0) + goto done; + + for (i = 0; i < count && result; i++) + result = G_IS_SCAN_LITERAL_EXPRESSION(args[i]); + + if (!result) + goto done; + + for (i = 0; i < count; i++) + { + literal = G_SCAN_LITERAL_EXPRESSION(args[i]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + switch (vtype) + { + case LVT_BOOLEAN: + result = g_scan_literal_expression_get_boolean_value(literal, &boolean); + if (result) + fprintf(stderr, "%s", boolean ? "true" : "false"); + break; + + case LVT_SIGNED_INTEGER: + result = g_scan_literal_expression_get_signed_integer_value(literal, &sinteger); + if (result) + fprintf(stderr, "0x%llx", sinteger); + break; + + case LVT_UNSIGNED_INTEGER: + result = g_scan_literal_expression_get_unsigned_integer_value(literal, &uinteger); + if (result) + fprintf(stderr, "0x%llx", uinteger); + break; + + case LVT_STRING: + result = g_scan_literal_expression_get_string_value(literal, &string); + if (result) + for (k = 0; k < string->len; k++) + { + if (isprint(string->data[k])) + fprintf(stderr, "%c", string->data[k]); + else + fprintf(stderr, "\\x%02hhx", string->data[k]); + } + break; + + default: + break; + + } + + } + + fprintf(stderr, "\n"); + + done: + + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_BOOLEAN, (bool []){ result })); + + return result; + +} diff --git a/src/analysis/scan/items/console/log.h b/src/analysis/scan/items/console/log.h new file mode 100644 index 0000000..95fc55f --- /dev/null +++ b/src/analysis/scan/items/console/log.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * log.h - prototypes pour l'affichage de message à partir des conditions d'une règle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_CONSOLE_LOG_H +#define _ANALYSIS_SCAN_ITEMS_CONSOLE_LOG_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_CONSOLE_LOG_FUNCTION g_scan_console_log_function_get_type() +#define G_SCAN_CONSOLE_LOG_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_CONSOLE_LOG_FUNCTION, GScanConsoleLogFunction)) +#define G_IS_SCAN_CONSOLE_LOG_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_CONSOLE_LOG_FUNCTION)) +#define G_SCAN_CONSOLE_LOG_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_CONSOLE_LOG_FUNCTION, GScanConsoleLogFunctionClass)) +#define G_IS_SCAN_CONSOLE_LOG_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_CONSOLE_LOG_FUNCTION)) +#define G_SCAN_CONSOLE_LOG_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_CONSOLE_LOG_FUNCTION, GScanConsoleLogFunctionClass)) + + +/* Mesure de la quantité de données scannées (instance) */ +typedef GScanRegisteredItem GScanConsoleLogFunction; + +/* Mesure de la quantité de données scannées (classe) */ +typedef GScanRegisteredItemClass GScanConsoleLogFunctionClass; + + +/* Indique le type défini pour un afficheur de messages arbitraires. */ +GType g_scan_console_log_function_get_type(void); + +/* Constitue une fonction d'affichage de messages quelconques. */ +GScanConsoleLogFunction *g_scan_console_log_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_CONSOLE_LOG_H */ diff --git a/src/analysis/scan/items/count.c b/src/analysis/scan/items/count.c new file mode 100644 index 0000000..1d01867 --- /dev/null +++ b/src/analysis/scan/items/count.c @@ -0,0 +1,251 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * count.c - récupération de la taille du contenu scanné + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "count.h" + + +#include "../item-int.h" +#include "../exprs/arithmetic.h" +#include "../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des décomptes d'ensemble homogène. */ +static void g_scan_count_function_class_init(GScanCountFunctionClass *); + +/* Initialise une instance de décompte d'ensemble homogène. */ +static void g_scan_count_function_init(GScanCountFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_count_function_dispose(GScanCountFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_count_function_finalize(GScanCountFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_count_function_get_name(const GScanCountFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_count_function_run_call(GScanCountFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un décompte d'ensemble. */ +G_DEFINE_TYPE(GScanCountFunction, g_scan_count_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des décomptes d'ensemble homogène. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_count_function_class_init(GScanCountFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_count_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_count_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_count_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_count_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de décompte d'ensemble homogène. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_count_function_init(GScanCountFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_count_function_dispose(GScanCountFunction *func) +{ + G_OBJECT_CLASS(g_scan_count_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_count_function_finalize(GScanCountFunction *func) +{ + G_OBJECT_CLASS(g_scan_count_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de décompte d'éléments d'un ensemble. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_count_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_COUNT_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_count_function_get_name(const GScanCountFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("count"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_count_function_run_call(GScanCountFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + size_t sum; /* Somme des décomptes */ + size_t i; /* Boucle de parcours */ + size_t value; /* Nouveau décompte */ + + result = (count > 0); + + if (result) + { + sum = 0; + + for (i = 0; i < count && result; i++) + { + result = g_scan_expression_count_items(args[i], ctx, &value); + sum += value; + } + + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, (unsigned long long []){ sum })); + + } + + return result; + +} diff --git a/src/analysis/scan/items/count.h b/src/analysis/scan/items/count.h new file mode 100644 index 0000000..d83714e --- /dev/null +++ b/src/analysis/scan/items/count.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * count.h - prototypes pour la récupération de la taille du contenu scanné + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_COUNT_H +#define _ANALYSIS_SCAN_ITEMS_COUNT_H + + +#include <glib-object.h> + + +#include "../item.h" + + + +#define G_TYPE_SCAN_COUNT_FUNCTION g_scan_count_function_get_type() +#define G_SCAN_COUNT_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_COUNT_FUNCTION, GScanCountFunction)) +#define G_IS_SCAN_COUNT_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_COUNT_FUNCTION)) +#define G_SCAN_COUNT_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_COUNT_FUNCTION, GScanCountFunctionClass)) +#define G_IS_SCAN_COUNT_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_COUNT_FUNCTION)) +#define G_SCAN_COUNT_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_COUNT_FUNCTION, GScanCountFunctionClass)) + + +/* Mesure de la quantité de données scannées (instance) */ +typedef GScanRegisteredItem GScanCountFunction; + +/* Mesure de la quantité de données scannées (classe) */ +typedef GScanRegisteredItemClass GScanCountFunctionClass; + + +/* Indique le type défini pour un décompte d'ensemble. */ +GType g_scan_count_function_get_type(void); + +/* Constitue une fonction de décompte d'éléments d'un ensemble. */ +GScanRegisteredItem *g_scan_count_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_COUNT_H */ diff --git a/src/analysis/scan/items/datasize.c b/src/analysis/scan/items/datasize.c new file mode 100644 index 0000000..11fe649 --- /dev/null +++ b/src/analysis/scan/items/datasize.c @@ -0,0 +1,272 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * datasize.c - récupération de la taille du contenu scanné + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "datasize.h" + + +#include "../item-int.h" +#include "../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des mesures de quantité de données. */ +static void g_scan_datasize_function_class_init(GScanDatasizeFunctionClass *); + +/* Initialise une instance de mesure de quantité de données. */ +static void g_scan_datasize_function_init(GScanDatasizeFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_datasize_function_dispose(GScanDatasizeFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_datasize_function_finalize(GScanDatasizeFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_datasize_function_get_name(const GScanDatasizeFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_datasize_function_reduce(GScanDatasizeFunction *, GScanContext *, GScanScope *, GScanExpression **); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_datasize_function_run_call(GScanDatasizeFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une mesure de quantité de données scannées. */ +G_DEFINE_TYPE(GScanDatasizeFunction, g_scan_datasize_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des mesures de quantité de données. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_datasize_function_class_init(GScanDatasizeFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_datasize_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_datasize_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_datasize_function_get_name; + registered->reduce = (reduce_registered_item_fc)g_scan_datasize_function_reduce; + registered->run_call = (run_registered_item_call_fc)g_scan_datasize_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de mesure de quantité de données. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_datasize_function_init(GScanDatasizeFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_datasize_function_dispose(GScanDatasizeFunction *func) +{ + G_OBJECT_CLASS(g_scan_datasize_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_datasize_function_finalize(GScanDatasizeFunction *func) +{ + G_OBJECT_CLASS(g_scan_datasize_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de récupération de taille de données. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_datasize_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_DATASIZE_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_datasize_function_get_name(const GScanDatasizeFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("datasize"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la réduction opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_datasize_function_reduce(GScanDatasizeFunction *item, GScanContext *ctx, GScanScope *scope, GScanExpression **out) +{ + bool result; /* Bilan à retourner */ + GBinContent *content; /* Contenu à manipuler */ + phys_t size; /* Quantité de données liées */ + + result = true; + + content = g_scan_context_get_content(ctx); + + size = g_binary_content_compute_size(content); + + *out = g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, (unsigned long long []){ size }); + + g_object_unref(G_OBJECT(content)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_datasize_function_run_call(GScanDatasizeFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + + result = g_scan_datasize_function_reduce(item, ctx, scope, (GScanExpression **)out); + + return result; + +} diff --git a/src/analysis/scan/items/datasize.h b/src/analysis/scan/items/datasize.h new file mode 100644 index 0000000..daa71d1 --- /dev/null +++ b/src/analysis/scan/items/datasize.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * datasize.h - prototypes pour la récupération de la taille du contenu scanné + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_DATASIZE_H +#define _ANALYSIS_SCAN_ITEMS_DATASIZE_H + + +#include <glib-object.h> + + +#include "../item.h" + + + +#define G_TYPE_SCAN_DATASIZE_FUNCTION g_scan_datasize_function_get_type() +#define G_SCAN_DATASIZE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_DATASIZE_FUNCTION, GScanDatasizeFunction)) +#define G_IS_SCAN_DATASIZE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_DATASIZE_FUNCTION)) +#define G_SCAN_DATASIZE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_DATASIZE_FUNCTION, GScanDatasizeFunctionClass)) +#define G_IS_SCAN_DATASIZE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_DATASIZE_FUNCTION)) +#define G_SCAN_DATASIZE_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_DATASIZE_FUNCTION, GScanDatasizeFunctionClass)) + + +/* Mesure de la quantité de données scannées (instance) */ +typedef GScanRegisteredItem GScanDatasizeFunction; + +/* Mesure de la quantité de données scannées (classe) */ +typedef GScanRegisteredItemClass GScanDatasizeFunctionClass; + + +/* Indique le type défini pour une mesure de quantité de données scannées. */ +GType g_scan_datasize_function_get_type(void); + +/* Constitue une fonction de récupération de taille de données. */ +GScanRegisteredItem *g_scan_datasize_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_DATASIZE_H */ diff --git a/src/analysis/scan/items/magic/Makefile.am b/src/analysis/scan/items/magic/Makefile.am new file mode 100644 index 0000000..1d741ff --- /dev/null +++ b/src/analysis/scan/items/magic/Makefile.am @@ -0,0 +1,16 @@ + +noinst_LTLIBRARIES = libanalysisscanitemsmagic.la + + +libanalysisscanitemsmagic_la_SOURCES = \ + cookie.h cookie.c \ + mime-encoding.h mime-encoding.c \ + mime-type.h mime-type.c \ + type.h type.c + +libanalysisscanitemsmagic_la_CFLAGS = $(LIBGOBJ_CFLAGS) $(LIBMAGIC_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanitemsmagic_la_SOURCES:%c=) diff --git a/src/analysis/scan/items/magic/cookie.c b/src/analysis/scan/items/magic/cookie.c new file mode 100644 index 0000000..41f26a0 --- /dev/null +++ b/src/analysis/scan/items/magic/cookie.c @@ -0,0 +1,122 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * cookie.c - chargement des motifs de reconnaissance de contenus + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "cookie.h" + + +#include <assert.h> + + +#include <i18n.h> + + +#include "../../../../core/logs.h" + + + +/* Référence des bibliothèques de reconnaissance */ +static magic_t __magic_cookie = 0; + + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Charge les motifs de reconnaissance de contenus. * +* * +* Retour : Bilan de l'opération de chargemement. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool init_magic_cookie(void) +{ + bool result; /* Bilan à retourner */ + int ret; /* Bilan d'une opération */ + + __magic_cookie = magic_open(0); + + ret = magic_load(__magic_cookie, NULL); + result = (ret != -1); + + if (!result) + log_variadic_message(LMT_EXT_ERROR, _("cannot load magic database: %s"), magic_error(__magic_cookie)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Décharge les motifs de reconnaissance de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void exit_magic_cookie(void) +{ + magic_close(__magic_cookie); + +} + + +/****************************************************************************** +* * +* Paramètres : flags = forme de reconnaissance à préparer. * +* * +* Description : Fournit la référence aux mécanismes de reconnaissance. * +* * +* Retour : Cookie prêt à emploi. * +* * +* Remarques : - * +* * +******************************************************************************/ + +magic_t get_magic_cookie(int flags) +{ + magic_t result; /* Référence à retourner */ +#ifndef NDEBUG + int ret; /* Bilan de la préparation */ +#endif + + result = __magic_cookie; + assert(result != 0); + +#ifndef NDEBUG + ret = magic_setflags(result, flags); + assert(ret != -1); +#else + magic_setflags(result, flags); +#endif + + return result; + +} diff --git a/src/analysis/scan/items/magic/cookie.h b/src/analysis/scan/items/magic/cookie.h new file mode 100644 index 0000000..0ee2274 --- /dev/null +++ b/src/analysis/scan/items/magic/cookie.h @@ -0,0 +1,44 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * cookie.h - prototypes pour le chargement des motifs de reconnaissance de contenus + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MAGIC_COOKIE_H +#define _ANALYSIS_SCAN_ITEMS_MAGIC_COOKIE_H + + +#include <magic.h> +#include <stdbool.h> + + + +/* Charge les motifs de reconnaissance de contenus. */ +bool init_magic_cookie(void); + +/* Décharge les motifs de reconnaissance de contenus. */ +void exit_magic_cookie(void); + +/* Fournit la référence aux mécanismes de reconnaissance. */ +magic_t get_magic_cookie(int); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MAGIC_COOKIE_H */ diff --git a/src/analysis/scan/items/magic/mime-encoding.c b/src/analysis/scan/items/magic/mime-encoding.c new file mode 100644 index 0000000..aee23ff --- /dev/null +++ b/src/analysis/scan/items/magic/mime-encoding.c @@ -0,0 +1,270 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * mime-encoding.c - reconnaissance de l'encodage d'un contenu + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "mime-encoding.h" + + +#include "cookie.h" +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des reconnaissances de contenus. */ +static void g_scan_mime_encoding_function_class_init(GScanMimeEncodingFunctionClass *); + +/* Initialise une instance de reconnaissance de contenus. */ +static void g_scan_mime_encoding_function_init(GScanMimeEncodingFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_mime_encoding_function_dispose(GScanMimeEncodingFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_mime_encoding_function_finalize(GScanMimeEncodingFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_mime_encoding_function_get_name(const GScanMimeEncodingFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_mime_encoding_function_run_call(GScanMimeEncodingFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une reconnaissance d'encodages de contenus. */ +G_DEFINE_TYPE(GScanMimeEncodingFunction, g_scan_mime_encoding_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des reconnaissances de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_encoding_function_class_init(GScanMimeEncodingFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_mime_encoding_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_mime_encoding_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_mime_encoding_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_mime_encoding_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de reconnaissance de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_encoding_function_init(GScanMimeEncodingFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_encoding_function_dispose(GScanMimeEncodingFunction *func) +{ + G_OBJECT_CLASS(g_scan_mime_encoding_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_encoding_function_finalize(GScanMimeEncodingFunction *func) +{ + G_OBJECT_CLASS(g_scan_mime_encoding_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de cernement d'encodages de contenus. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_mime_encoding_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MIME_ENCODING_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_mime_encoding_function_get_name(const GScanMimeEncodingFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("mime_encoding"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_mime_encoding_function_run_call(GScanMimeEncodingFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + magic_t cookie; /* Référence des bibliothèques */ + GBinContent *content; /* Contenu à manipuler */ + vmpa2t pos; /* Tête de lecture */ + phys_t size; /* Quantité de données dispos. */ + const bin_t *data; /* Accès à des données */ + const char *desc; /* Description du contenu */ + sized_string_t string; /* Description à diffuser */ + + result = (count == 0); + if (!result) goto exit; + + cookie = get_magic_cookie(MAGIC_MIME_ENCODING); + + content = g_scan_context_get_content(ctx); + + g_binary_content_compute_start_pos(content, &pos); + + size = g_binary_content_compute_size(content); + + data = g_binary_content_get_raw_access(content, &pos, size); + + desc = magic_buffer(cookie, data, size); + + if (desc != NULL) + { + string.data = (char *)desc; + string.len = strlen(desc); + } + else + { + string.data = ""; + string.len = 0; + } + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &string)); + + g_object_unref(G_OBJECT(content)); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/magic/mime-encoding.h b/src/analysis/scan/items/magic/mime-encoding.h new file mode 100644 index 0000000..45ac241 --- /dev/null +++ b/src/analysis/scan/items/magic/mime-encoding.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * mime-encoding.h - prototypes pour la reconnaissance de l'encodage d'un contenu + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MAGIC_MIME_ENCODING_H +#define _ANALYSIS_SCAN_ITEMS_MAGIC_MIME_ENCODING_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_MIME_ENCODING_FUNCTION g_scan_mime_encoding_function_get_type() +#define G_SCAN_MIME_ENCODING_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MIME_ENCODING_FUNCTION, GScanMimeEncodingFunction)) +#define G_IS_SCAN_MIME_ENCODING_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MIME_ENCODING_FUNCTION)) +#define G_SCAN_MIME_ENCODING_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MIME_ENCODING_FUNCTION, GScanMimeEncodingFunctionClass)) +#define G_IS_SCAN_MIME_ENCODING_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MIME_ENCODING_FUNCTION)) +#define G_SCAN_MIME_ENCODING_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MIME_ENCODING_FUNCTION, GScanMimeEncodingFunctionClass)) + + +/* Reconnaissance d'encodages de contenus (instance) */ +typedef GScanRegisteredItem GScanMimeEncodingFunction; + +/* Reconnaissance d'encodages de contenus (classe) */ +typedef GScanRegisteredItemClass GScanMimeEncodingFunctionClass; + + +/* Indique le type défini pour une reconnaissance d'encodages de contenus. */ +GType g_scan_mime_encoding_function_get_type(void); + +/* Constitue une fonction de cernement d'encodages de contenus. */ +GScanRegisteredItem *g_scan_mime_encoding_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MAGIC_MIME_ENCODING_H */ diff --git a/src/analysis/scan/items/magic/mime-type.c b/src/analysis/scan/items/magic/mime-type.c new file mode 100644 index 0000000..0635a33 --- /dev/null +++ b/src/analysis/scan/items/magic/mime-type.c @@ -0,0 +1,270 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * type.c - reconnaissance du type MIME d'un contenu + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "mime-type.h" + + +#include "cookie.h" +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des reconnaissances de contenus. */ +static void g_scan_mime_type_function_class_init(GScanMimeTypeFunctionClass *); + +/* Initialise une instance de reconnaissance de contenus. */ +static void g_scan_mime_type_function_init(GScanMimeTypeFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_mime_type_function_dispose(GScanMimeTypeFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_mime_type_function_finalize(GScanMimeTypeFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_mime_type_function_get_name(const GScanMimeTypeFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_mime_type_function_run_call(GScanMimeTypeFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une reconnaissance de types de contenus. */ +G_DEFINE_TYPE(GScanMimeTypeFunction, g_scan_mime_type_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des reconnaissances de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_type_function_class_init(GScanMimeTypeFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_mime_type_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_mime_type_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_mime_type_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_mime_type_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de reconnaissance de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_type_function_init(GScanMimeTypeFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_type_function_dispose(GScanMimeTypeFunction *func) +{ + G_OBJECT_CLASS(g_scan_mime_type_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_mime_type_function_finalize(GScanMimeTypeFunction *func) +{ + G_OBJECT_CLASS(g_scan_mime_type_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction d'identification de types de contenus.* +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_mime_type_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MIME_TYPE_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_mime_type_function_get_name(const GScanMimeTypeFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("mime_type"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_mime_type_function_run_call(GScanMimeTypeFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + magic_t cookie; /* Référence des bibliothèques */ + GBinContent *content; /* Contenu à manipuler */ + vmpa2t pos; /* Tête de lecture */ + phys_t size; /* Quantité de données dispos. */ + const bin_t *data; /* Accès à des données */ + const char *desc; /* Description du contenu */ + sized_string_t string; /* Description à diffuser */ + + result = (count == 0); + if (!result) goto exit; + + cookie = get_magic_cookie(MAGIC_MIME_TYPE); + + content = g_scan_context_get_content(ctx); + + g_binary_content_compute_start_pos(content, &pos); + + size = g_binary_content_compute_size(content); + + data = g_binary_content_get_raw_access(content, &pos, size); + + desc = magic_buffer(cookie, data, size); + + if (desc != NULL) + { + string.data = (char *)desc; + string.len = strlen(desc); + } + else + { + string.data = ""; + string.len = 0; + } + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &string)); + + g_object_unref(G_OBJECT(content)); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/magic/mime-type.h b/src/analysis/scan/items/magic/mime-type.h new file mode 100644 index 0000000..f46cd15 --- /dev/null +++ b/src/analysis/scan/items/magic/mime-type.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * mime-type.h - prototypes pour la reconnaissance du type MIME d'un contenu + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MAGIC_MIME_TYPE_H +#define _ANALYSIS_SCAN_ITEMS_MAGIC_MIME_TYPE_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_MIME_TYPE_FUNCTION g_scan_mime_type_function_get_type() +#define G_SCAN_MIME_TYPE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MIME_TYPE_FUNCTION, GScanMimeTypeFunction)) +#define G_IS_SCAN_MIME_TYPE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MIME_TYPE_FUNCTION)) +#define G_SCAN_MIME_TYPE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MIME_TYPE_FUNCTION, GScanMimeTypeFunctionClass)) +#define G_IS_SCAN_MIME_TYPE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MIME_TYPE_FUNCTION)) +#define G_SCAN_MIME_TYPE_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MIME_TYPE_FUNCTION, GScanMimeTypeFunctionClass)) + + +/* Reconnaissance de types de contenus (instance) */ +typedef GScanRegisteredItem GScanMimeTypeFunction; + +/* Reconnaissance de types de contenus (classe) */ +typedef GScanRegisteredItemClass GScanMimeTypeFunctionClass; + + +/* Indique le type défini pour une reconnaissance de types de contenus. */ +GType g_scan_mime_type_function_get_type(void); + +/* Constitue une fonction d'identification de types de contenus. */ +GScanRegisteredItem *g_scan_mime_type_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MAGIC_MIME_TYPE_H */ diff --git a/src/analysis/scan/items/magic/type.c b/src/analysis/scan/items/magic/type.c new file mode 100644 index 0000000..43b16ff --- /dev/null +++ b/src/analysis/scan/items/magic/type.c @@ -0,0 +1,270 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * type.c - reconnaissance du type d'un contenu + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "type.h" + + +#include "cookie.h" +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des reconnaissances de contenus. */ +static void g_scan_magic_type_function_class_init(GScanMagicTypeFunctionClass *); + +/* Initialise une instance de reconnaissance de contenus. */ +static void g_scan_magic_type_function_init(GScanMagicTypeFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_magic_type_function_dispose(GScanMagicTypeFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_magic_type_function_finalize(GScanMagicTypeFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_magic_type_function_get_name(const GScanMagicTypeFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_magic_type_function_run_call(GScanMagicTypeFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une reconnaissance de types de contenus. */ +G_DEFINE_TYPE(GScanMagicTypeFunction, g_scan_magic_type_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des reconnaissances de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_magic_type_function_class_init(GScanMagicTypeFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_magic_type_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_magic_type_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_magic_type_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_magic_type_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de reconnaissance de contenus. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_magic_type_function_init(GScanMagicTypeFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_magic_type_function_dispose(GScanMagicTypeFunction *func) +{ + G_OBJECT_CLASS(g_scan_magic_type_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_magic_type_function_finalize(GScanMagicTypeFunction *func) +{ + G_OBJECT_CLASS(g_scan_magic_type_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction d'identification de types de contenus.* +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_magic_type_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MAGIC_TYPE_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_magic_type_function_get_name(const GScanMagicTypeFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("type"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_magic_type_function_run_call(GScanMagicTypeFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + magic_t cookie; /* Référence des bibliothèques */ + GBinContent *content; /* Contenu à manipuler */ + vmpa2t pos; /* Tête de lecture */ + phys_t size; /* Quantité de données dispos. */ + const bin_t *data; /* Accès à des données */ + const char *desc; /* Description du contenu */ + sized_string_t string; /* Description à diffuser */ + + result = (count == 0); + if (!result) goto exit; + + cookie = get_magic_cookie(MAGIC_NONE); + + content = g_scan_context_get_content(ctx); + + g_binary_content_compute_start_pos(content, &pos); + + size = g_binary_content_compute_size(content); + + data = g_binary_content_get_raw_access(content, &pos, size); + + desc = magic_buffer(cookie, data, size); + + if (desc != NULL) + { + string.data = (char *)desc; + string.len = strlen(desc); + } + else + { + string.data = ""; + string.len = 0; + } + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &string)); + + g_object_unref(G_OBJECT(content)); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/magic/type.h b/src/analysis/scan/items/magic/type.h new file mode 100644 index 0000000..7a26da3 --- /dev/null +++ b/src/analysis/scan/items/magic/type.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * type.h - prototypes pour la reconnaissance du type d'un contenu + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MAGIC_TYPE_H +#define _ANALYSIS_SCAN_ITEMS_MAGIC_TYPE_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_MAGIC_TYPE_FUNCTION g_scan_magic_type_function_get_type() +#define G_SCAN_MAGIC_TYPE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MAGIC_TYPE_FUNCTION, GScanMagicTypeFunction)) +#define G_IS_SCAN_MAGIC_TYPE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MAGIC_TYPE_FUNCTION)) +#define G_SCAN_MAGIC_TYPE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MAGIC_TYPE_FUNCTION, GScanMagicTypeFunctionClass)) +#define G_IS_SCAN_MAGIC_TYPE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MAGIC_TYPE_FUNCTION)) +#define G_SCAN_MAGIC_TYPE_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MAGIC_TYPE_FUNCTION, GScanMagicTypeFunctionClass)) + + +/* Reconnaissance de types de contenus (instance) */ +typedef GScanRegisteredItem GScanMagicTypeFunction; + +/* Reconnaissance de types de contenus (classe) */ +typedef GScanRegisteredItemClass GScanMagicTypeFunctionClass; + + +/* Indique le type défini pour une reconnaissance de types de contenus. */ +GType g_scan_magic_type_function_get_type(void); + +/* Constitue une fonction d'identification de types de contenus. */ +GScanRegisteredItem *g_scan_magic_type_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MAGIC_TYPE_H */ diff --git a/src/analysis/scan/items/math/Makefile.am b/src/analysis/scan/items/math/Makefile.am new file mode 100644 index 0000000..1f37c72 --- /dev/null +++ b/src/analysis/scan/items/math/Makefile.am @@ -0,0 +1,13 @@ + +noinst_LTLIBRARIES = libanalysisscanitemsmath.la + + +libanalysisscanitemsmath_la_SOURCES = \ + to_string.h to_string.c + +libanalysisscanitemsmath_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanitemsmath_la_SOURCES:%c=) diff --git a/src/analysis/scan/items/math/to_string.c b/src/analysis/scan/items/math/to_string.c new file mode 100644 index 0000000..5debb61 --- /dev/null +++ b/src/analysis/scan/items/math/to_string.c @@ -0,0 +1,381 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * to_string.c - conversion d'une valeur entière en chaîne + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "to_string.h" + + +#include <assert.h> +#include <stdlib.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des conversions de texte en entier. */ +static void g_scan_math_to_string_function_class_init(GScanMathToStringFunctionClass *); + +/* Initialise une instance de conversion de texte en entier. */ +static void g_scan_math_to_string_function_init(GScanMathToStringFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_math_to_string_function_dispose(GScanMathToStringFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_math_to_string_function_finalize(GScanMathToStringFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_math_to_string_function_get_name(const GScanMathToStringFunction *); + +/* Réalise la conversion d'une valeur en texte. */ +static void convert_integer_to_string(unsigned long long, unsigned long long, char **); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_math_to_string_function_run_call(GScanMathToStringFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une conversion d'entier en texte. */ +G_DEFINE_TYPE(GScanMathToStringFunction, g_scan_math_to_string_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des conversions de texte en entier. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_math_to_string_function_class_init(GScanMathToStringFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_math_to_string_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_math_to_string_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_math_to_string_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_math_to_string_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de conversion de texte en entier. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_math_to_string_function_init(GScanMathToStringFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_math_to_string_function_dispose(GScanMathToStringFunction *func) +{ + G_OBJECT_CLASS(g_scan_math_to_string_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_math_to_string_function_finalize(GScanMathToStringFunction *func) +{ + G_OBJECT_CLASS(g_scan_math_to_string_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée une fonction de conversion de valeur entière en texte. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_math_to_string_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MATH_TO_STRING_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_math_to_string_function_get_name(const GScanMathToStringFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("to_string"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : val = valeur entière à traiter. * +* base = base à considérer. * +* data = tête d'écriture à faire évoluer. [OUT] * +* * +* Description : Réalise la conversion d'une valeur en texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void convert_integer_to_string(unsigned long long val, unsigned long long base, char **data) +{ + static const char digits[16] = "0123456789abcdef"; + + if (val < base) + *((*data)++) = digits[val]; + + else + { + convert_integer_to_string(val / base, base, data); + + *((*data)++) = digits[val % base]; + + } + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_math_to_string_function_run_call(GScanMathToStringFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + GScanLiteralExpression *literal; /* Version plus accessible */ + LiteralValueType vtype; /* Type de valeur portée */ + long long sval; /* Valeur signée obtenue */ + unsigned long long uval; /* Valeur non signée obtenue */ + bool negative; /* Besoin de signe en préfixe ?*/ + unsigned long long base; /* Base de conversion */ + char *data; /* Chaîne "C" à constituer */ + char *iter; /* Tête d'écriture */ + sized_string_t string; /* Chaîne finale complète */ + + /* Validation des arguments */ + + result = (count == 1 || count == 2); + if (!result) goto exit; + + result = G_IS_SCAN_LITERAL_EXPRESSION(args[0]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[0]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_SIGNED_INTEGER || vtype == LVT_UNSIGNED_INTEGER); + if (!result) goto exit; + + if (vtype == LVT_SIGNED_INTEGER) + { + result = g_scan_literal_expression_get_signed_integer_value(literal, &sval); + if (!result) goto exit; + + assert(sval < 0); + + negative = (sval < 0); + + if (negative) + uval = -sval; + + } + else + { + result = g_scan_literal_expression_get_unsigned_integer_value(literal, &uval); + if (!result) goto exit; + } + + if (count == 1) + base = 10; + + else + { + result = G_IS_SCAN_LITERAL_EXPRESSION(args[1]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[1]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_UNSIGNED_INTEGER); + if (!result) goto exit; + + result = g_scan_literal_expression_get_unsigned_integer_value(literal, &base); + if (!result) goto exit; + + result = (base == 2 || base == 8 || base == 10 || base == 16); + if (!result) goto exit; + + } + + /* Réalisation de l'opération attendue */ + + data = malloc((1 + 2 + 64 * 8 + 1) * sizeof(char)); + iter = data; + + if (negative) + *(iter++) = '-'; + + switch (base) + { + case 2: + *(iter++) = '0'; + *(iter++) = 'b'; + break; + + case 8: + *(iter++) = '0'; + break; + + case 10: + break; + + case 16: + *(iter++) = '0'; + *(iter++) = 'x'; + break; + + default: + assert(false); + break; + + } + + convert_integer_to_string(uval, base, &iter); + + string.data = data; + string.len = iter - data; + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &string)); + + free(data); + + result = true; + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/math/to_string.h b/src/analysis/scan/items/math/to_string.h new file mode 100644 index 0000000..b9213a9 --- /dev/null +++ b/src/analysis/scan/items/math/to_string.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * to_string.h - prototypes pour la conversion d'une valeur entière en chaîne + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MATH_TO_STRING_H +#define _ANALYSIS_SCAN_ITEMS_MATH_TO_STRING_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_MATH_TO_STRING_FUNCTION g_scan_math_to_string_function_get_type() +#define G_SCAN_MATH_TO_STRING_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MATH_TO_STRING_FUNCTION, GScanMathToStringFunction)) +#define G_IS_SCAN_MATH_TO_STRING_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MATH_TO_STRING_FUNCTION)) +#define G_SCAN_MATH_TO_STRING_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MATH_TO_STRING_FUNCTION, GScanMathToStringFunctionClass)) +#define G_IS_SCAN_MATH_TO_STRING_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MATH_TO_STRING_FUNCTION)) +#define G_SCAN_MATH_TO_STRING_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MATH_TO_STRING_FUNCTION, GScanMathToStringFunctionClass)) + + +/* Conversion d'une valeur entière en valeur textuelle (instance) */ +typedef GScanRegisteredItem GScanMathToStringFunction; + +/* Conversion d'une valeur entière en valeur textuelle (classe) */ +typedef GScanRegisteredItemClass GScanMathToStringFunctionClass; + + +/* Indique le type défini pour une conversion d'entier en texte. */ +GType g_scan_math_to_string_function_get_type(void); + +/* Crée une fonction de conversion de valeur entière en texte. */ +GScanRegisteredItem *g_scan_math_to_string_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MATH_TO_STRING_H */ diff --git a/src/analysis/scan/items/maxcommon.c b/src/analysis/scan/items/maxcommon.c new file mode 100644 index 0000000..e8c4db3 --- /dev/null +++ b/src/analysis/scan/items/maxcommon.c @@ -0,0 +1,374 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * maxcommon.c - détermination de la plus grand occurrence au sein d'un ensemble d'éléments + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "maxcommon.h" + + +#include <assert.h> +#include <malloc.h> + + +#include "../item-int.h" +#include "../exprs/literal.h" +#include "../../../glibext/comparison-int.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des repérages de plus grande occurrence. */ +static void g_scan_maxcommon_function_class_init(GScanMaxcommonFunctionClass *); + +/* Initialise une instance de repérage d'occurrence maximake. */ +static void g_scan_maxcommon_function_init(GScanMaxcommonFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_maxcommon_function_dispose(GScanMaxcommonFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_maxcommon_function_finalize(GScanMaxcommonFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_maxcommon_function_get_name(const GScanMaxcommonFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_maxcommon_function_run_call(GScanMaxcommonFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un décompte d'élément le plus représenté dans une série. */ +G_DEFINE_TYPE(GScanMaxcommonFunction, g_scan_maxcommon_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des repérages de plus grande occurrence.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_maxcommon_function_class_init(GScanMaxcommonFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_maxcommon_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_maxcommon_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_maxcommon_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_maxcommon_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de repérage d'occurrence maximake. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_maxcommon_function_init(GScanMaxcommonFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_maxcommon_function_dispose(GScanMaxcommonFunction *func) +{ + G_OBJECT_CLASS(g_scan_maxcommon_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_maxcommon_function_finalize(GScanMaxcommonFunction *func) +{ + G_OBJECT_CLASS(g_scan_maxcommon_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de calcul de plus grande occurrence. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_maxcommon_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MAXCOMMON_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_maxcommon_function_get_name(const GScanMaxcommonFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("maxcommon"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_maxcommon_function_run_call(GScanMaxcommonFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + size_t used; /* Prochain emplacement libre */ + GScanExpression **collected; /* Représentants de groupes */ + size_t *scores; /* Taille de ces groupes */ + size_t i; /* Boucle de parcours #1 */ + size_t k; /* Boucle de parcours #2 */ + bool status; /* Bilan de la comparaison */ + bool equal; /* Egalité établie ? */ + size_t arg0_count; /* Taille de l'argument unique */ + GScanExpression *arg0_item; /* Elément de cet argument */ + size_t best; /* Meilleur score identifié */ + + result = (count > 0); + if (!result) goto exit; + + used = 0; + + /* Si la série à étudier est directement fournie */ + if (count > 1) + { + collected = malloc(count * sizeof(GScanExpression *)); + scores = malloc(count * sizeof(size_t)); + + for (i = 0; i < count; i++) + { + for (k = 0; k < used; k++) + { + status = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(args[i]), + G_COMPARABLE_ITEM(collected[k]), + RCO_EQ, &equal); + + if (status && equal) + break; + + } + + if (k < used) + scores[k]++; + + else + { + collected[used] = args[i]; + g_object_ref(G_OBJECT(args[i])); + scores[used] = 1; + + used++; + + } + + } + + } + + /* Sinon on considère que l'arguement unique porte la liste (idéalement) */ + else + { + if (G_IS_SCAN_LITERAL_EXPRESSION(args[0]) || !g_scan_expression_handle_set_features(args[0])) + { + best = 1; + goto quick_unique; + } + +#ifndef NDEBUG + g_scan_expression_count_items(args[0], ctx, &arg0_count); +#else + status = g_scan_expression_count_items(args[0], ctx, &arg0_count); + assert(status); +#endif + + collected = malloc(arg0_count * sizeof(GScanExpression *)); + scores = malloc(arg0_count * sizeof(size_t)); + + if (arg0_count == 0) + { + best = 0; + goto quick_empty; + } + + for (i = 0; i < arg0_count; i++) + { +#ifndef NDEBUG + g_scan_expression_get_item(args[0], i, ctx, &arg0_item); +#else + status = g_scan_expression_get_item(args[0], i, ctx, &arg0_item); + assert(status); +#endif + + for (k = 0; k < used; k++) + { + status = g_comparable_item_compare_rich(G_COMPARABLE_ITEM(arg0_item), + G_COMPARABLE_ITEM(collected[k]), + RCO_EQ, &equal); + + if (status && equal) + break; + + } + + if (k < used) + { + g_object_unref(G_OBJECT(arg0_item)); + scores[k]++; + } + + else + { + collected[used] = arg0_item; + scores[used] = 1; + + used++; + + } + + } + + } + + /* Analyse des résultats */ + + best = 0; + + for (i = 0; i < used; i++) + if (scores[i] > best) + best = scores[i]; + + for (i = 0; i < used; i++) + g_object_unref(G_OBJECT(collected[i])); + + free(collected); + free(scores); + + quick_unique: + + assert(best > 0); + + quick_empty: + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, (unsigned long long []){ best })); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/maxcommon.h b/src/analysis/scan/items/maxcommon.h new file mode 100644 index 0000000..a834c00 --- /dev/null +++ b/src/analysis/scan/items/maxcommon.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * maxcommon.h - prototypes pour la détermination de la plus grand occurrence au sein d'un ensemble d'éléments + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MAXCOMMON_H +#define _ANALYSIS_SCAN_ITEMS_MAXCOMMON_H + + +#include <glib-object.h> + + +#include "../item.h" + + + +#define G_TYPE_SCAN_MAXCOMMON_FUNCTION g_scan_maxcommon_function_get_type() +#define G_SCAN_MAXCOMMON_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MAXCOMMON_FUNCTION, GScanMaxcommonFunction)) +#define G_IS_SCAN_MAXCOMMON_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MAXCOMMON_FUNCTION)) +#define G_SCAN_MAXCOMMON_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MAXCOMMON_FUNCTION, GScanMaxcommonFunctionClass)) +#define G_IS_SCAN_MAXCOMMON_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MAXCOMMON_FUNCTION)) +#define G_SCAN_MAXCOMMON_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MAXCOMMON_FUNCTION, GScanMaxcommonFunctionClass)) + + +/* Détermination de la plus grand occurrence au sein d'un ensemble (instance) */ +typedef GScanRegisteredItem GScanMaxcommonFunction; + +/* Détermination de la plus grand occurrence au sein d'un ensemble (classe) */ +typedef GScanRegisteredItemClass GScanMaxcommonFunctionClass; + + +/* Indique le type défini pour un décompte d'élément le plus représenté dans une série. */ +GType g_scan_maxcommon_function_get_type(void); + +/* Constitue une fonction de calcul de plus grande occurrence. */ +GScanRegisteredItem *g_scan_maxcommon_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MAXCOMMON_H */ diff --git a/src/analysis/scan/items/modpath.c b/src/analysis/scan/items/modpath.c new file mode 100644 index 0000000..62d3387 --- /dev/null +++ b/src/analysis/scan/items/modpath.c @@ -0,0 +1,306 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * modpath.c - récupération des combinaisons de modification de motifs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "modpath.h" + + +#include "../item-int.h" + + +#include "../exprs/handler.h" +#include "../exprs/literal.h" +#include "../exprs/set.h" +#include "../matches/bytes.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des énumérations de formules de motifs. */ +static void g_scan_modpath_function_class_init(GScanModpathFunctionClass *); + +/* Initialise une instance d'énumération de formules de motifs. */ +static void g_scan_modpath_function_init(GScanModpathFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_modpath_function_dispose(GScanModpathFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_modpath_function_finalize(GScanModpathFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_modpath_function_get_name(const GScanModpathFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_modpath_function_run_call(GScanModpathFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une énumération de formules créant des motifs. */ +G_DEFINE_TYPE(GScanModpathFunction, g_scan_modpath_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des énumérations de formules de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modpath_function_class_init(GScanModpathFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_modpath_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_modpath_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_modpath_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_modpath_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance d'énumération de formules de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modpath_function_init(GScanModpathFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modpath_function_dispose(GScanModpathFunction *func) +{ + G_OBJECT_CLASS(g_scan_modpath_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modpath_function_finalize(GScanModpathFunction *func) +{ + G_OBJECT_CLASS(g_scan_modpath_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction d'énumération des formules de motifs. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_modpath_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MODPATH_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_modpath_function_get_name(const GScanModpathFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("modpath"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_modpath_function_run_call(GScanModpathFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + + return false; + +#if 0 /* FIXME */ + + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours #1 */ + size_t mcount; /* Quantité de correspondances */ + GScanMatch **matches; /* Correspondances établies */ + size_t k; /* Boucle de parcours #2 */ + sized_string_t path; /* Combinaison à conserver */ + GScanExpression *subitem; /* Nouvel élément à transmettre*/ + + /* Validation préalable du type des arguments */ + + result = true; + + for (i = 0; i < count && result; i++) + result = G_IS_SCAN_PATTERN_HANDLER(args[i]); + + if (!result) + goto exit; + + /* Construction des chemins attendus */ + + *out = G_OBJECT(g_scan_generic_set_new()); + + for (i = 0; i < count; i++) + { + matches = g_scan_pattern_handler_get_all_matches(G_SCAN_PATTERN_HANDLER(args[i]), ctx, &mcount); + if (mcount == 0) continue; + + /** + * La série est à priori constituée d'éléments de même type, donc + * un test unique suffit. + */ + if (!G_IS_SCAN_BYTES_MATCH(matches[0])) + { + for (k = 0; k < mcount; k++) + g_object_unref(G_OBJECT(matches[k])); + } + + else + { + for (k = 0; k < mcount; k++) + { + path.data = g_scan_bytes_match_get_modifier_path(G_SCAN_BYTES_MATCH(matches[k])); + if (path.data == NULL) continue; + + path.len = strlen(path.data); + + subitem = g_scan_literal_expression_new(LVT_STRING, &path); + + g_scan_generic_set_add_item(G_SCAN_GENERIC_SET(*out), subitem); + + g_object_unref(G_OBJECT(subitem)); + + exit_szstr(&path); + + g_object_unref(G_OBJECT(matches[k])); + + } + + } + + free(matches); + + } + + exit: + + return result; + +#endif + +} diff --git a/src/analysis/scan/items/modpath.h b/src/analysis/scan/items/modpath.h new file mode 100644 index 0000000..3a78ef7 --- /dev/null +++ b/src/analysis/scan/items/modpath.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * modpath.h - prototypes pour la récupération des combinaisons de modification de motifs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_MODPATH_H +#define _ANALYSIS_SCAN_ITEMS_MODPATH_H + + +#include <glib-object.h> + + +#include "../item.h" + + + +#define G_TYPE_SCAN_MODPATH_FUNCTION g_scan_modpath_function_get_type() +#define G_SCAN_MODPATH_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MODPATH_FUNCTION, GScanModpathFunction)) +#define G_IS_SCAN_MODPATH_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MODPATH_FUNCTION)) +#define G_SCAN_MODPATH_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MODPATH_FUNCTION, GScanModpathFunctionClass)) +#define G_IS_SCAN_MODPATH_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MODPATH_FUNCTION)) +#define G_SCAN_MODPATH_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MODPATH_FUNCTION, GScanModpathFunctionClass)) + + +/* Récupération de formules à l'origine de la construction de motifs (instance) */ +typedef GScanRegisteredItem GScanModpathFunction; + +/* Récupération de formules à l'origine de la construction de motifs (classe) */ +typedef GScanRegisteredItemClass GScanModpathFunctionClass; + + +/* Indique le type défini pour une énumération de formules créant des motifs. */ +GType g_scan_modpath_function_get_type(void); + +/* Constitue une fonction d'énumération des formules de motifs. */ +GScanRegisteredItem *g_scan_modpath_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_MODPATH_H */ diff --git a/src/analysis/scan/items/string/Makefile.am b/src/analysis/scan/items/string/Makefile.am new file mode 100644 index 0000000..6f8d6c5 --- /dev/null +++ b/src/analysis/scan/items/string/Makefile.am @@ -0,0 +1,16 @@ + +noinst_LTLIBRARIES = libanalysisscanitemsstring.la + + +libanalysisscanitemsstring_la_SOURCES = \ + lower.h lower.c \ + to_int.h to_int.c \ + upper.h upper.c \ + wide.h wide.c + +libanalysisscanitemsstring_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanitemsstring_la_SOURCES:%c=) diff --git a/src/analysis/scan/items/string/lower.c b/src/analysis/scan/items/string/lower.c new file mode 100644 index 0000000..241d87a --- /dev/null +++ b/src/analysis/scan/items/string/lower.c @@ -0,0 +1,270 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * lower.c - bascule de lettres en minuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "lower.h" + + +#include <ctype.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des bascules de lettres en minuscules. */ +static void g_scan_string_lower_function_class_init(GScanStringLowerFunctionClass *); + +/* Initialise une instance de bascule de lettres en minuscules. */ +static void g_scan_string_lower_function_init(GScanStringLowerFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_string_lower_function_dispose(GScanStringLowerFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_string_lower_function_finalize(GScanStringLowerFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_string_lower_function_get_name(const GScanStringLowerFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_string_lower_function_run_call(GScanStringLowerFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une bascule de la casse d'une suite de caractères. */ +G_DEFINE_TYPE(GScanStringLowerFunction, g_scan_string_lower_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des bascules de lettres en minuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_lower_function_class_init(GScanStringLowerFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_string_lower_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_string_lower_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_string_lower_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_string_lower_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de bascule de lettres en minuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_lower_function_init(GScanStringLowerFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_lower_function_dispose(GScanStringLowerFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_lower_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_lower_function_finalize(GScanStringLowerFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_lower_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de bascule de lettres en minuscules. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_string_lower_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_STRING_LOWER_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_string_lower_function_get_name(const GScanStringLowerFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("lower"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_string_lower_function_run_call(GScanStringLowerFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + GScanLiteralExpression *literal; /* Version plus accessible */ + LiteralValueType vtype; /* Type de valeur portée */ + const sized_string_t *string; /* Description du chaîne */ + sized_string_t new; /* Description transformée */ + size_t i; /* Boucle de parcours */ + + /* Validation des arguments */ + + result = (count == 1); + if (!result) goto exit; + + result = G_IS_SCAN_LITERAL_EXPRESSION(args[0]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[0]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_STRING); + if (!result) goto exit; + + result = g_scan_literal_expression_get_string_value(literal, &string); + if (!result) goto exit; + + /* Réalisation de l'opération attendue */ + + new.data = malloc(string->len); + new.len = string->len; + + for (i = 0; i < string->len; i++) + new.data[i] = tolower(string->data[i]); + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &new)); + + exit_szstr(&new); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/string/lower.h b/src/analysis/scan/items/string/lower.h new file mode 100644 index 0000000..b9eb00a --- /dev/null +++ b/src/analysis/scan/items/string/lower.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * lower.h - prototypes pour la bascule de lettres en minuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_STRING_LOWER_H +#define _ANALYSIS_SCAN_ITEMS_STRING_LOWER_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_STRING_LOWER_FUNCTION g_scan_string_lower_function_get_type() +#define G_SCAN_STRING_LOWER_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_STRING_LOWER_FUNCTION, GScanStringLowerFunction)) +#define G_IS_SCAN_STRING_LOWER_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_STRING_LOWER_FUNCTION)) +#define G_SCAN_STRING_LOWER_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_STRING_LOWER_FUNCTION, GScanStringLowerFunctionClass)) +#define G_IS_SCAN_STRING_LOWER_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_STRING_LOWER_FUNCTION)) +#define G_SCAN_STRING_LOWER_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_STRING_LOWER_FUNCTION, GScanStringLowerFunctionClass)) + + +/* Bascule d'une suite de caractères en minuscules (instance) */ +typedef GScanRegisteredItem GScanStringLowerFunction; + +/* Bascule d'une suite de caractères en minuscules (classe) */ +typedef GScanRegisteredItemClass GScanStringLowerFunctionClass; + + +/* Indique le type défini pour une bascule de la casse d'une suite de caractères. */ +GType g_scan_string_lower_function_get_type(void); + +/* Constitue une fonction de bascule de lettres en minuscules. */ +GScanRegisteredItem *g_scan_string_lower_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_STRING_LOWER_H */ diff --git a/src/analysis/scan/items/string/to_int.c b/src/analysis/scan/items/string/to_int.c new file mode 100644 index 0000000..150fd06 --- /dev/null +++ b/src/analysis/scan/items/string/to_int.c @@ -0,0 +1,303 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * to_int.c - conversion d'une chaîne en valeur entière + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "to_int.h" + + +#include <stdlib.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des conversions de texte en entier. */ +static void g_scan_string_to_int_function_class_init(GScanStringToIntFunctionClass *); + +/* Initialise une instance de conversion de texte en entier. */ +static void g_scan_string_to_int_function_init(GScanStringToIntFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_string_to_int_function_dispose(GScanStringToIntFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_string_to_int_function_finalize(GScanStringToIntFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_string_to_int_function_get_name(const GScanStringToIntFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_string_to_int_function_run_call(GScanStringToIntFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une conversion de texte en entier. */ +G_DEFINE_TYPE(GScanStringToIntFunction, g_scan_string_to_int_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des conversions de texte en entier. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_to_int_function_class_init(GScanStringToIntFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_string_to_int_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_string_to_int_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_string_to_int_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_string_to_int_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de conversion de texte en entier. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_to_int_function_init(GScanStringToIntFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_to_int_function_dispose(GScanStringToIntFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_to_int_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_to_int_function_finalize(GScanStringToIntFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_to_int_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée une fonction de conversion de texte en valeur entière. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_string_to_int_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_STRING_TO_INT_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_string_to_int_function_get_name(const GScanStringToIntFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("to_int"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_string_to_int_function_run_call(GScanStringToIntFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + GScanLiteralExpression *literal; /* Version plus accessible */ + LiteralValueType vtype; /* Type de valeur portée */ + const sized_string_t *string; /* Chaîne à convertir */ + unsigned long long base; /* Base de conversion */ + char *data; /* Chaîne "C" à considérer */ + long long sval; /* Valeur signée obtenue */ + unsigned long long uval; /* Valeur non signée obtenue */ + + /* Validation des arguments */ + + result = (count == 1 || count == 2); + if (!result) goto exit; + + result = G_IS_SCAN_LITERAL_EXPRESSION(args[0]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[0]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_STRING); + if (!result) goto exit; + + result = g_scan_literal_expression_get_string_value(literal, &string); + if (!result) goto exit; + + if (string->len == 0) goto exit; + + if (count == 1) + base = 0; + + else + { + result = G_IS_SCAN_LITERAL_EXPRESSION(args[1]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[1]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_UNSIGNED_INTEGER); + if (!result) goto exit; + + result = g_scan_literal_expression_get_unsigned_integer_value(literal, &base); + if (!result) goto exit; + + } + + /* Réalisation de l'opération attendue */ + + data = strndup(string->data, string->len); + + if (string->data[0] == '-') + { + sval = strtoll(data, NULL, base); + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_SIGNED_INTEGER, &sval)); + + } + else + { + uval = strtoll(data, NULL, base); + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, &uval)); + + } + + free(data); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/string/to_int.h b/src/analysis/scan/items/string/to_int.h new file mode 100644 index 0000000..ffd971b --- /dev/null +++ b/src/analysis/scan/items/string/to_int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * to_int.h - prototypes pour la conversion d'une chaîne en valeur entière + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_STRING_TO_INT_H +#define _ANALYSIS_SCAN_ITEMS_STRING_TO_INT_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_STRING_TO_INT_FUNCTION g_scan_string_to_int_function_get_type() +#define G_SCAN_STRING_TO_INT_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_STRING_TO_INT_FUNCTION, GScanStringToIntFunction)) +#define G_IS_SCAN_STRING_TO_INT_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_STRING_TO_INT_FUNCTION)) +#define G_SCAN_STRING_TO_INT_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_STRING_TO_INT_FUNCTION, GScanStringToIntFunctionClass)) +#define G_IS_SCAN_STRING_TO_INT_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_STRING_TO_INT_FUNCTION)) +#define G_SCAN_STRING_TO_INT_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_STRING_TO_INT_FUNCTION, GScanStringToIntFunctionClass)) + + +/* Conversion d'une valeur textuelle en valeur entière (instance) */ +typedef GScanRegisteredItem GScanStringToIntFunction; + +/* Conversion d'une valeur textuelle en valeur entière (classe) */ +typedef GScanRegisteredItemClass GScanStringToIntFunctionClass; + + +/* Indique le type défini pour une conversion de texte en entier. */ +GType g_scan_string_to_int_function_get_type(void); + +/* Crée une fonction de conversion de texte en valeur entière. */ +GScanRegisteredItem *g_scan_string_to_int_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_STRING_TO_INT_H */ diff --git a/src/analysis/scan/items/string/upper.c b/src/analysis/scan/items/string/upper.c new file mode 100644 index 0000000..d09ae00 --- /dev/null +++ b/src/analysis/scan/items/string/upper.c @@ -0,0 +1,270 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * upper.c - bascule de lettres en majuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "upper.h" + + +#include <ctype.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des bascules de lettres en majuscules. */ +static void g_scan_string_upper_function_class_init(GScanStringUpperFunctionClass *); + +/* Initialise une instance de bascule de lettres en majuscules. */ +static void g_scan_string_upper_function_init(GScanStringUpperFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_string_upper_function_dispose(GScanStringUpperFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_string_upper_function_finalize(GScanStringUpperFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_string_upper_function_get_name(const GScanStringUpperFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_string_upper_function_run_call(GScanStringUpperFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une bascule de la casse d'une suite de caractères. */ +G_DEFINE_TYPE(GScanStringUpperFunction, g_scan_string_upper_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des bascules de lettres en majuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_upper_function_class_init(GScanStringUpperFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_string_upper_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_string_upper_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_string_upper_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_string_upper_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de bascule de lettres en majuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_upper_function_init(GScanStringUpperFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_upper_function_dispose(GScanStringUpperFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_upper_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_upper_function_finalize(GScanStringUpperFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_upper_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de bascule de lettres en majuscules. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_string_upper_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_STRING_UPPER_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_string_upper_function_get_name(const GScanStringUpperFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("upper"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_string_upper_function_run_call(GScanStringUpperFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + GScanLiteralExpression *literal; /* Version plus accessible */ + LiteralValueType vtype; /* Type de valeur portée */ + const sized_string_t *string; /* Description du chaîne */ + sized_string_t new; /* Description transformée */ + size_t i; /* Boucle de parcours */ + + /* Validation des arguments */ + + result = (count == 1); + if (!result) goto exit; + + result = G_IS_SCAN_LITERAL_EXPRESSION(args[0]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[0]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_STRING); + if (!result) goto exit; + + result = g_scan_literal_expression_get_string_value(literal, &string); + if (!result) goto exit; + + /* Réalisation de l'opération attendue */ + + new.data = malloc(string->len); + new.len = string->len; + + for (i = 0; i < string->len; i++) + new.data[i] = toupper(string->data[i]); + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &new)); + + exit_szstr(&new); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/string/upper.h b/src/analysis/scan/items/string/upper.h new file mode 100644 index 0000000..4fdeb09 --- /dev/null +++ b/src/analysis/scan/items/string/upper.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * upper.h - prototypes pour la bascule de lettres en majuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_STRING_UPPER_H +#define _ANALYSIS_SCAN_ITEMS_STRING_UPPER_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_STRING_UPPER_FUNCTION g_scan_string_upper_function_get_type() +#define G_SCAN_STRING_UPPER_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_STRING_UPPER_FUNCTION, GScanStringUpperFunction)) +#define G_IS_SCAN_STRING_UPPER_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_STRING_UPPER_FUNCTION)) +#define G_SCAN_STRING_UPPER_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_STRING_UPPER_FUNCTION, GScanStringUpperFunctionClass)) +#define G_IS_SCAN_STRING_UPPER_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_STRING_UPPER_FUNCTION)) +#define G_SCAN_STRING_UPPER_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_STRING_UPPER_FUNCTION, GScanStringUpperFunctionClass)) + + +/* Bascule d'une suite de caractères en majuscules (instance) */ +typedef GScanRegisteredItem GScanStringUpperFunction; + +/* Bascule d'une suite de caractères en majuscules (classe) */ +typedef GScanRegisteredItemClass GScanStringUpperFunctionClass; + + +/* Indique le type défini pour une bascule de la casse d'une suite de caractères. */ +GType g_scan_string_upper_function_get_type(void); + +/* Constitue une fonction de bascule de lettres en majuscules. */ +GScanRegisteredItem *g_scan_string_upper_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_STRING_UPPER_H */ diff --git a/src/analysis/scan/items/string/wide.c b/src/analysis/scan/items/string/wide.c new file mode 100644 index 0000000..378f21c --- /dev/null +++ b/src/analysis/scan/items/string/wide.c @@ -0,0 +1,270 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * wide.c - bascule de texte ASCII en UTF-16 + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "wide.h" + + +#include <ctype.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des bascules de texte ASCII en UTF-16. */ +static void g_scan_string_wide_function_class_init(GScanStringWideFunctionClass *); + +/* Initialise une instance de bascule de texte ASCII en UTF-16. */ +static void g_scan_string_wide_function_init(GScanStringWideFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_string_wide_function_dispose(GScanStringWideFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_string_wide_function_finalize(GScanStringWideFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_string_wide_function_get_name(const GScanStringWideFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_string_wide_function_run_call(GScanStringWideFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une bascule de texte ASCII en UTF-16. */ +G_DEFINE_TYPE(GScanStringWideFunction, g_scan_string_wide_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des bascules de texte ASCII en UTF-16. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_wide_function_class_init(GScanStringWideFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_string_wide_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_string_wide_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_string_wide_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_string_wide_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de bascule de texte ASCII en UTF-16. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_wide_function_init(GScanStringWideFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_wide_function_dispose(GScanStringWideFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_wide_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_string_wide_function_finalize(GScanStringWideFunction *func) +{ + G_OBJECT_CLASS(g_scan_string_wide_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de bascule de texte ASCII en UTF-16. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_string_wide_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_STRING_WIDE_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_string_wide_function_get_name(const GScanStringWideFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("wide"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_string_wide_function_run_call(GScanStringWideFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + GScanLiteralExpression *literal; /* Version plus accessible */ + LiteralValueType vtype; /* Type de valeur portée */ + const sized_string_t *string; /* Description du chaîne */ + sized_string_t new; /* Description transformée */ + size_t i; /* Boucle de parcours */ + + /* Validation des arguments */ + + result = (count == 1); + if (!result) goto exit; + + result = G_IS_SCAN_LITERAL_EXPRESSION(args[0]); + if (!result) goto exit; + + literal = G_SCAN_LITERAL_EXPRESSION(args[0]); + + vtype = g_scan_literal_expression_get_value_type(literal); + + result = (vtype == LVT_STRING); + if (!result) goto exit; + + result = g_scan_literal_expression_get_string_value(literal, &string); + if (!result) goto exit; + + /* Réalisation de l'opération attendue */ + + new.len = string->len * 2; + new.data = calloc(new.len, sizeof(bin_t)); + + for (i = 0; i < string->len; i++) + new.data[i * 2] = string->data[i]; + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_STRING, &new)); + + exit_szstr(&new); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/string/wide.h b/src/analysis/scan/items/string/wide.h new file mode 100644 index 0000000..65195bd --- /dev/null +++ b/src/analysis/scan/items/string/wide.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * wide.h - prototypes pour la bascule de texte ASCII en UTF-16 + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_STRING_WIDE_H +#define _ANALYSIS_SCAN_ITEMS_STRING_WIDE_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_STRING_WIDE_FUNCTION g_scan_string_wide_function_get_type() +#define G_SCAN_STRING_WIDE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_STRING_WIDE_FUNCTION, GScanStringWideFunction)) +#define G_IS_SCAN_STRING_WIDE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_STRING_WIDE_FUNCTION)) +#define G_SCAN_STRING_WIDE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_STRING_WIDE_FUNCTION, GScanStringWideFunctionClass)) +#define G_IS_SCAN_STRING_WIDE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_STRING_WIDE_FUNCTION)) +#define G_SCAN_STRING_WIDE_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_STRING_WIDE_FUNCTION, GScanStringWideFunctionClass)) + + +/* Bascule d'une suite de texte ASCII en UTF-16 (instance) */ +typedef GScanRegisteredItem GScanStringWideFunction; + +/* Bascule d'une suite de texte ASCII en UTF-16 (classe) */ +typedef GScanRegisteredItemClass GScanStringWideFunctionClass; + + +/* Indique le type défini pour une bascule de texte ASCII en UTF-16. */ +GType g_scan_string_wide_function_get_type(void); + +/* Constitue une fonction de bascule de texte ASCII en UTF-16. */ +GScanRegisteredItem *g_scan_string_wide_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_STRING_WIDE_H */ diff --git a/src/analysis/scan/items/time/Makefile.am b/src/analysis/scan/items/time/Makefile.am new file mode 100644 index 0000000..e5330be --- /dev/null +++ b/src/analysis/scan/items/time/Makefile.am @@ -0,0 +1,14 @@ + +noinst_LTLIBRARIES = libanalysisscanitemstime.la + + +libanalysisscanitemstime_la_SOURCES = \ + make.h make.c \ + now.h now.c + +libanalysisscanitemstime_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanitemstime_la_SOURCES:%c=) diff --git a/src/analysis/scan/items/time/make.c b/src/analysis/scan/items/time/make.c new file mode 100644 index 0000000..e7330a3 --- /dev/null +++ b/src/analysis/scan/items/time/make.c @@ -0,0 +1,350 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * make.c - construction de volume de secondes à partir d'une date + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "make.h" + + +#include <assert.h> +#include <time.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des conversions de dates en secondes. */ +static void g_scan_time_make_function_class_init(GScanTimeMakeFunctionClass *); + +/* Initialise une instance de convertisseur de date en secondes. */ +static void g_scan_time_make_function_init(GScanTimeMakeFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_time_make_function_dispose(GScanTimeMakeFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_time_make_function_finalize(GScanTimeMakeFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_time_make_function_get_name(const GScanTimeMakeFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_time_make_function_run_call(GScanTimeMakeFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une conversion de date en nombre de secondes. */ +G_DEFINE_TYPE(GScanTimeMakeFunction, g_scan_time_make_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des conversions de dates en secondes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_make_function_class_init(GScanTimeMakeFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_time_make_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_time_make_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_time_make_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_time_make_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de convertisseur de date en secondes.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_make_function_init(GScanTimeMakeFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_make_function_dispose(GScanTimeMakeFunction *func) +{ + G_OBJECT_CLASS(g_scan_time_make_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_make_function_finalize(GScanTimeMakeFunction *func) +{ + G_OBJECT_CLASS(g_scan_time_make_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de décompte du temps écoulé. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_time_make_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TIME_MAKE_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_time_make_function_get_name(const GScanTimeMakeFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("make"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_time_make_function_run_call(GScanTimeMakeFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + bool status; /* Possibilité de construction */ + size_t i; /* Boucle de parcours */ + LiteralValueType vtype; /* Type de valeur portée */ + struct tm date; /* Date à mettre en place */ + unsigned long long value; /* Valeur entière à utiliser */ + time_t computed; /* Nombre de secondes déterminé*/ + + /* Validation des arguments */ + + result = (count == 3 || count == 6); + if (!result) goto exit; + + status = true; + + for (i = 0; i < count && status; i++) + { + status = G_IS_SCAN_LITERAL_EXPRESSION(args[i]); + if (!status) break; + + vtype = g_scan_literal_expression_get_value_type(G_SCAN_LITERAL_EXPRESSION(args[i])); + + status = (vtype == LVT_UNSIGNED_INTEGER); + if (!status) break; + + } + + if (!status) goto exit; + + /* Lecture des arguments */ + + memset(&date, 0, sizeof(struct tm)); + + status = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[0]), &value); + assert(status); + if (!status) goto exit; + + if (value < 1900) + { + result = false; + goto exit; + } + + date.tm_year = value - 1900; + + status = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[1]), &value); + assert(status); + if (!status) goto exit; + + if (value > 12) + { + result = false; + goto exit; + } + + date.tm_mon = value - 1; + + status = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[2]), &value); + assert(status); + if (!status) goto exit; + + if (value < 1 || value > 31) + { + result = false; + goto exit; + } + + date.tm_mday = value; + + if (count == 6) + { + status = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[3]), &value); + assert(status); + if (!status) goto exit; + + if (value >= 24) + { + result = false; + goto exit; + } + + date.tm_hour = value; + + status = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[4]), &value); + assert(status); + if (!status) goto exit; + + if (value >= 60) + { + result = false; + goto exit; + } + + date.tm_min = value; + + status = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[5]), &value); + assert(status); + if (!status) goto exit; + + if (value >= 60) + { + result = false; + goto exit; + } + + date.tm_sec = value; + + } + + /* Construction de la valeur finale */ + + computed = timegm(&date); + + if (computed != (time_t)-1) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, (unsigned long long []){ computed })); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/time/make.h b/src/analysis/scan/items/time/make.h new file mode 100644 index 0000000..f4be276 --- /dev/null +++ b/src/analysis/scan/items/time/make.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * make.h - prototypes pour une construction de volume de secondes à partir d'une date + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_TIME_MAKE_H +#define _ANALYSIS_SCAN_ITEMS_TIME_MAKE_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_TIME_MAKE_FUNCTION g_scan_time_make_function_get_type() +#define G_SCAN_TIME_MAKE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TIME_MAKE_FUNCTION, GScanTimeMakeFunction)) +#define G_IS_SCAN_TIME_MAKE_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TIME_MAKE_FUNCTION)) +#define G_SCAN_TIME_MAKE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TIME_MAKE_FUNCTION, GScanTimeMakeFunctionClass)) +#define G_IS_SCAN_TIME_MAKE_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TIME_MAKE_FUNCTION)) +#define G_SCAN_TIME_MAKE_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TIME_MAKE_FUNCTION, GScanTimeMakeFunctionClass)) + + +/* Convertisseur de date en nombre de secondes depuis le 01/01/1970 (instance) */ +typedef GScanRegisteredItem GScanTimeMakeFunction; + +/* Convertisseur de date en nombre de secondes depuis le 01/01/1970 (classe) */ +typedef GScanRegisteredItemClass GScanTimeMakeFunctionClass; + + +/* Indique le type défini pour une conversion de date en nombre de secondes. */ +GType g_scan_time_make_function_get_type(void); + +/* Constitue une fonction de décompte du temps écoulé. */ +GScanRegisteredItem *g_scan_time_make_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_TIME_MAKE_H */ diff --git a/src/analysis/scan/items/time/now.c b/src/analysis/scan/items/time/now.c new file mode 100644 index 0000000..7f8b627 --- /dev/null +++ b/src/analysis/scan/items/time/now.c @@ -0,0 +1,243 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * now.c - décompte du temps écoulé depuis Epoch + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "now.h" + + +#include <time.h> + + +#include "../../item-int.h" +#include "../../exprs/literal.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des décomptes de temps écoulé. */ +static void g_scan_time_now_function_class_init(GScanTimeNowFunctionClass *); + +/* Initialise une instance de décompte de temps écoulé. */ +static void g_scan_time_now_function_init(GScanTimeNowFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_time_now_function_dispose(GScanTimeNowFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_time_now_function_finalize(GScanTimeNowFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_time_now_function_get_name(const GScanTimeNowFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_time_now_function_run_call(GScanTimeNowFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un décompte de secondes écoulées depuis le 01/01/1970. */ +G_DEFINE_TYPE(GScanTimeNowFunction, g_scan_time_now_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des décomptes de temps écoulé. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_now_function_class_init(GScanTimeNowFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_time_now_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_time_now_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_time_now_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_time_now_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de décompte de temps écoulé. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_now_function_init(GScanTimeNowFunction *func) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_now_function_dispose(GScanTimeNowFunction *func) +{ + G_OBJECT_CLASS(g_scan_time_now_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_time_now_function_finalize(GScanTimeNowFunction *func) +{ + G_OBJECT_CLASS(g_scan_time_now_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Constitue une fonction de décompte du temps écoulé. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_time_now_function_new(void) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TIME_NOW_FUNCTION, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_time_now_function_get_name(const GScanTimeNowFunction *item) +{ + char *result; /* Désignation à retourner */ + + result = strdup("now"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_time_now_function_run_call(GScanTimeNowFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + time_t now; /* Date relative courante */ + + result = (count == 0); + if (!result) goto exit; + + now = time(NULL); + + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, (unsigned long long []){ now })); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/time/now.h b/src/analysis/scan/items/time/now.h new file mode 100644 index 0000000..73ed52a --- /dev/null +++ b/src/analysis/scan/items/time/now.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * now.h - prototypes pour le décompte du temps écoulé depuis Epoch + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_TIME_NOW_H +#define _ANALYSIS_SCAN_ITEMS_TIME_NOW_H + + +#include <glib-object.h> + + +#include "../../item.h" + + + +#define G_TYPE_SCAN_TIME_NOW_FUNCTION g_scan_time_now_function_get_type() +#define G_SCAN_TIME_NOW_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TIME_NOW_FUNCTION, GScanTimeNowFunction)) +#define G_IS_SCAN_TIME_NOW_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TIME_NOW_FUNCTION)) +#define G_SCAN_TIME_NOW_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TIME_NOW_FUNCTION, GScanTimeNowFunctionClass)) +#define G_IS_SCAN_TIME_NOW_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TIME_NOW_FUNCTION)) +#define G_SCAN_TIME_NOW_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TIME_NOW_FUNCTION, GScanTimeNowFunctionClass)) + + +/* Décompte du nombre de seccondes écoulées depuis le 01/01/1970 (instance) */ +typedef GScanRegisteredItem GScanTimeNowFunction; + +/* Décompte du nombre de seccondes écoulées depuis le 01/01/1970 (classe) */ +typedef GScanRegisteredItemClass GScanTimeNowFunctionClass; + + +/* Indique le type défini pour un décompte de secondes écoulées depuis le 01/01/1970. */ +GType g_scan_time_now_function_get_type(void); + +/* Constitue une fonction de décompte du temps écoulé. */ +GScanRegisteredItem *g_scan_time_now_function_new(void); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_TIME_NOW_H */ diff --git a/src/analysis/scan/items/uint-int.h b/src/analysis/scan/items/uint-int.h new file mode 100644 index 0000000..49050e6 --- /dev/null +++ b/src/analysis/scan/items/uint-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * uint-int.h - prototypes internes pour la lecture d'un mot à partir de données binaires + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_UINT_INT_H +#define _ANALYSIS_SCAN_ITEMS_UINT_INT_H + + +#include "uint.h" + + +#include "../item-int.h" + + + +/* Fonction conduisant à la lecture d'un mot (instance) */ +struct _GScanUintFunction +{ + GScanRegisteredItem parent; /* A laisser en premier */ + + MemoryDataSize size; /* Taille du mot à lire */ + SourceEndian endian; /* Boutisme à respecter */ + +}; + +/* Fonction conduisant à la lecture d'un mot (classe) */ +struct _GScanUintFunctionClass +{ + GScanRegisteredItemClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un nouvelle fonction de lecture d'entiers. */ +bool g_scan_uint_function_create(GScanUintFunction *, MemoryDataSize, SourceEndian); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_UINT_INT_H */ diff --git a/src/analysis/scan/items/uint.c b/src/analysis/scan/items/uint.c new file mode 100644 index 0000000..8060aca --- /dev/null +++ b/src/analysis/scan/items/uint.c @@ -0,0 +1,388 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * uint.c - lecture d'un mot à partir de données binaires + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "uint.h" + + +#include <assert.h> + + +#include "uint-int.h" +#include "../exprs/literal.h" +#include "../../../common/extstr.h" + + + +/* ---------------------- INTRODUCTION D'UNE NOUVELLE FONCTION ---------------------- */ + + +/* Initialise la classe des lectures de valeurs entières. */ +static void g_scan_uint_function_class_init(GScanUintFunctionClass *); + +/* Initialise une instance de lecture de valeur entière. */ +static void g_scan_uint_function_init(GScanUintFunction *); + +/* Supprime toutes les références externes. */ +static void g_scan_uint_function_dispose(GScanUintFunction *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_uint_function_finalize(GScanUintFunction *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_uint_function_get_name(const GScanUintFunction *); + +/* Réduit une expression à une forme plus simple. */ +static bool g_scan_uint_function_run_call(GScanUintFunction *, GScanExpression **, size_t, GScanContext *, GScanScope *, GObject **); + + + +/* ---------------------------------------------------------------------------------- */ +/* INTRODUCTION D'UNE NOUVELLE FONCTION */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une lecture de mot à partir de données binaires. */ +G_DEFINE_TYPE(GScanUintFunction, g_scan_uint_function, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des lectures de valeurs entières. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_uint_function_class_init(GScanUintFunctionClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_uint_function_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_uint_function_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_uint_function_get_name; + registered->run_call = (run_registered_item_call_fc)g_scan_uint_function_run_call; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance à initialiser. * +* * +* Description : Initialise une instance de lecture de valeur entière. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_uint_function_init(GScanUintFunction *func) +{ + func->size = MDS_UNDEFINED; + func->endian = SRE_LITTLE; + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_uint_function_dispose(GScanUintFunction *func) +{ + G_OBJECT_CLASS(g_scan_uint_function_parent_class)->dispose(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : func = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_uint_function_finalize(GScanUintFunction *func) +{ + G_OBJECT_CLASS(g_scan_uint_function_parent_class)->finalize(G_OBJECT(func)); + +} + + +/****************************************************************************** +* * +* Paramètres : size = taille du mot à venir lire dans les données. * +* * +* Description : Constitue une fonction de lecture de valeur entière. * +* * +* Retour : Fonction mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRegisteredItem *g_scan_uint_function_new(MemoryDataSize size, SourceEndian endian) +{ + GScanRegisteredItem *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_UINT_FUNCTION, NULL); + + if (!g_scan_uint_function_create(G_SCAN_UINT_FUNCTION(result), size, endian)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : func = encadrement d'un parcours de correspondances. * +* size = taille du mot à venir lire dans les données. * +* * +* Description : Met en place un nouvelle fonction de lecture d'entiers. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_uint_function_create(GScanUintFunction *func, MemoryDataSize size, SourceEndian endian) +{ + bool result; /* Bilan à retourner */ + + result = true; + + func->size = size; + func->endian = endian; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_uint_function_get_name(const GScanUintFunction *item) +{ + char *result; /* Désignation à retourner */ + + switch (item->size & ~MDS_SIGN) + { + case MDS_8_BITS_UNSIGNED: + result = strdup("int8"); + break; + + case MDS_16_BITS_UNSIGNED: + result = strdup("int16"); + break; + + case MDS_32_BITS_UNSIGNED: + result = strdup("int32"); + break; + + case MDS_64_BITS_UNSIGNED: + result = strdup("int64"); + break; + + default: + assert(false); + result = NULL; + break; + + } + + if (result) + { + if (!MDS_IS_SIGNED(item->size)) + result = strprep(result, "u"); + + if (item->endian == SRE_BIG) + result = stradd(result, "be"); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* args = liste d'éventuels arguments fournis. * +* count = taille de cette liste. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT] * +* * +* Description : Réduit une expression à une forme plus simple. * +* * +* Retour : Réduction correspondante, expression déjà réduite, ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_uint_function_run_call(GScanUintFunction *item, GScanExpression **args, size_t count, GScanContext *ctx, GScanScope *scope, GObject **out) +{ + bool result; /* Bilan à retourner */ + unsigned long long offset; /* Position du mot ciblé */ + GBinContent *content; /* Contenu à manipuler */ + vmpa2t pos; /* Tête de lecture */ + uint8_t val_s8; /* Valeur entière sur 8 bits */ + uint8_t val_u8; /* Valeur entière sur 8 bits */ + uint16_t val_s16; /* Valeur entière sur 16 bits */ + uint16_t val_u16; /* Valeur entière sur 16 bits */ + uint32_t val_s32; /* Valeur entière sur 32 bits */ + uint32_t val_u32; /* Valeur entière sur 32 bits */ + uint64_t val_s64; /* Valeur entière sur 64 bits */ + uint64_t val_u64; /* Valeur entière sur 64 bits */ + + result = (count == 1 && G_IS_SCAN_LITERAL_EXPRESSION(args[0])); + if (!result) goto exit; + + result = g_scan_literal_expression_get_unsigned_integer_value(G_SCAN_LITERAL_EXPRESSION(args[0]), &offset); + if (!result) goto exit; + + content = g_scan_context_get_content(ctx); + + g_binary_content_compute_start_pos(content, &pos); + advance_vmpa(&pos, offset); + + switch (item->size) + { + case MDS_8_BITS_SIGNED: + result = g_binary_content_read_s8(content, &pos, &val_s8); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_SIGNED_INTEGER, + (long long []){ val_s8 })); + break; + + case MDS_8_BITS_UNSIGNED: + result = g_binary_content_read_u8(content, &pos, &val_u8); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ val_u8 })); + break; + + case MDS_16_BITS_SIGNED: + result = g_binary_content_read_s16(content, &pos, item->endian, &val_s16); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_SIGNED_INTEGER, + (long long []){ val_s16 })); + break; + + case MDS_16_BITS_UNSIGNED: + result = g_binary_content_read_u16(content, &pos, item->endian, &val_u16); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ val_u16 })); + break; + + case MDS_32_BITS_SIGNED: + result = g_binary_content_read_s32(content, &pos, item->endian, &val_s32); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_SIGNED_INTEGER, + (long long []){ val_s32 })); + break; + + case MDS_32_BITS_UNSIGNED: + result = g_binary_content_read_u32(content, &pos, item->endian, &val_u32); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ val_u32 })); + break; + + case MDS_64_BITS_SIGNED: + result = g_binary_content_read_s64(content, &pos, item->endian, &val_s64); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_SIGNED_INTEGER, + (long long []){ val_s64 })); + break; + + case MDS_64_BITS_UNSIGNED: + result = g_binary_content_read_u64(content, &pos, item->endian, &val_u64); + if (result) + *out = G_OBJECT(g_scan_literal_expression_new(LVT_UNSIGNED_INTEGER, + (unsigned long long []){ val_u64 })); + break; + + default: + break; + + } + + g_object_unref(G_OBJECT(content)); + + exit: + + return result; + +} diff --git a/src/analysis/scan/items/uint.h b/src/analysis/scan/items/uint.h new file mode 100644 index 0000000..d3dd3cb --- /dev/null +++ b/src/analysis/scan/items/uint.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * uint.h - prototypes pour la lecture d'un mot à partir de données binaires + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_ITEMS_UINT_H +#define _ANALYSIS_SCAN_ITEMS_UINT_H + + +#include <glib-object.h> + + +#include "../item.h" +#include "../../../arch/archbase.h" + + + +#define G_TYPE_SCAN_UINT_FUNCTION g_scan_uint_function_get_type() +#define G_SCAN_UINT_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_UINT_FUNCTION, GScanUintFunction)) +#define G_IS_SCAN_UINT_FUNCTION(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_UINT_FUNCTION)) +#define G_SCAN_UINT_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_UINT_FUNCTION, GScanUintFunctionClass)) +#define G_IS_SCAN_UINT_FUNCTION_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_UINT_FUNCTION)) +#define G_SCAN_UINT_FUNCTION_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_UINT_FUNCTION, GScanUintFunctionClass)) + + +/* Fonction conduisant à la lecture d'un mot (instance) */ +typedef struct _GScanUintFunction GScanUintFunction; + +/* Fonction conduisant à la lecture d'un mot (classe) */ +typedef struct _GScanUintFunctionClass GScanUintFunctionClass; + + +/* Indique le type défini pour une lecture de mot à partir de données binaires. */ +GType g_scan_uint_function_get_type(void); + +/* Constitue une fonction de lecture de valeur entière. */ +GScanRegisteredItem *g_scan_uint_function_new(MemoryDataSize, SourceEndian); + + + +#endif /* _ANALYSIS_SCAN_ITEMS_UINT_H */ diff --git a/src/analysis/scan/matches-int.h b/src/analysis/scan/matches-int.h new file mode 100644 index 0000000..4e6a244 --- /dev/null +++ b/src/analysis/scan/matches-int.h @@ -0,0 +1,71 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * matches-int.h - prototypes internes pour la sauvegarde de correspondances de motif identifiées + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MATCHES_INT_H +#define _ANALYSIS_SCAN_MATCHES_INT_H + + +#include "matches.h" + + + +/* Dénombre les correspondances enregistrées pour un motif. */ +typedef size_t (* count_scan_matches_fc) (const GScanMatches *); + +/* Affiche une série de correspondances au format texte. */ +typedef void (* output_scan_matches_to_text_fc) (const GScanMatches *, int); + +/* Affiche une série de correspondances au format JSON. */ +typedef void (* output_scan_matches_to_json_fc) (const GScanMatches *, const sized_string_t *, unsigned int, int); + + +/* Correspondances trouvées avec un motif (instance) */ +struct _GScanMatches +{ + GObject parent; /* A laisser en premier */ + + /** + * L'aspect constant des instances marque seulement le fait que les + * pointeurs sont partagés avec un contexte, qui est le réel propriétaire + * de ces instances. + */ + const GScanContext *context; /* Contexte de rattachement */ + const GSearchPattern *source; /* Motif d'origine recherché */ + +}; + +/* Correspondances trouvées avec un motif (classe) */ +struct _GScanMatchesClass +{ + GObjectClass parent; /* A laisser en premier */ + + count_scan_matches_fc count; /* Décompte des correspondances*/ + + output_scan_matches_to_text_fc to_text; /* Impression au format texte */ + output_scan_matches_to_json_fc to_json; /* Impression au format JSON */ + +}; + + + +#endif /* _ANALYSIS_SCAN_MATCHES_INT_H */ diff --git a/src/analysis/scan/matches.c b/src/analysis/scan/matches.c new file mode 100644 index 0000000..1290c90 --- /dev/null +++ b/src/analysis/scan/matches.c @@ -0,0 +1,319 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * matches.c - sauvegarde de correspondances de motif identifiées + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "matches.h" + + +#include "matches-int.h" + + + +/* Initialise la classe des séries de correspondances de motifs. */ +static void g_scan_matches_class_init(GScanMatchesClass *); + +/* Initialise une instance de série de correspondances trouvées. */ +static void g_scan_matches_init(GScanMatches *); + +/* Supprime toutes les références externes. */ +static void g_scan_matches_dispose(GScanMatches *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_matches_finalize(GScanMatches *); + + + +/* Indique le type défini pour une série de correspondances identifiées. */ +G_DEFINE_TYPE(GScanMatches, g_scan_matches, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des séries de correspondances de motifs.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_matches_class_init(GScanMatchesClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_matches_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_matches_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance à initialiser. * +* * +* Description : Initialise une instance de série de correspondances trouvées.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_matches_init(GScanMatches *matches) +{ + matches->context = NULL; + matches->source = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_matches_dispose(GScanMatches *matches) +{ + /** + * Contexte et source sont des instances partagées. Leur propriété n'est + * donc pas à modifier avec un appel à g_clear_object() ici. + */ + + G_OBJECT_CLASS(g_scan_matches_parent_class)->dispose(G_OBJECT(matches)); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_matches_finalize(GScanMatches *matches) +{ + G_OBJECT_CLASS(g_scan_matches_parent_class)->finalize(G_OBJECT(matches)); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance dont l'initialisation est à compléter. * +* context = contexte associé au scan courant. * +* source = lien vers le motif recherché d'origine. * +* * +* Description : Associe des éléments de contexte à des correspondances. * +* * +* Retour : - * +* * +* Remarques : Aucun transfert de propriété n'a lieu ici ! * +* * +******************************************************************************/ + +void g_scan_matches_attach(GScanMatches *matches, const GScanContext *context, const GSearchPattern *source) +{ + matches->context = context; + matches->source = source; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = informations de correspondances à consulter. * +* * +* Description : Fournit le contexte du scan associé aux correspondances. * +* * +* Retour : Contexte de scan courant. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanContext *g_scan_bytes_matches_get_context(const GScanMatches *matches) +{ + GScanContext *result; /* Instance à retourner */ + + result = (GScanContext *)matches->context; + + g_object_ref(G_OBJECT(result)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à consulter. * +* * +* Description : Indique la source du motif d'origine recherché. * +* * +* Retour : Motif à l'origine des correspondances. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GSearchPattern *g_scan_matches_get_source(const GScanMatches *matches) +{ + GSearchPattern *result; /* Source à retourner */ + + result = (GSearchPattern *)matches->source; + + g_object_ref(G_OBJECT(result)); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondances à consulter. * +* * +* Description : Dénombre les correspondances enregistrées pour un motif. * +* * +* Retour : Quantité de correspondances établies. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_scan_matches_count(const GScanMatches *matches) +{ + size_t result; /* Quantité à retourner */ + GScanMatchesClass *class; /* Classe à activer */ + + class = G_SCAN_MATCHES_GET_CLASS(matches); + + result = class->count(matches); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à manipuler. * +* fd = canal d'écriture. * +* * +* Description : Affiche une série de correspondances au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_matches_output_to_text(const GScanMatches *matches, int fd) +{ + GScanMatchesClass *class; /* Classe à activer */ + + class = G_SCAN_MATCHES_GET_CLASS(matches); + + class->to_text(matches, fd); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à manipuler. * +* * +* Description : Convertit une série de correspondances en texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_matches_convert_as_text(const GScanMatches *matches) +{ + /* TODO */ + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à manipuler. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* * +* Description : Affiche une série de correspondances au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_matches_output_to_json(const GScanMatches *matches, const sized_string_t *padding, unsigned int level, int fd) +{ + GScanMatchesClass *class; /* Classe à activer */ + + class = G_SCAN_MATCHES_GET_CLASS(matches); + + class->to_json(matches, padding, level + 1, fd); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à manipuler. * +* * +* Description : Convertit une série de correspondances en JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_matches_convert_as_json(const GScanMatches *matches) +{ + /* TODO */ + +} diff --git a/src/analysis/scan/matches.h b/src/analysis/scan/matches.h new file mode 100644 index 0000000..26e54ed --- /dev/null +++ b/src/analysis/scan/matches.h @@ -0,0 +1,80 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * matches.h - prototypes pour la sauvegarde de correspondances de motif identifiées + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MATCHES_H +#define _ANALYSIS_SCAN_MATCHES_H + + +#include <glib-object.h> + + +#include "pattern.h" +#include "../../common/szstr.h" + + + +#define G_TYPE_SCAN_MATCHES g_scan_matches_get_type() +#define G_SCAN_MATCHES(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MATCHES, GScanMatches)) +#define G_IS_SCAN_MATCHES(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MATCHES)) +#define G_SCAN_MATCHES_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MATCHES, GScanMatchesClass)) +#define G_IS_SCAN_MATCHES_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MATCHES)) +#define G_SCAN_MATCHES_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MATCHES, GScanMatchesClass)) + + +/* Correspondances trouvées avec un motif (instance) */ +typedef struct _GScanMatches GScanMatches; + +/* Correspondances trouvées avec un motif (classe) */ +typedef struct _GScanMatchesClass GScanMatchesClass; + + +/* Indique le type défini pour une série de correspondances identifiées. */ +GType g_scan_matches_get_type(void); + +/* Associe des éléments de contexte à des correspondances. */ +void g_scan_matches_attach(GScanMatches *, const GScanContext *, const GSearchPattern *); + +/* Fournit le contexte du scan associé aux correspondances. */ +GScanContext *g_scan_bytes_matches_get_context(const GScanMatches *); + +/* Indique la source du motif d'origine recherché. */ +GSearchPattern *g_scan_matches_get_source(const GScanMatches *); + +/* Dénombre les correspondances enregistrées pour un motif. */ +size_t g_scan_matches_count(const GScanMatches *); + +/* Affiche une série de correspondances au format texte. */ +void g_scan_matches_output_to_text(const GScanMatches *, int); + +/* Convertit une série de correspondances en texte. */ +void g_scan_matches_convert_as_text(const GScanMatches *); + +/* Affiche une série de correspondances au format JSON. */ +void g_scan_matches_output_to_json(const GScanMatches *, const sized_string_t *, unsigned int, int); + +/* Convertit une série de correspondances en JSON. */ +void g_scan_matches_convert_as_json(const GScanMatches *); + + + +#endif /* _ANALYSIS_SCAN_MATCHES_H */ diff --git a/src/analysis/scan/matches/Makefile.am b/src/analysis/scan/matches/Makefile.am new file mode 100644 index 0000000..f1a69c3 --- /dev/null +++ b/src/analysis/scan/matches/Makefile.am @@ -0,0 +1,15 @@ + +noinst_LTLIBRARIES = libanalysisscanmatches.la + + +libanalysisscanmatches_la_SOURCES = \ + area.h area.c \ + bytes-int.h \ + bytes.h bytes.c + +libanalysisscanmatches_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanmatches_la_SOURCES:%c=) diff --git a/src/analysis/scan/matches/area.c b/src/analysis/scan/matches/area.c new file mode 100644 index 0000000..3f512b0 --- /dev/null +++ b/src/analysis/scan/matches/area.c @@ -0,0 +1,57 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * area.c - conservation des localisations de correspondances + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "area.h" + + + +/****************************************************************************** +* * +* Paramètres : a = première zone de correspondance à comparer. * +* b = seconde zone de correspondance à comparer. * +* * +* Description : Etablit une comparaison entre deux zones de correspondance. * +* * +* Retour : Bilan de la comparaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +int compare_match_area_as_dl_item(const dl_list_item *a, const dl_list_item *b) +{ + int result; /* Bilan à retourner */ + match_area_t *area_a; /* Première zone à traiter */ + match_area_t *area_b; /* Seconde zone à traiter */ + + area_a = match_area_from_item(a); + area_b = match_area_from_item(b); + + result = sort_uint64_t(area_a->start, area_b->start); + + if (result == 0) + result = sort_uint64_t(area_a->end, area_b->end); + + return result; + +} diff --git a/src/analysis/scan/matches/area.h b/src/analysis/scan/matches/area.h new file mode 100644 index 0000000..b059b35 --- /dev/null +++ b/src/analysis/scan/matches/area.h @@ -0,0 +1,85 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * area.h - prototypes pour la conservation des localisations de correspondances + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MATCHES_AREA_H +#define _ANALYSIS_SCAN_MATCHES_AREA_H + + +#include <assert.h> + + +#include "../../../arch/vmpa.h" +#include "../../../common/dllist.h" + + + +/* Couverture d'une correspondance */ +typedef struct _match_area_t +{ + phys_t start; /* Point de départ */ + phys_t end; /* Point d'arrivée (exclus) */ + + DL_LIST_ITEM(link); /* Lien vers les maillons */ + + size_t mod_path_index; /* Indice de construction */ + bool has_mod_path; /* Validité du champ précédent */ + +} match_area_t; + + +#define match_area_from_item(item) \ + (match_area_t *)container_of(item, match_area_t, link) + +#define add_tail_match_area(new, head) \ + dl_list_add_tail(new, head, match_area_t, link) + +#define del_match_area(item, head) \ + dl_list_del(item, head, match_area_t, link) + +#define for_each_match_area(pos, head) \ + dl_list_for_each(pos, head, match_area_t, link) + +#define for_each_match_area_safe(pos, head, next) \ + dl_list_for_each_safe(pos, head, next, match_area_t, link) + +#define is_last_match_area(item, head) \ + dl_list_is_last(item, head, link) + +#define merge_match_areas(head1, head2) \ + dl_list_merge(head1, head2, match_area_t, link) + +#define sort_match_areas_no_dup(head, len, cmp, dup) \ + ({ \ + assert(!dl_list_empty(*(head))); \ + dl_list_item *hmbr = &(*head)->link; \ + sort_dl_list_no_dup(&hmbr, len, cmp, dup); \ + match_area_from_item(hmbr); \ + }) + + +/* Etablit une comparaison entre deux zones de correspondance. */ +int compare_match_area_as_dl_item(const dl_list_item *, const dl_list_item *); + + + +#endif /* _ANALYSIS_SCAN_MATCHES_AREA_H */ diff --git a/src/analysis/scan/matches/bytes-int.h b/src/analysis/scan/matches/bytes-int.h new file mode 100644 index 0000000..f6239e3 --- /dev/null +++ b/src/analysis/scan/matches/bytes-int.h @@ -0,0 +1,54 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * bytes-int.h - prototypes internes pour la sauvegarde de correspondances avec des suites d'octets identifiées + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MATCHES_BYTES_INT_H +#define _ANALYSIS_SCAN_MATCHES_BYTES_INT_H + + +#include "bytes.h" + + +#include "../matches-int.h" + + + +/* Correspondances trouvées avec des suite d'octets (instance) */ +struct _GScanBytesMatches +{ + GScanMatches parent; /* A laisser en premier */ + + match_area_t *areas; /* Zones couvertes */ + size_t count; /* Nombre de zones */ + +}; + +/* Correspondances trouvées avec des suite d'octets (classe) */ +struct _GScanBytesMatchesClass +{ + GScanMatchesClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_MATCHES_BYTES_INT_H */ diff --git a/src/analysis/scan/matches/bytes.c b/src/analysis/scan/matches/bytes.c new file mode 100644 index 0000000..a23188b --- /dev/null +++ b/src/analysis/scan/matches/bytes.c @@ -0,0 +1,712 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * bytes.h - sauvegarde d'une correspondance identifiée de suite d'octets + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "bytes.h" + + +#include <assert.h> +#include <ctype.h> +#include <stdio.h> + + +#include "bytes-int.h" +#include "../patterns/token.h" +#include "../../../common/cpp.h" +#include "../../../core/logs.h" + + + +/* -------------------- CONSERVATION DE CORRESPONDANCES ETABLIES -------------------- */ + + +/* Initialise la classe des séries de correspondances d'octets. */ +static void g_scan_bytes_matches_class_init(GScanBytesMatchesClass *); + +/* Initialise une instance de série de correspondances trouvées. */ +static void g_scan_bytes_matches_init(GScanBytesMatches *); + +/* Supprime toutes les références externes. */ +static void g_scan_bytes_matches_dispose(GScanBytesMatches *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_bytes_matches_finalize(GScanBytesMatches *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Dénombre les correspondances enregistrées pour un motif. */ +static size_t g_scan_bytes_matches_count(const GScanBytesMatches *); + +/* Affiche une correspondance au format texte. */ +static void g_scan_bytes_matches_output_to_text(const GScanBytesMatches *, int); + +/* Affiche une correspondance au format JSON. */ +static void g_scan_bytes_matches_output_to_json(const GScanBytesMatches *, const sized_string_t *, unsigned int, int); + + + +/* ---------------------------------------------------------------------------------- */ +/* CONSERVATION DE CORRESPONDANCES ETABLIES */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une série de correspondances d'octets identifiées. */ +G_DEFINE_TYPE(GScanBytesMatches, g_scan_bytes_matches, G_TYPE_SCAN_MATCHES); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des séries de correspondances d'octets. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_bytes_matches_class_init(GScanBytesMatchesClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanMatchesClass *matches; /* Version parente de la classe*/ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_bytes_matches_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_bytes_matches_finalize; + + matches = G_SCAN_MATCHES_CLASS(klass); + + matches->count = (count_scan_matches_fc)g_scan_bytes_matches_count; + + matches->to_text = (output_scan_matches_to_text_fc)g_scan_bytes_matches_output_to_text; + matches->to_json = (output_scan_matches_to_json_fc)g_scan_bytes_matches_output_to_json; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance à initialiser. * +* * +* Description : Initialise une instance de série de correspondances trouvées.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_bytes_matches_init(GScanBytesMatches *matches) +{ + matches->areas = NULL; + matches->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_bytes_matches_dispose(GScanBytesMatches *matches) +{ + G_OBJECT_CLASS(g_scan_bytes_matches_parent_class)->dispose(G_OBJECT(matches)); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_bytes_matches_finalize(GScanBytesMatches *matches) +{ + G_OBJECT_CLASS(g_scan_bytes_matches_parent_class)->finalize(G_OBJECT(matches)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée un suivi pour série de correspondances avec des octets. * +* * +* Retour : Correspondance mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanMatches *g_scan_bytes_matches_new(void) +{ + GScanMatches *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_BYTES_MATCHES, NULL); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à manipuler. * +* list = correspondances établies à mémoriser. * +* count = taille de cette liste. * +* * +* Description : Intègre une liste de correspondances vérifiées. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_bytes_matches_set_list(GScanBytesMatches *matches, match_area_t *list, size_t count) +{ + matches->areas = list; + + matches->count = count; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à consulter. * +* index = indice de la correspondance recherchée. * +* * +* Description : Fournit les informations relatives à une correspondance. * +* * +* Retour : Propritétés de la correspondance visée ou NULL pour un échec.* +* * +* Remarques : - * +* * +******************************************************************************/ + +const match_area_t *g_scan_bytes_matches_get(const GScanBytesMatches *matches, size_t index) +{ + const match_area_t *result; /* Pointeur à retourner */ + + for_each_match_area(result, matches->areas) + { + if (index == 0) + break; + } + + assert(index == 0); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = informations de correspondance à consulter. * +* index = indice de la correspondance visée. * +* start = position de départ d'un motif détecté. [OUT] * +* end = position d'arrivée d'un motif détecté. [OUT] * +* * +* Description : Indique la localisation d'une correspondance établie. * +* * +* Retour : Taille mesurée de la correspondance. * +* * +* Remarques : - * +* * +******************************************************************************/ + +phys_t g_scan_bytes_matches_get_location(const GScanBytesMatches *matches, size_t index, phys_t *start, phys_t *end) +{ + phys_t result; /* Taille à retourner */ + + result = 0; + + /* + result = match->len; + + *start = match->start; + *end = match->start + result; + */ + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = informations de correspondance à consulter. * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison gagnante. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_bytes_matches_get_modifier_path(const GScanBytesMatches *matches) +{ + char *result; /* Combinaison à retourner */ + GBytesToken *pattern; /* Autre version du motif */ + + result = NULL; + + /* + + if (match->has_mod_path) + { + pattern = G_BYTES_TOKEN(G_SCAN_MATCH(match)->source); + result = g_bytes_token_get_modifier_path(pattern, match->mod_path_index); + } + + else + result = NULL; + */ + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à consulter. * +* * +* Description : Dénombre les correspondances enregistrées pour un motif. * +* * +* Retour : Quantité de correspondances établies. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static size_t g_scan_bytes_matches_count(const GScanBytesMatches *matches) +{ + size_t result; /* Quantité à retourner */ + + result = matches->count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à manipuler. * +* fd = canal d'écriture. * +* * +* Description : Affiche une correspondance au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_bytes_matches_output_to_text(const GScanBytesMatches *matches, int fd) +{ + GScanMatches *base; /* Lien vers les infos de base */ + GBinContent *content; /* Contenu binaire analysé */ + const char *name; /* Désignation du motif ciblé */ + match_area_t *iter; /* Boucle de parcours #1 */ + char value[2 + ULLONG_MAXLEN]; /* Impression de la position */ + int ret; /* Bilan d'une conversion */ + vmpa2t pos; /* Tête de lecture */ + phys_t len; /* Taille d'une correspondance */ + const bin_t *data; /* Accès aux données brutes */ + phys_t k; /* Boucle de parcours #2 */ + + base = G_SCAN_MATCHES(matches); + + content = g_scan_context_get_content(base->context); + + name = g_search_pattern_get_name(base->source); + + for_each_match_area(iter, matches->areas) + { + /* Position dans le binaire (hexadécimal) */ + + ret = snprintf(value, ULLONG_MAXLEN, "0x%llx", (unsigned long long)iter->start); + + if (ret > 0) + write(fd, value, ret); + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting offset to hex!"); + write(fd, "\"<error>\"", 9); + } + + write(fd, ":", 1); + + /* Affichage de la désignation */ + + write(fd, "$", 1); + + /** + * Les fonctionnalités Yara d'origine autorisent les variables anonymes '$'. + * + * Cette absence de nom est supportée ici. + */ + + if (name != NULL) + write(fd, name, strlen(name)); + + write(fd, ": ", 2); + + /* Affichage du contenu */ + + init_vmpa(&pos, iter->start, VMPA_NO_VIRTUAL); + + len = iter->end - iter->start; + + data = g_binary_content_get_raw_access(content, &pos, len); + assert(data != NULL); + + for (k = 0; k < len; k++) + { + if (isprint(data[k])) + write(fd, &data[k], 1); + + else + { + write(fd, "\\x", 2); + + ret = snprintf(value, ULLONG_MAXLEN, "%02hhx", data[k]); + + if (ret > 0) + { + assert(ret == 2); + write(fd, value, ret); + } + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting data!"); + write(fd, "??", 2); + } + + } + + } + + write(fd, "\n", 1); + + } + + g_object_unref(G_OBJECT(content)); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = définition de correspondance à manipuler. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* * +* Description : Affiche une correspondance au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_bytes_matches_output_to_json(const GScanBytesMatches *matches, const sized_string_t *padding, unsigned int level, int fd) +{ + unsigned int i; /* Boucle de parcours #1 */ + char value[4 + ULLONG_MAXLEN]; /* Impression de la position */ + int ret; /* Bilan d'une conversion */ + GScanMatches *base; /* Lien vers les infos de base */ + GBinContent *content; /* Contenu binaire analysé */ + match_area_t *iter; /* Boucle de parcours #1 */ + vmpa2t pos; /* Tête de lecture */ + phys_t len; /* Taille d'une correspondance */ + const bin_t *data; /* Accès aux données brutes */ + phys_t k; /* Boucle de parcours #2 */ + + /* Nombre de correspondances */ + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + write(fd, "\"match_count\": ", 15); + + ret = snprintf(value, ULLONG_MAXLEN, "%zu", matches->count); + + if (ret > 0) + write(fd, value, ret); + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting value!"); + write(fd, "null", 4); + } + + write(fd, ",\n", 2); + + /* Détail des correspondances */ + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + write(fd, "\"matches\": [\n", 13); + + base = G_SCAN_MATCHES(matches); + + content = g_scan_context_get_content(base->context); + + for_each_match_area(iter, matches->areas) + { + /* Marqueur de début */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "{\n", 2); + + /* Position dans le binaire (décimal) */ + + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"offset\": ", 10); + + ret = snprintf(value, ULLONG_MAXLEN, "%llu", (unsigned long long)iter->start); + + if (ret > 0) + write(fd, value, ret); + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting offset!"); + write(fd, "null", 4); + } + + write(fd, ",\n", 2); + + /* Position dans le binaire (hexadécimal) */ + + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"offset_hex\": ", 14); + + ret = snprintf(value, ULLONG_MAXLEN, "\"0x%llx\"", (unsigned long long)iter->start); + + if (ret > 0) + write(fd, value, ret); + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting offset to hex!"); + write(fd, "null", 4); + } + + write(fd, ",\n", 2); + + /* Affichage du contenu brut */ + + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"content\": \"", 12); + + init_vmpa(&pos, iter->start, VMPA_NO_VIRTUAL); + + len = iter->end - iter->start; + + data = g_binary_content_get_raw_access(content, &pos, len); + assert(data != NULL); + + for (k = 0; k < len; k++) + { + if (data[k] == '\\') + write(fd, "\\\\", 2); + + else if (isprint(data[k])) + write(fd, &data[k], 1); + + else + { + write(fd, "\\u", 2); + + /** + * Cf. https://datatracker.ietf.org/doc/html/rfc8259#section-7 + */ + ret = snprintf(value, ULLONG_MAXLEN, "%04hhx", data[k]); + + if (ret > 0) + { + assert(ret == 4); + write(fd, value, ret); + } + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting data!"); + write(fd, "??", 2); + } + + } + + } + + write(fd, "\",\n", 3); + + /* Affichage du contenu en version humainement lisible */ + + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"content_str\": \"", 16); + + init_vmpa(&pos, iter->start, VMPA_NO_VIRTUAL); + + data = g_binary_content_get_raw_access(content, &pos, len); + assert(data != NULL); + + for (k = 0; k < len; k++) + { + if (data[k] == '\\') + write(fd, "\\\\", 2); + + else if (isprint(data[k])) + write(fd, &data[k], 1); + + else + { + write(fd, "\\\\x", 3); + + ret = snprintf(value, ULLONG_MAXLEN, "%02hhx", data[k]); + + if (ret > 0) + { + assert(ret == 2); + write(fd, value, ret); + } + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting data!"); + write(fd, "??", 2); + } + + } + + } + + write(fd, "\",\n", 3); + + /* Affichage du contenu brut */ + + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"length\": ", 10); + + ret = snprintf(value, ULLONG_MAXLEN, "%llu", (unsigned long long)len); + + if (ret > 0) + write(fd, value, ret); + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting data!"); + write(fd, "-1", 2); + } + + write(fd, ",\n", 2); + + /* Affichage du contenu brut (hexadécimal) */ + + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"length_hex\": ", 14); + + ret = snprintf(value, ULLONG_MAXLEN, "\"0x%llx\"", (unsigned long long)len); + + if (ret > 0) + write(fd, value, ret); + + else + { + log_simple_message(LMT_EXT_ERROR, "Error while converting data!"); + write(fd, "\"0xffffffffffffffff\"", 20); + } + + write(fd, "\n", 1); + + /* Marqueur de fin */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + if (is_last_match_area(iter, matches->areas)) + write(fd, "}\n", 2); + else + write(fd, "},\n", 3); + + } + + g_object_unref(G_OBJECT(content)); + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + write(fd, "]\n", 2); + +} diff --git a/src/analysis/scan/matches/bytes.h b/src/analysis/scan/matches/bytes.h new file mode 100644 index 0000000..90d6062 --- /dev/null +++ b/src/analysis/scan/matches/bytes.h @@ -0,0 +1,75 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * bytes.h - prototypes pour la sauvegarde de correspondances avec des suites d'octets identifiées + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MATCHES_BYTES_H +#define _ANALYSIS_SCAN_MATCHES_BYTES_H + + +#include <glib-object.h> + + +#include "area.h" +#include "../context.h" +#include "../matches.h" + + + +/* -------------------- CONSERVATION DE CORRESPONDANCES ETABLIES -------------------- */ + + +#define G_TYPE_SCAN_BYTES_MATCHES g_scan_bytes_matches_get_type() +#define G_SCAN_BYTES_MATCHES(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_BYTES_MATCHES, GScanBytesMatches)) +#define G_IS_SCAN_BYTES_MATCHES(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_BYTES_MATCHES)) +#define G_SCAN_BYTES_MATCHES_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_BYTES_MATCHES, GScanBytesMatchesClass)) +#define G_IS_SCAN_BYTES_MATCHES_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_BYTES_MATCHES)) +#define G_SCAN_BYTES_MATCHES_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_BYTES_MATCHES, GScanBytesMatchesClass)) + + +/* Correspondances trouvées avec des suite d'octets (instance) */ +typedef struct _GScanBytesMatches GScanBytesMatches; + +/* Correspondances trouvées avec des suite d'octets (classe) */ +typedef struct _GScanBytesMatchesClass GScanBytesMatchesClass; + + +/* Indique le type défini pour une série de correspondances d'octets identifiées. */ +GType g_scan_bytes_matches_get_type(void); + +/* Crée un suivi pour série de correspondances avec des octets. */ +GScanMatches *g_scan_bytes_matches_new(void); + +/* Intègre une liste de correspondances vérifiées. */ +void g_scan_bytes_matches_set_list(GScanBytesMatches *, match_area_t *, size_t); + +/* Fournit les informations relatives à une correspondance. */ +const match_area_t *g_scan_bytes_matches_get(const GScanBytesMatches *, size_t); + +/* Indique la localisation d'une correspondance établie. */ +phys_t g_scan_bytes_matches_get_location(const GScanBytesMatches *, size_t, phys_t *, phys_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +char *g_scan_bytes_matches_get_modifier_path(const GScanBytesMatches *); + + + +#endif /* _ANALYSIS_SCAN_MATCHES_BYTES_H */ diff --git a/src/analysis/scan/matches/pending.c b/src/analysis/scan/matches/pending.c new file mode 100644 index 0000000..c653257 --- /dev/null +++ b/src/analysis/scan/matches/pending.c @@ -0,0 +1,677 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pending.c - consolidation de correspondances partielles + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "pending.h" + + +#include <malloc.h> +#include <stdlib.h> +#include <string.h> + + +#include "../../../common/sort.h" + + + + + +/* ------------------------- MEMORISATION D'UNE ZONE BORNEE ------------------------- */ + + +/* Compare deux couvertures bornées de correspondances. */ +static int compare_match_area(const match_area_t *, const match_area_t *); + + + +/* -------------------- CONSERVATION DE CORRESPONDANCES ETABLIES -------------------- */ + + +#define PENDING_ALLOC_SIZE 10 + + + + + +/* ---------------------------------------------------------------------------------- */ +/* MEMORISATION D'UNE ZONE BORNEE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : allocator = allocateur dédié à l'ensemble de zones. * +* start = point de départ d'une nouvelle correspondance. * +* length = taille de la zone couverte. * +* * +* Description : Crée une nouvelle structure de suivi de correspondance. * +* * +* Retour : Structure initialisée mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static match_area_t *create_match_area(GUMemCache *allocator, phys_t start, phys_t length) +{ + match_area_t *result; /* Zone à retourner */ + + result = g_umem_cache_alloc(allocator); + + DL_LIST_ITEM_INIT(&result->link); + + result->start = start; + result->end = start + length; + + assert(matches->content_start <= result->start); + assert(result->end <= matches->content_end); + + result->ttl = 1; + + result->has_mod_path = false; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : allocator = allocateur dédié à l'ensemble de zones. * +* start = point de départ d'une nouvelle correspondance. * +* length = taille de la zone couverte. * +* index = indice de construction pour le motif concerné. * +* * +* Description : Crée une nouvelle structure de suivi de correspondance. * +* * +* Retour : Structure initialisée mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static match_area_t *create_match_area_with_path(GUMemCache *allocator, phys_t start, phys_t length, size_t index) +{ + match_area_t *result; /* Zone à retourner */ + + result = g_umem_cache_alloc(allocator); + + DL_LIST_ITEM_INIT(&result->link); + + result->start = start; + result->end = start + length; + + assert(matches->content_start <= result->start); + assert(result->end <= matches->content_end); + + result->ttl = 1; + + result->mod_path_index = index; + result->has_mod_path = true; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : area = zone de suivi à supprimer. * +* allocator = allocateur dédié à l'ensemble de zones. * +* * +* Description : Supprime une structure de suivi de correspondance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void delete_match_area(match_area_t *area, GUMemCache *allocator) +{ + // TODO : assert(alone) + + g_umem_cache_free(allocator, area); + +} + + +/****************************************************************************** +* * +* Paramètres : a = pointeur vers la première zone à analyser. * +* b = pointeur vers la seconde zone à analyser. * +* * +* Description : Compare deux couvertures bornées de correspondances. * +* * +* Retour : Bilan de la comparaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static int compare_match_area(const match_area_t *a, const match_area_t *b) +{ + int result; /* Bilan à renvoyer */ + + result = sort_unsigned_long_long(a->start, b->start); + + if (result == 0) + result = sort_unsigned_long_long(a->end, b->end); + + if (result == 0) + result = sort_unsigned_long_long(a->ttl, b->ttl); + + if (result == 0) + result = sort_unsigned_long_long(a->has_mod_path, b->has_mod_path); + + if (result == 0) + result = sort_unsigned_long_long(a->mod_path_index, b->mod_path_index); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* CONSERVATION DE CORRESPONDANCES ETABLIES */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à initialiser. * +* start = première position du contenu (souvent 0). * +* end = position de fin du contenu. * +* * +* Description : Initialise une structure de consolidation de correspondances.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void init_pending_matches(pending_matches_t *matches, const phys_t *start, const phys_t *end) +{ + matches->content_start = *start; + matches->content_end = *end; + + matches->allocator = NULL; + matches->areas = NULL; + matches->allocated = 0; + matches->used = 0; + + matches->initialized = false; + + matches->abort = false; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = suivi de correspondances à initialiser. [OUT] * +* src = suivi de correspondances à copier. * +* * +* Description : Copie une structure de consolidation de correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void copy_pending_matches(pending_matches_t *dest, const pending_matches_t *src) +{ + dest->content_start = src->content_start; + dest->content_end = src->content_end; + + dest->areas = malloc(src->used * sizeof(match_area_t)); + dest->allocated = src->used; + dest->used = src->used; + + memcpy(dest->areas, src->areas, src->used * sizeof(match_area_t)); + + dest->initialized = src->initialized; + + dest->abort = src->abort; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = suivi de correspondances à initialiser. [OUT] * +* src = suivi de correspondances à copier. * +* * +* Description : Fusionne une structure de consolidation avec une autre. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void merge_pending_matches(pending_matches_t *dest, const pending_matches_t *src) +{ + if ((dest->used + src->used) > dest->allocated) + { + dest->allocated += src->used; + + dest->areas = realloc(dest->areas, dest->allocated * sizeof(match_area_t)); + + } + + memcpy(&dest->areas[dest->used], src->areas, src->used * sizeof(match_area_t)); + + dest->used += src->used; + + dest->initialized |= src->initialized; + + dest->abort |= src->abort; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à purger. * +* * +* Description : Libère la mémoire utilisée par une consolidation. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void exit_pending_matches(pending_matches_t *matches) +{ + if (matches->areas != NULL) + free(matches->areas); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à consulter. * +* * +* Description : Dénombre les correspondances établies jusque là. * +* * +* Retour : Quantité de correspondances complètes jusqu'à présent. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t count_pending_matches(const pending_matches_t *matches) +{ + size_t result; /* Quantité à renvoyer */ + + result = matches->used; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à consulter. * +* count = nombre de correspondances en attente. [OUT] * +* * +* Description : Fournit la liste des correspondances établies à présent. * +* * +* Retour : Liste de correspondances en lecture seule. * +* * +* Remarques : - * +* * +******************************************************************************/ + +match_area_t * const *get_all_pending_matches(const pending_matches_t *matches, size_t *count) +{ + match_area_t * const *result; /* Série à renvoyer */ + + result = &matches->areas; + + *count = matches->used; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à compléter. * +* start = point de départ d'une nouvelle correspondance. * +* length = taille de la zone couverte. * +* * +* Description : Ajoute au suivi la définition d'une nouvelle correspondance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void add_pending_match(pending_matches_t *matches, phys_t start, phys_t length) +{ + match_area_t *area; /* Nouvelle zone à intégrer */ + + area = create_match_area(matches->allocator, start, length); + + dl_list_add_tail(area, &matches->areas, match_area_t, link); + matches->used++; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à compléter. * +* start = point de départ d'une nouvelle correspondance. * +* length = taille de la zone couverte. * +* index = indice de construction pour le motif concerné. * +* * +* Description : Ajoute au suivi la définition d'une nouvelle correspondance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void add_pending_match_with_path(pending_matches_t *matches, phys_t start, phys_t length, size_t index) +{ + match_area_t *area; /* Nouvelle zone à intégrer */ + + area = create_match_area_with_path(matches->allocator, start, length, index); + + dl_list_add_tail(area, &matches->areas, match_area_t, link); + matches->used++; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à compléter. * +* target = indice de la zone de correspondance concernée. * +* start = nouvelle position initiale de la zone couverte. * +* * +* Description : Etend une zone couverte dans le suivi des correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void extend_pending_match_beginning(pending_matches_t *matches, size_t target, phys_t start) +{ + match_area_t *area; /* Zone à actualiser */ + + assert(target < matches->used); + + area = &matches->areas[target]; + + if (area->ttl == 0) + { + assert(matches->content_start <= start); + + area->start = start; + + area->ttl = 1; + + } + else + { + assert(area->ttl == 1); + + add_pending_match(matches, start, area->end - start); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à compléter. * +* target = indice de la zone de correspondance concernée. * +* length = taille de la zone couverte supplémentaire. * +* * +* Description : Etend une zone couverte dans le suivi des correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void extend_pending_match_ending(pending_matches_t *matches, size_t target, phys_t end) +{ + match_area_t *area; /* Zone à actualiser */ + + assert(target < matches->used); + + area = &matches->areas[target]; + + if (area->ttl == 0) + { + assert(end <= matches->content_end); + + area->end = end; + + area->ttl = 1; + + } + else + { + assert(area->ttl == 1); + + add_pending_match(matches, area->start, end - area->start); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à modifier. * +* * +* Description : Réinitialisation à 0 tous les TTL de correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void reset_pending_matches_ttl(pending_matches_t *matches) +{ + size_t i; /* Boucle de parcours */ + + assert(matches->initialized); + + for (i = 0; i < matches->used; i++) + matches->areas[i].ttl = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à modifier. * +* * +* Description : Retire toutes les correspondances sans issue pour l'analyse. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void purge_pending_matches(pending_matches_t *matches) +{ + match_area_t *del_start; /* Départ d'une zone morte */ + match_area_t *del_end; /* Fin d'une zone morte */ + size_t del_remaining; /* Nombre de valides ensuite */ + size_t del_count; /* Nombre d'éléments à effacer */ + size_t i; /* Boucle de parcours */ + + assert(matches->initialized); + + /** + * Note : le code original était le suivant : + * + + * for (i = matches->used; i > 0; i--) + * if (matches->areas[i - 1].ttl == 0) + * { + * memmove(&matches->areas[i - 1], &matches->areas[i], (matches->used - i) * sizeof(match_area_t)); + * matches->used--; + * } + * + * Pour éviter les appels à memmove(), un déplacement par blocs est désormais visée. + */ + + del_start = NULL; + del_end = NULL; + del_count = 0; + del_remaining = 0; + + /* Suppression en bloc si possible */ + + for (i = matches->used; i > 0; i--) + { + if (matches->areas[i - 1].ttl == 0) + { + del_start = &matches->areas[i - 1]; + + if (del_end == NULL) + { + del_end = del_start; + del_remaining = matches->used - i; + } + + del_count++; + + } + else + { + if (del_start != NULL) + { + assert(&matches->areas[i] == del_start); + + if (del_remaining > 0) + memmove(del_start, del_end + 1, del_remaining * sizeof(match_area_t)); + + assert(matches->used > del_count); + matches->used -= del_count; + + del_start = NULL; + del_end = NULL; + del_count = 0; + del_remaining = 0; + + } + + } + + } + + /* Dernier traitement au besoin */ + + if (del_start != NULL) + { + assert(&matches->areas[0] == del_start); + + if (del_remaining > 0) + memmove(del_start, del_end + 1, del_remaining * sizeof(match_area_t)); + + assert(matches->used >= del_count); + matches->used -= del_count; + + } + + /* Bilan */ + + matches->abort = (matches->used == 0); + +} + + +/****************************************************************************** +* * +* Paramètres : matches = suivi de correspondances à finaliser. * +* * +* Description : Trie les correspondances et retire tous les doublons. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void sort_and_filter_pending_matches(pending_matches_t *matches) +{ + match_area_t *last; /* Dernière zone conservée */ + size_t i; /* Boucle de parcours */ + match_area_t *cur; /* Zone courante dans l'analyse*/ + + if (matches->used > 0) + { + qsort(matches->areas, matches->used, sizeof(match_area_t), (__compar_fn_t)compare_match_area); + + last = &matches->areas[0]; + + for (i = 1; i < matches->used; i++) + { + cur = &matches->areas[i]; + + if (last->start != cur->start || last->end != cur->end) + { + if ((cur - last) > 1) + { + memmove(last + 1, cur, (matches->used - i) * sizeof(match_area_t)); + matches->used -= (cur - last + 1); + } + + last = cur; + + } + + } + + cur = &matches->areas[matches->used - 1]; + + if (last != cur) + matches->used = last - matches->areas + 1; + + } + +} diff --git a/src/analysis/scan/matches/pending.h b/src/analysis/scan/matches/pending.h new file mode 100644 index 0000000..e430ca1 --- /dev/null +++ b/src/analysis/scan/matches/pending.h @@ -0,0 +1,129 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pending.h - prototypes pour la consolidation de correspondances partielles + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#if 0 //ndef _ANALYSIS_SCAN_MATCHES_PENDING_H +#define _ANALYSIS_SCAN_MATCHES_PENDING_H + + +#include <assert.h> +#include <stdbool.h> + + +#include "../../content.h" +#include "../../../common/dllist.h" + + + +// TODO : move vers ByteMatch +typedef int GUMemCache; + + + +/* Couverture d'une correspondance */ +typedef struct _match_area_t +{ + DL_LIST_ITEM(link); /* Lien vers les maillons */ + + phys_t start; /* Point de départ */ + phys_t end; /* Point d'arrivée (exclus) */ + + unsigned long ttl; /* Durée de vie pour analyse */ + + size_t mod_path_index; /* Indice de construction */ + bool has_mod_path; /* Validité du champ précédent */ + +} match_area_t; + +/* Suivi de correspondances */ +typedef struct _pending_matches_t +{ + phys_t content_start; /* Point de début du contenu */ + phys_t content_end; /* Point de fin du contenu */ + + GUMemCache *allocator; /* Allocateur pour zones */ + match_area_t *areas; /* Zones couvertes */ + size_t allocated; /* Nombre d'allocations */ + size_t used; /* Nombre de zones */ + + bool initialized; /* Etat du suivi */ + + bool abort; /* Inutilité d'une poursuite */ + +} pending_matches_t; + + +/* Initialise une structure de consolidation de correspondances. */ +void init_pending_matches(pending_matches_t *, const phys_t *, const phys_t *); + +/* Copie une structure de consolidation de correspondances. */ +void copy_pending_matches(pending_matches_t *, const pending_matches_t *); + +/* Fusionner une structure de consolidation avec une autre. */ +void merge_pending_matches(pending_matches_t *, const pending_matches_t *); + +/* Libère la mémoire utilisée par une consolidation. */ +void exit_pending_matches(pending_matches_t *); + +// TODO ajouter un assert(used == 0) si !initialized */ +#define are_pending_matches_initialized(pm) pm->initialized + +#define set_pending_matches_initialized(pm) pm->initialized = true + +/* Dénombre les correspondances établies jusque là. */ +size_t count_pending_matches(const pending_matches_t *); + +/* Fournit la liste des correspondances établies à présent. */ +match_area_t * const *get_all_pending_matches(const pending_matches_t *, size_t *); + +/* Ajoute au suivi la définition d'une nouvelle correspondance. */ +void add_pending_match(pending_matches_t *, phys_t, phys_t); + +/* Ajoute au suivi la définition d'une nouvelle correspondance. */ +void add_pending_match_with_path(pending_matches_t *, phys_t, phys_t, size_t); + +/* Etend une zone couverte dans le suivi des correspondances. */ +void extend_pending_match_beginning(pending_matches_t *, size_t, phys_t); + +/* Etend une zone couverte dans le suivi des correspondances. */ +void extend_pending_match_ending(pending_matches_t *, size_t, phys_t); + +/* Réinitialisation à 0 tous les TTL de correspondances. */ +void reset_pending_matches_ttl(pending_matches_t *); + +#define keep_pending_match(p) \ + do \ + { \ + assert(p->ttl == 0); \ + p->ttl = 1; \ + } \ + while (0); + +/* Retire toutes les correspondances sans issue pour l'analyse. */ +void purge_pending_matches(pending_matches_t *); + +/* Trie les correspondances et retire tous les doublons. */ +void sort_and_filter_pending_matches(pending_matches_t *); + + + +#endif /* _ANALYSIS_SCAN_MATCHES_PENDING_H */ diff --git a/src/analysis/scan/options-int.h b/src/analysis/scan/options-int.h new file mode 100644 index 0000000..975fb6c --- /dev/null +++ b/src/analysis/scan/options-int.h @@ -0,0 +1,60 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * options-int.h - prototypes internes pour le rassemblement des options d'analyse communiquées par le donneur d'ordre + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_OPTIONS_INT_H +#define _ANALYSIS_SCAN_OPTIONS_INT_H + + +#include "options.h" + + + +/* Rassemblement d'options d'analyses (instance) */ +struct _GScanOptions +{ + GObject parent; /* A laisser en premier */ + + GType data_backend; /* Choix du moteur d'analyse */ + + bool check_only; /* Qu'une validation syntaxique*/ + + bool print_json; /* Sortie au format json ? */ + bool print_strings; /* Affichage de correspondances*/ + bool print_stats; /* Affichage de statistiques ? */ + bool print_tags; /* Affichage des étiquttes ? */ + + char **selected_tags; /* Etiquettes sélectionnées */ + size_t selected_count; /* Nombre de ces étiquettes */ + +}; + +/* Rassemblement d'options d'analyses (classe) */ +struct _GScanOptionsClass +{ + GObjectClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_OPTIONS_INT_H */ diff --git a/src/analysis/scan/options.c b/src/analysis/scan/options.c new file mode 100644 index 0000000..ecff9f1 --- /dev/null +++ b/src/analysis/scan/options.c @@ -0,0 +1,490 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * options.c - rassemblement des options d'analyse communiquées par le donneur d'ordre + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "options.h" + + +#include <malloc.h> +#include <string.h> + + +#include "options-int.h" + + + +/* Initialise la classe des ensembles d'options d'analyses. */ +static void g_scan_options_class_init(GScanOptionsClass *); + +/* Initialise une instance de groupe d'options d'analyse. */ +static void g_scan_options_init(GScanOptions *); + +/* Supprime toutes les références externes. */ +static void g_scan_options_dispose(GScanOptions *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_options_finalize(GScanOptions *); + + + +/* Indique le type défini pour un ensemble d'options d'analyses. */ +G_DEFINE_TYPE(GScanOptions, g_scan_options, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des ensembles d'options d'analyses. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_options_class_init(GScanOptionsClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_options_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_options_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : options = instance à initialiser. * +* * +* Description : Initialise une instance de groupe d'options d'analyse. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_options_init(GScanOptions *options) +{ + options->data_backend = G_TYPE_INVALID; + + options->check_only = false; + + options->print_json = false; + options->print_strings = false; + options->print_stats = false; + + options->selected_tags = NULL; + options->selected_count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : options = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_options_dispose(GScanOptions *options) +{ + G_OBJECT_CLASS(g_scan_options_parent_class)->dispose(G_OBJECT(options)); + +} + + +/****************************************************************************** +* * +* Paramètres : options = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_options_finalize(GScanOptions *options) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < options->selected_count; i++) + free(options->selected_tags[i]); + + if (options->selected_tags != NULL) + free(options->selected_tags); + + G_OBJECT_CLASS(g_scan_options_parent_class)->finalize(G_OBJECT(options)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée un réceptacle pour diverses options d'analyse. * +* * +* Retour : Point de collecte mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanOptions *g_scan_options_new(void) +{ + GScanOptions *result; /* Instance à retourner */ + + result = g_object_new(G_TYPE_SCAN_OPTIONS, NULL); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à consulter. * +* * +* Description : Indique le type d'un moteur d'analyse de données sélectionné.* +* * +* Retour : Type d'objet, idéalement valide. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GType g_scan_options_get_backend_for_data(const GScanOptions *options) +{ + GType result; /* Type à retourner */ + + result = options->data_backend; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à modifier. * +* backend = type du moteur sélectionné. * +* * +* Description : Sélectionne un type de moteur d'analyse pour données brutes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_set_backend_for_data(GScanOptions *options, GType backend) +{ + options->data_backend = backend; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à consulter. * +* * +* Description : Indique un besoin limité à une validation syntaxique. * +* * +* Retour : Etat de l'option visée à conservé. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_options_get_check_only(const GScanOptions *options) +{ + bool result; /* Statut à retourner */ + + result = options->check_only; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à modifier. * +* state = état de l'option visée à conserver. * +* * +* Description : Mémorise un besoin de validation syntaxique uniquement. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_set_check_only(GScanOptions *options, bool state) +{ + options->check_only = state; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à consulter. * +* * +* Description : Impose le format JSON comme type de sortie. * +* * +* Retour : Etat de l'option visée à conservé. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_options_get_print_json(const GScanOptions *options) +{ + bool result; /* Statut à retourner */ + + result = options->print_json; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à modifier. * +* state = état de l'option visée à conserver. * +* * +* Description : Mémorise le format JSON comme type de sortie. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_set_print_json(GScanOptions *options, bool state) +{ + options->print_json = state; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à consulter. * +* * +* Description : Indique un besoin d'affichage des correspondances finales. * +* * +* Retour : Etat de l'option visée à conservé. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_options_get_print_strings(const GScanOptions *options) +{ + bool result; /* Statut à retourner */ + + result = options->print_strings; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à modifier. * +* state = état de l'option visée à conserver. * +* * +* Description : Mémorise un besoin d'affichage des correspondances finales. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_set_print_strings(GScanOptions *options, bool state) +{ + options->print_strings = state; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à consulter. * +* * +* Description : Indique un besoin de statistiques en fin de compilation. * +* * +* Retour : Etat de l'option visée à conservé. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_options_get_print_stats(const GScanOptions *options) +{ + bool result; /* Statut à retourner */ + + result = options->print_stats; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à modifier. * +* state = état de l'option visée à conserver. * +* * +* Description : Mémorise un besoin de statistiques en fin de compilation. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_set_print_stats(GScanOptions *options, bool state) +{ + options->print_stats = state; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à consulter. * +* * +* Description : Indique un besoin d'affichage des étiquettes avec résultats. * +* * +* Retour : Etat de l'option visée à conservé. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_options_get_print_tags(const GScanOptions *options) +{ + bool result; /* Statut à retourner */ + + result = options->print_tags; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à modifier. * +* state = état de l'option visée à conserver. * +* * +* Description : Mémorise un besoin d'affichage des étiquettes avec résultats.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_set_print_tags(GScanOptions *options, bool state) +{ + options->print_tags = state; + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à compléter. * +* tag = étiquette de règle à sélectionner. * +* * +* Description : Inscrit une étiquette comme sélection de règles à afficher. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_options_select_tag(GScanOptions *options, const char *tag) +{ + options->selected_tags = realloc(options->selected_tags, ++options->selected_count * sizeof(char *)); + + options->selected_tags[options->selected_count - 1] = strdup(tag); + +} + + +/****************************************************************************** +* * +* Paramètres : options = ensemble d'options d'analyses à compléter. * +* tag = étiquette de règle à auditionner. * +* * +* Description : Détermine si une étiquette donnée conduit à un affichage. * +* * +* Retour : true si une règle portant l'étiquette doit être affichée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_options_has_tag_as_selected(const GScanOptions *options, const char *tag) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + + if (tag == NULL) + result = (options->selected_count == 0); + + else + { + result = false; + + for (i = 0; i < options->selected_count; i++) + if (strcmp(options->selected_tags[i], tag) == 0) + { + result = true; + break; + } + + } + + return result; + +} diff --git a/src/analysis/scan/options.h b/src/analysis/scan/options.h new file mode 100644 index 0000000..059c57e --- /dev/null +++ b/src/analysis/scan/options.h @@ -0,0 +1,98 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * options.h - prototypes pour le rassemblement des options d'analyse communiquées par le donneur d'ordre + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_OPTIONS_H +#define _ANALYSIS_SCAN_OPTIONS_H + + +#include <glib-object.h> +#include <stdbool.h> + + + +#define G_TYPE_SCAN_OPTIONS g_scan_options_get_type() +#define G_SCAN_OPTIONS(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_OPTIONS, GScanOptions)) +#define G_IS_SCAN_OPTIONS(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_OPTIONS)) +#define G_SCAN_OPTIONS_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_OPTIONS, GScanOptionsClass)) +#define G_IS_SCAN_OPTIONS_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_OPTIONS)) +#define G_SCAN_OPTIONS_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_OPTIONS, GScanOptionsClass)) + + +/* Rassemblement d'options d'analyses (instance) */ +typedef struct _GScanOptions GScanOptions; + +/* Rassemblement d'options d'analyses (classe) */ +typedef struct _GScanOptionsClass GScanOptionsClass; + + +/* Indique le type défini pour un ensemble d'options d'analyses. */ +GType g_scan_options_get_type(void); + +/* Crée un réceptacle pour diverses options d'analyse. */ +GScanOptions *g_scan_options_new(void); + +/* Indique le type d'un moteur d'analyse de données sélectionné. */ +GType g_scan_options_get_backend_for_data(const GScanOptions *); + +/* Sélectionne un type de moteur d'analyse pour données brutes. */ +void g_scan_options_set_backend_for_data(GScanOptions *, GType); + +/* Indique un besoin limité à une validation syntaxique. */ +bool g_scan_options_get_check_only(const GScanOptions *); + +/* Mémorise un besoin de validation syntaxique uniquement. */ +void g_scan_options_set_check_only(GScanOptions *, bool); + +/* Impose le format JSON comme type de sortie. */ +bool g_scan_options_get_print_json(const GScanOptions *); + +/* Mémorise le format JSON comme type de sortie. */ +void g_scan_options_set_print_json(GScanOptions *, bool); + +/* Indique un besoin d'affichage des correspondances finales. */ +bool g_scan_options_get_print_strings(const GScanOptions *); + +/* Mémorise un besoin d'affichage des correspondances finales. */ +void g_scan_options_set_print_strings(GScanOptions *, bool); + +/* Indique un besoin de statistiques en fin de compilation. */ +bool g_scan_options_get_print_stats(const GScanOptions *); + +/* Mémorise un besoin de statistiques en fin de compilation. */ +void g_scan_options_set_print_stats(GScanOptions *, bool); + +/* Indique un besoin d'affichage des étiquettes avec résultats. */ +bool g_scan_options_get_print_tags(const GScanOptions *); + +/* Mémorise un besoin d'affichage des étiquettes avec résultats. */ +void g_scan_options_set_print_tags(GScanOptions *, bool); + +/* Inscrit une étiquette comme sélection de règles à afficher. */ +void g_scan_options_select_tag(GScanOptions *, const char *); + +/* Détermine si une étiquette donnée conduit à un affichage. */ +bool g_scan_options_has_tag_as_selected(const GScanOptions *, const char *); + + + +#endif /* _ANALYSIS_SCAN_OPTIONS_H */ diff --git a/src/analysis/scan/pattern-int.h b/src/analysis/scan/pattern-int.h new file mode 100644 index 0000000..b510c75 --- /dev/null +++ b/src/analysis/scan/pattern-int.h @@ -0,0 +1,63 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pattern-int.h - prototypes internes pour la définition de motif à rechercher + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERN_INT_H +#define _ANALYSIS_SCAN_PATTERN_INT_H + + +#include "pattern.h" + + +#include "context.h" + + + +/* Affiche un motif de recherche au format texte. */ +typedef void (* output_pattern_to_text_fc) (const GSearchPattern *, GScanContext *, int); + +/* Affiche un motif de recherche au format JSON. */ +typedef void (* output_pattern_to_json_fc) (const GSearchPattern *, GScanContext *, const sized_string_t *, unsigned int, int); + + +/* Motif à rechercher au sein d'un contenu (instance) */ +struct _GSearchPattern +{ + GObject parent; /* A laisser en premier */ + + char *name; /* Eventuelle désignation */ + +}; + +/* Motif à rechercher au sein d'un contenu (classe) */ +struct _GSearchPatternClass +{ + GObjectClass parent; /* A laisser en premier */ + + output_pattern_to_text_fc to_text; /* Impression au format texte */ + output_pattern_to_json_fc to_json; /* Impression au format JSON */ + +}; + + + +#endif /* _ANALYSIS_SCAN_PATTERN_INT_H */ diff --git a/src/analysis/scan/pattern.c b/src/analysis/scan/pattern.c new file mode 100644 index 0000000..dc4418c --- /dev/null +++ b/src/analysis/scan/pattern.c @@ -0,0 +1,425 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pattern.c - définition de motif à localiser dans du contenu binaire + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "pattern.h" + + +#include <malloc.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <sys/mman.h> +#include <sys/stat.h> + + +#include "pattern-int.h" +#include "../../core/logs.h" + + + +/* Initialise la classe des motifs à localiser dans du binaire. */ +static void g_search_pattern_class_init(GSearchPatternClass *); + +/* Initialise une instance de motif à localiser dans du binaire. */ +static void g_search_pattern_init(GSearchPattern *); + +/* Supprime toutes les références externes. */ +static void g_search_pattern_dispose(GSearchPattern *); + +/* Procède à la libération totale de la mémoire. */ +static void g_search_pattern_finalize(GSearchPattern *); + + + +/* Indique le type défini pour un motif à localiser. */ +G_DEFINE_TYPE(GSearchPattern, g_search_pattern, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des motifs à localiser dans du binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_search_pattern_class_init(GSearchPatternClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_search_pattern_dispose; + object->finalize = (GObjectFinalizeFunc)g_search_pattern_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = instance à initialiser. * +* * +* Description : Initialise une instance de motif à localiser dans du binaire.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_search_pattern_init(GSearchPattern *pattern) +{ + pattern->name = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_search_pattern_dispose(GSearchPattern *pattern) +{ + G_OBJECT_CLASS(g_search_pattern_parent_class)->dispose(G_OBJECT(pattern)); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_search_pattern_finalize(GSearchPattern *pattern) +{ + if (pattern->name != NULL) + free(pattern->name); + + G_OBJECT_CLASS(g_search_pattern_parent_class)->finalize(G_OBJECT(pattern)); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à consulter. * +* * +* Description : Fournit la désignation attribuée à un motif de recherche. * +* * +* Retour : Eventuelle étiquette associée ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char *g_search_pattern_get_name(const GSearchPattern *pattern) +{ + char *result; /* Désignation à retourner */ + + result = pattern->name; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à consulter. * +* name = désignation en tant que variable locale. * +* len = taille de cette désignation. * +* * +* Description : Inscrit la désignation attribuée à un motif de recherche. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_search_pattern_set_name(GSearchPattern *pattern, const char *name, size_t len) +{ + if (pattern->name != NULL) + free(pattern->name); + + if (name == NULL) + pattern->name = NULL; + else + pattern->name = strndup(name, len); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_search_pattern_output_to_text(const GSearchPattern *pattern, GScanContext *context, int fd) +{ + GSearchPatternClass *class; /* Classe à activer */ + + class = G_SEARCH_PATTERN_GET_CLASS(pattern); + + class->to_text(pattern, context, fd); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* * +* Description : Convertit un motif de recherche en texte. * +* * +* Retour : Données textuelles ou NULL en cas d'erreur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_search_pattern_convert_as_text(const GSearchPattern *pattern, GScanContext *context) +{ + char *result; /* Données à retourner */ + char *name; /* Nom "unique" pour le canal */ + int ret; /* Bilan de création de nom */ + int fd; /* Canal d'écriture */ + struct stat info; /* Infos. incluant une taille */ + ssize_t got; /* Données effectivement relues*/ + + static unsigned long long counter = 0; + + result = NULL; + + ret = asprintf(&name, "rost-pattern2text-%llu", counter++); + if (ret == -1) goto exit; + + fd = memfd_create(name, MFD_CLOEXEC); + if (fd == -1) + { + LOG_ERROR_N("memfd_create"); + goto exit_with_name; + } + + g_search_pattern_output_to_text(pattern, context, fd); + + ret = fstat(fd, &info); + if (ret != 0) + { + LOG_ERROR_N("fstat"); + goto exit_with_name_and_fd; + } + + result = malloc((info.st_size + 1) * sizeof(char)); + + lseek(fd, SEEK_SET, 0); + + got = read(fd, result, info.st_size); + if (got != info.st_size) + { + LOG_ERROR_N("read"); + free(result); + goto exit_with_name_and_fd; + } + + result[info.st_size] = '\0'; + + exit_with_name_and_fd: + + close(fd); + + exit_with_name: + + free(name); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* tail = décline la pose d'une virgule finale ? * +* * +* Description : Affiche un motif de recherche au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_search_pattern_output_to_json(const GSearchPattern *pattern, GScanContext *context, const sized_string_t *padding, unsigned int level, int fd, bool tail) +{ + unsigned int i; /* Boucle de parcours */ + GSearchPatternClass *class; /* Classe à activer */ + + /* Introduction */ + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + write(fd, "{\n", 2); + + /* Désignation du motif */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"name\": \"$", 10); + + write(fd, pattern->name, strlen(pattern->name)); + + write(fd, "\",\n", 3); + + /* Affichage du contenu */ + + class = G_SEARCH_PATTERN_GET_CLASS(pattern); + + class->to_json(pattern, context, padding, level, fd); + + /* Conclusion */ + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + if (tail) + write(fd, "}\n", 2); + else + write(fd, "},\n", 3); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* * +* Description : Convertit un motif de recherche en JSON. * +* * +* Retour : Données textuelles au format JSON ou NULL en cas d'erreur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_search_pattern_convert_as_json(const GSearchPattern *pattern, GScanContext *context) +{ + char *result; /* Données à retourner */ + char *name; /* Nom "unique" pour le canal */ + int ret; /* Bilan de création de nom */ + int fd; /* Canal d'écriture */ + sized_string_t padding; /* Bourrage pour le JSON */ + struct stat info; /* Infos. incluant une taille */ + ssize_t got; /* Données effectivement relues*/ + + static unsigned long long counter = 0; + + result = NULL; + + ret = asprintf(&name, "rost-pattern2json-%llu", counter++); + if (ret == -1) goto exit; + + fd = memfd_create(name, MFD_CLOEXEC); + if (fd == -1) + { + LOG_ERROR_N("memfd_create"); + goto exit_with_name; + } + + padding.data = " "; + padding.len = 3; + + g_search_pattern_output_to_json(pattern, context, &padding, 0, fd, false); + + ret = fstat(fd, &info); + if (ret != 0) + { + LOG_ERROR_N("fstat"); + goto exit_with_name_and_fd; + } + + result = malloc((info.st_size + 1) * sizeof(char)); + + lseek(fd, SEEK_SET, 0); + + got = read(fd, result, info.st_size); + if (got != info.st_size) + { + LOG_ERROR_N("read"); + free(result); + goto exit_with_name_and_fd; + } + + result[info.st_size] = '\0'; + + exit_with_name_and_fd: + + close(fd); + + exit_with_name: + + free(name); + + exit: + + return result; + +} diff --git a/src/analysis/scan/pattern.h b/src/analysis/scan/pattern.h new file mode 100644 index 0000000..72f87e4 --- /dev/null +++ b/src/analysis/scan/pattern.h @@ -0,0 +1,79 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pattern.h - prototypes pour la définition de motif à localiser dans du contenu binaire + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERN_H +#define _ANALYSIS_SCAN_PATTERN_H + + +#include <glib-object.h> + + +#include "../../arch/archbase.h" +#include "../../arch/vmpa.h" +#include "../../common/szstr.h" + + + +/* Depuis context.h: contexte de suivi d'une analyse en cours (instance) */ +typedef struct _GScanContext GScanContext; +; + +#define G_TYPE_SEARCH_PATTERN g_search_pattern_get_type() +#define G_SEARCH_PATTERN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SEARCH_PATTERN, GSearchPattern)) +#define G_IS_SEARCH_PATTERN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SEARCH_PATTERN)) +#define G_SEARCH_PATTERN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SEARCH_PATTERN, GSearchPatternClass)) +#define G_IS_SEARCH_PATTERN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SEARCH_PATTERN)) +#define G_SEARCH_PATTERN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SEARCH_PATTERN, GSearchPatternClass)) + + +/* Motif à rechercher au sein d'un contenu (instance) */ +typedef struct _GSearchPattern GSearchPattern; + +/* Motif à rechercher au sein d'un contenu (classe) */ +typedef struct _GSearchPatternClass GSearchPatternClass; + + +/* Indique le type défini pour un motif à localiser. */ +GType g_search_pattern_get_type(void); + +/* Fournit la désignation attribuée à un motif de recherche. */ +const char *g_search_pattern_get_name(const GSearchPattern *); + +/* Inscrit la désignation attribuée à un motif de recherche. */ +void g_search_pattern_set_name(GSearchPattern *, const char *, size_t); + +/* Affiche un motif de recherche au format texte. */ +void g_search_pattern_output_to_text(const GSearchPattern *, GScanContext *, int); + +/* Convertit un motif de recherche en texte. */ +char *g_search_pattern_convert_as_text(const GSearchPattern *, GScanContext *); + +/* Affiche un motif de recherche au format JSON. */ +void g_search_pattern_output_to_json(const GSearchPattern *, GScanContext *, const sized_string_t *, unsigned int, int, bool); + +/* Convertit un motif de recherche en JSON. */ +char *g_search_pattern_convert_as_json(const GSearchPattern *, GScanContext *); + + + +#endif /* _ANALYSIS_SCAN_PATTERN_H */ diff --git a/src/analysis/scan/patterns/Makefile.am b/src/analysis/scan/patterns/Makefile.am new file mode 100644 index 0000000..989a562 --- /dev/null +++ b/src/analysis/scan/patterns/Makefile.am @@ -0,0 +1,30 @@ + +noinst_LTLIBRARIES = libanalysisscanpatterns.la + + +libanalysisscanpatterns_la_SOURCES = \ + backend-int.h \ + backend.h backend.c \ + customizer-int.h \ + customizer.h customizer.c \ + modarg.h \ + modifier-int.h \ + modifier.h modifier.c \ + patid.h \ + token-int.h \ + token.h token.c + +libanalysisscanpatterns_la_LIBADD = \ + backends/libanalysisscanpatternsbackends.la \ + modifiers/libanalysisscanpatternsmodifiers.la \ + tokens/libanalysisscanpatternstokens.la + +libanalysisscanpatterns_la_CFLAGS = $(LIBGOBJ_CFLAGS) $(LIBPYTHON_INTERPRETER_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanpatterns_la_SOURCES:%c=) + + +SUBDIRS = backends modifiers tokens diff --git a/src/analysis/scan/patterns/backend-int.h b/src/analysis/scan/patterns/backend-int.h new file mode 100644 index 0000000..aeabe1b --- /dev/null +++ b/src/analysis/scan/patterns/backend-int.h @@ -0,0 +1,78 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * backend-int.h - prototypes internes pour une méthode de recherches au sein d'un contenu binaire + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKEND_INT_H +#define _ANALYSIS_SCAN_PATTERNS_BACKEND_INT_H + + +#include "backend.h" + + + +/* Indique la taille maximale des suites d'octets recherchées. */ +typedef size_t (* get_backend_atom_max_size_fc) (const GEngineBackend *); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +typedef patid_t (* enroll_plain_into_backend_fc) (GEngineBackend *, const uint8_t *, size_t, uint32_t [2]); + +/* Met en ordre les derniers détails avant un premier scan. */ +typedef bool (* warm_up_backend_fc) (GEngineBackend *); + +/* Récupère les identifiants finaux pour un motif recherché. */ +typedef patid_t (* build_backend_plain_pattern_id_fc) (const GEngineBackend *, const uint32_t [2]); + +/* Détermine le nombre d'identifiants constitués. */ +typedef size_t (* count_backend_plain_pattern_ids_fc) (const GEngineBackend *); + +/* Parcours un contenu binaire à la recherche de motifs. */ +typedef void (* run_backend_scan_fc) (const GEngineBackend *, GScanContext *); + +/* Imprime quelques faits quant aux éléments mis en place. */ +typedef void (* output_backend_stats_fc) (const GEngineBackend *); + + +/* Méthode de traitement d'un contenu binaire pour recherches (instance) */ +struct _GEngineBackend +{ + GObject parent; /* A laisser en premier */ + +}; + +/* Méthode de traitement d'un contenu binaire pour recherches (classe) */ +struct _GEngineBackendClass +{ + GObjectClass parent; /* A laisser en premier */ + + get_backend_atom_max_size_fc get_max_size; /* Taille maximale d'atome */ + enroll_plain_into_backend_fc enroll_plain; /* Inscription simpl e */ + warm_up_backend_fc warm_up; /* Préchauffage avant analyse */ + build_backend_plain_pattern_id_fc build_id; /* Définition d'identifiant*/ + count_backend_plain_pattern_ids_fc count_ids; /* Décompte des id. */ + run_backend_scan_fc run_scan; /* Lancement d'une analyse */ + output_backend_stats_fc output; /* Impression de statistiques */ + +}; + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKEND_INT_H */ diff --git a/src/analysis/scan/patterns/backend.c b/src/analysis/scan/patterns/backend.c new file mode 100644 index 0000000..a887600 --- /dev/null +++ b/src/analysis/scan/patterns/backend.c @@ -0,0 +1,311 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * backend.c - méthode de recherches au sein d'un contenu binaire + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "backend.h" + + +#include "backend-int.h" + + + +/* Initialise la classe des méthodes de recherche pour binaire. */ +static void g_engine_backend_class_init(GEngineBackendClass *); + +/* Initialise une instance de méthode de recherche pour binaire. */ +static void g_engine_backend_init(GEngineBackend *); + +/* Supprime toutes les références externes. */ +static void g_engine_backend_dispose(GEngineBackend *); + +/* Procède à la libération totale de la mémoire. */ +static void g_engine_backend_finalize(GEngineBackend *); + + + +/* Indique le type défini pour une méthode de recherche dans du binaire. */ +G_DEFINE_TYPE(GEngineBackend, g_engine_backend, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des méthodes de recherche pour binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_engine_backend_class_init(GEngineBackendClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_engine_backend_dispose; + object->finalize = (GObjectFinalizeFunc)g_engine_backend_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance à initialiser. * +* * +* Description : Initialise une instance de méthode de recherche pour binaire.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_engine_backend_init(GEngineBackend *backend) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_engine_backend_dispose(GEngineBackend *backend) +{ + G_OBJECT_CLASS(g_engine_backend_parent_class)->dispose(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_engine_backend_finalize(GEngineBackend *backend) +{ + G_OBJECT_CLASS(g_engine_backend_parent_class)->finalize(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Indique la taille maximale des suites d'octets recherchées. * +* * +* Retour : Valeur strictement positive. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_engine_backend_get_atom_max_size(const GEngineBackend *backend) +{ + size_t result; /* Taille à faire connaître */ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + result = class->get_max_size(backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* plain = chaîne de caractères classique à intégrer. * +* len = taille de cette chaîne. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Inscrit dans le moteur une chaîne de caractères à rechercher.* +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_engine_backend_enroll_plain_pattern(GEngineBackend *backend, const uint8_t *plain, size_t len, uint32_t tmp_id[2]) +{ + bool result; /* Bilan à retourner */ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + result = class->enroll_plain(backend, plain, len, tmp_id); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Met en ordre les derniers détails avant un premier scan. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_engine_backend_warm_up(GEngineBackend *backend) +{ + bool result; /* Bilan à retourner */ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + if (class->warm_up != NULL) + result = class->warm_up(backend); + else + result = true; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Récupère les identifiants finaux pour un motif recherché. * +* * +* Retour : Identifiant constitué ou INVALID_PATTERN_ID en cas d'échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +patid_t g_engine_backend_build_plain_pattern_id(const GEngineBackend *backend, const uint32_t tmp_id[2]) +{ + patid_t result; /* Identifiant à retourner */ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + result = class->build_id(backend, tmp_id); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* * +* Description : Détermine le nombre d'identifiants constitués. * +* * +* Retour : Quantité de gestionnaires de suivi à prévoir. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_engine_backend_count_plain_pattern_ids(const GEngineBackend *backend) +{ + size_t result; /* Quantité à retourner */ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + result = class->count_ids(backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_engine_backend_run_scan(const GEngineBackend *backend, GScanContext *context) +{ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + class->run_scan(backend, context); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Imprime quelques faits quant aux éléments mis en place. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_engine_backend_output_stats(const GEngineBackend *backend) +{ + GEngineBackendClass *class; /* Classe à activer */ + + class = G_ENGINE_BACKEND_GET_CLASS(backend); + + if (class->output != NULL) + class->output(backend); + +} diff --git a/src/analysis/scan/patterns/backend.h b/src/analysis/scan/patterns/backend.h new file mode 100644 index 0000000..3f9be03 --- /dev/null +++ b/src/analysis/scan/patterns/backend.h @@ -0,0 +1,79 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * backend.h - prototypes pour une méthode de recherches au sein d'un contenu binaire + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKEND_H +#define _ANALYSIS_SCAN_PATTERNS_BACKEND_H + + +#include <glib-object.h> +#include <stdbool.h> +#include <stdint.h> + + +#include "../context.h" +#include "../../content.h" + + + +#define G_TYPE_ENGINE_BACKEND g_engine_backend_get_type() +#define G_ENGINE_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_ENGINE_BACKEND, GEngineBackend)) +#define G_IS_ENGINE_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_ENGINE_BACKEND)) +#define G_ENGINE_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_ENGINE_BACKEND, GEngineBackendClass)) +#define G_IS_ENGINE_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_ENGINE_BACKEND)) +#define G_ENGINE_BACKEND_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_ENGINE_BACKEND, GEngineBackendClass)) + + +/* Méthode de traitement d'un contenu binaire pour recherches (instance) */ +typedef struct _GEngineBackend GEngineBackend; + +/* Méthode de traitement d'un contenu binaire pour recherches (classe) */ +typedef struct _GEngineBackendClass GEngineBackendClass; + + +/* Indique le type défini pour une méthode de recherche dans du binaire. */ +GType g_engine_backend_get_type(void); + +/* Indique la taille maximale des suites d'octets recherchées. */ +size_t g_engine_backend_get_atom_max_size(const GEngineBackend *); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +bool g_engine_backend_enroll_plain_pattern(GEngineBackend *, const uint8_t *, size_t, uint32_t [2]); + +/* Met en ordre les derniers détails avant un premier scan. */ +bool g_engine_backend_warm_up(GEngineBackend *); + +/* Récupère les identifiants finaux pour un motif recherché. */ +patid_t g_engine_backend_build_plain_pattern_id(const GEngineBackend *, const uint32_t [2]); + +/* Détermine le nombre d'identifiants constitués. */ +size_t g_engine_backend_count_plain_pattern_ids(const GEngineBackend *); + +/* Parcours un contenu binaire à la recherche de motifs. */ +void g_engine_backend_run_scan(const GEngineBackend *, GScanContext *); + +/* Imprime quelques faits quant aux éléments mis en place. */ +void g_engine_backend_output_stats(const GEngineBackend *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKEND_H */ diff --git a/src/analysis/scan/patterns/backends/Makefile.am b/src/analysis/scan/patterns/backends/Makefile.am new file mode 100644 index 0000000..23b0163 --- /dev/null +++ b/src/analysis/scan/patterns/backends/Makefile.am @@ -0,0 +1,29 @@ + +noinst_LTLIBRARIES = libanalysisscanpatternsbackends.la + + +libanalysisscanpatternsbackends_la_SOURCES = \ + acism-int.h \ + acism.h acism.c \ + bitap-int.h \ + bitap.h bitap.c \ + hyperscan-int.h \ + hyperscan.h hyperscan.c + +# Cf. https://www.gnu.org/software/automake/manual/html_node/Per_002dObject-Flags.html + +AM_CFLAGS = $(LIBGOBJ_CFLAGS) $(LIBHS_CFLAGS) + + + +#AM_CFLAGS:=$(filter-out -O2,$(AM_CFLAGS)) + + +#bitap.lo: AM_CFLAGS += -Ofast -march=native -falign-functions=1 -falign-jumps=1 -falign-loops=1 -falign-labels=1 #-mavx512bw +#bitap.lo: AM_CFLAGS += -O3 -march=native -falign-functions=1 -falign-jumps=1 -falign-loops=1 -falign-labels=1 #-mavx512bw +bitap.lo: AM_CFLAGS += -g -march=native -mno-vzeroupper -falign-functions=1 -falign-jumps=1 -falign-loops=1 -falign-labels=1 + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanpatternsbackends_la_SOURCES:%c=) diff --git a/src/analysis/scan/patterns/backends/acism-int.h b/src/analysis/scan/patterns/backends/acism-int.h new file mode 100644 index 0000000..c4a72ca --- /dev/null +++ b/src/analysis/scan/patterns/backends/acism-int.h @@ -0,0 +1,206 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * acism-int.h - prototypes internes pour la méthode de recherche basée sur l'algorithme Aho-Corasick Interleaved State-transition Matrix + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKENDS_ACISM_INT_H +#define _ANALYSIS_SCAN_PATTERNS_BACKENDS_ACISM_INT_H + + +#include "acism.h" + + +#include <stdint.h> + + +#include "../backend-int.h" +#include "../../../../common/bits.h" + + + +//#define __USE_BYTE_FREQ +//#define __SORT_BEFORE_BITMASK + + +#define ACSIM_ATOM_SIZE 7 + + + +/* Définition d'une portion de cible */ +typedef struct _acism_source_t +{ + /** + * Champs renseignés dans g_acism_backend_setup_for(). + */ + + const uint8_t *atoms; /* Motif remarquable */ + size_t len; /* Nombre d'octets considérés */ + + /** + * Champs renseignés dans g_acism_backend_build_trie(). + */ + + bool is_first; /* Première instance rencontrée*/ + + union + { + uint32_t coverage[2]; /* Départ et quantité de suivis*/ + struct + { + size_t first_source; /* Indice de première source */ + uint32_t index; /* Position dans la liste */ + }; + }; + +} acism_source_t; + +#define SOURCE_COVERAGE_START 0 +#define SOURCE_COVERAGE_COUNT 1 +#define SOURCE_COVERAGE_END 1 + +/* Etude de la fréquence des octets pour attribution des codes */ +typedef struct _acism_freq_rank_t +{ + unsigned int frequency; /* Occurrences d'un octet */ + uint8_t rank; /* Valeur dudit octet */ + +} acism_freq_rank_t; + +/* Identifiant unique pour une valeur 8 bits donnée (max 257) */ +typedef uint16_t acism_code_t; + +#define MIN_ACISM_CODE 0 +#define MAX_ACISM_CODE 0xffff + +#define ROOT_STATE_INDEX 0 + +/* Noeud de l'arborescence brute */ +typedef struct _acism_trie_node_t +{ + struct _acism_trie_node_t *parent; /* Noeud parent pour remontée */ + struct _acism_trie_node_t *sibling; /* Noeud de même niveau suivant*/ + struct _acism_trie_node_t *child; /* Noeud de lecture suivant */ + struct _acism_trie_node_t *suffix_link; /* Retour en cas d'échec */ + + bin_t data; /* Donnée brute représentée */ + acism_code_t code; /* Identifiant du noeud */ + + acism_code_t min_child_code; /* Plus petit code suivant */ + acism_code_t max_child_code; /* Plus grand code suivant */ + size_t children_count; /* Nombre de codes suivants */ + + size_t matched_atom; /* Indice de correspondance */ + + size_t state_index; /* Indice de le tableau final */ + +} acism_trie_node_t; + +#if __LONG_WIDTH__ < 64 + +/* Cellule du tableau compressé final */ +typedef struct _acism_state_t +{ + union + { + /* Indice 0 */ + struct + { + unsigned int match : 1; /* Correspondance ici */ + unsigned int unused : 4; /* Espace encore disponible */ + unsigned int atom_size : 3; /* Taille d'atome représenté */ + unsigned int suffix : 1; /* Correspondance ailleurs */ + }; + + /* Indice 1 et + */ + unsigned int code : 9; /* Position depuis la base */ + + }; + + unsigned int index : 23; /* Indice de saut */ + +} acism_state_t; + +#else + +/* Cellule du tableau compressé final */ +typedef union _acism_state_t +{ + /* Indice 0 */ + struct + { + uint8_t match : 1; /* Correspondance ici */ + uint8_t single_source : 1; /* Unique source à notifier */ + uint8_t atom_size; /* Indice de saut */ + uint8_t suffix : 1; /* Correspondance ailleurs */ + }; + + /* Indice 1 et + */ + uint32_t code; /* Position depuis la base */ + + /* Tous */ + struct + { + uint32_t any; /* Saut de bits */ + uint32_t index; /* Indice de saut */ + }; + +} acism_state_t; + +#endif + +/* Méthode de recherche basée sur l'algorithme Acism (instance) */ +struct _GAcismBackend +{ + GEngineBackend parent; /* A laisser en premier */ + +#ifdef __USE_BYTE_FREQ + acism_code_t codes_for_bytes[256]; /* Traduction octets -> codes */ + acism_code_t codes_count; /* Quantité de traductions */ +#endif + + acism_source_t *sources; /* Liste de motifs remarquables*/ + size_t sources_count; /* Quantité de ces motifs */ + + size_t nchars; /* Taille cumulée des motifs */ + +#ifdef __USE_BYTE_FREQ + acism_freq_rank_t frequencies[256]; /* Fréquences des octets */ +#endif + + acism_trie_node_t *nodes; /* Liste de noeuds */ + size_t nodes_used; /* Nombre de noeuds utilisés */ + + bitfield_t *bitmap_usage; /* Localisation des usages */ + acism_state_t *states; /* Tableau de transitions */ + uint32_t *coverages; /* Bornes de suivi de positions*/ + +}; + +/* Méthode de recherche basée sur l'algorithme Acism (classe) */ +struct _GAcismBackendClass +{ + GEngineBackendClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKENDS_ACISM_INT_H */ diff --git a/src/analysis/scan/patterns/backends/acism.c b/src/analysis/scan/patterns/backends/acism.c new file mode 100644 index 0000000..53bad11 --- /dev/null +++ b/src/analysis/scan/patterns/backends/acism.c @@ -0,0 +1,1522 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * acism.c - méthode de recherche basée sur l'algorithme Aho-Corasick Interleaved State-transition Matrix + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "acism.h" + + +#include <assert.h> +#include <stdlib.h> +#include <string.h> + + +#include "acism-int.h" +#include "../../../../common/sort.h" + + + +/* ---------------------- IMPLANTATION D'UNE NOUVELLE APPROCHE ---------------------- */ + + +/* Initialise la classe des méthodes basée sur ACISM. */ +static void g_acism_backend_class_init(GAcismBackendClass *); + +/* Initialise une instance de méthodes basée sur ACISM. */ +static void g_acism_backend_init(GAcismBackend *); + +/* Supprime toutes les références externes. */ +static void g_acism_backend_dispose(GAcismBackend *); + +/* Procède à la libération totale de la mémoire. */ +static void g_acism_backend_finalize(GAcismBackend *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique la taille maximale des suites d'octets recherchées. */ +size_t g_acism_backend_get_atom_max_size(const GAcismBackend *); + +/* Intègre un motif limité de contenu à rechercher. */ +static void g_acism_backend_setup_for(GAcismBackend *, const uint8_t *, size_t, uint32_t [2]); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +static bool g_acism_backend_enroll_plain_pattern(GAcismBackend *, const uint8_t *, size_t, uint32_t [2]); + +#ifdef __USE_BYTE_FREQ + +/* Compare un niveau de fréquence avec un autre. */ +static int compare_byte_frequencies(const acism_freq_rank_t *, const acism_freq_rank_t *); + +/* Détermine les identifiants de chaque valeur 8 bits utile. */ +static void g_acism_backend_define_codes(GAcismBackend *); + +#endif + +/* Construit l'arborescence de noeuds de lecture. */ +static void g_acism_backend_build_trie(GAcismBackend *); + +/* Construit l'arborescence de noeuds de lecture. */ +static void g_acism_backend_build_suffix_links(GAcismBackend *); + +#ifdef __SORT_BEFORE_BITMASK + +/* Compare des noeuds selon l'espace de codes couvert. */ +static int compare_node_according_to_code_range(const acism_trie_node_t **, const acism_trie_node_t **); + +#endif + +/* Organise la convertion de l'arborescence en tableau. */ +static void g_acism_backend_prepare_interleave_array(GAcismBackend *); + +/* Compresse l'arborescence dans un tableau de position. */ +static void g_acism_backend_build_interleave_array(GAcismBackend *); + +/* Met en ordre les derniers détails avant un premier scan. */ +static bool g_acism_backend_warm_up(GAcismBackend *); + +/* Récupère les identifiants finaux pour un motif recherché. */ +static patid_t g_acism_backend_build_plain_pattern_id(const GAcismBackend *, const uint32_t [2]); + +/* Détermine le nombre d'identifiants constitués. */ +static size_t g_acism_backend_count_plain_pattern_ids(const GAcismBackend *); + +/* Parcours un contenu binaire à la recherche de motifs. */ +static void g_acism_backend_run_scan(const GAcismBackend *, GScanContext *); + +/* Affiche les caractéristques d'un noeud et de ses enfants. */ +static void visit_and_output_node(const acism_trie_node_t *, unsigned int); + +/* Imprime quelques faits quant aux éléments mis en place. */ +static void g_acism_backend_output_stats(const GAcismBackend *); + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLANTATION D'UNE NOUVELLE APPROCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un moteur de recherche pour données. */ +G_DEFINE_TYPE(GAcismBackend, g_acism_backend, G_TYPE_ENGINE_BACKEND); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des méthodes basée sur ACISM. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_class_init(GAcismBackendClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GEngineBackendClass *backend; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_acism_backend_dispose; + object->finalize = (GObjectFinalizeFunc)g_acism_backend_finalize; + + backend = G_ENGINE_BACKEND_CLASS(klass); + + backend->get_max_size = (get_backend_atom_max_size_fc)g_acism_backend_get_atom_max_size; + backend->enroll_plain = (enroll_plain_into_backend_fc)g_acism_backend_enroll_plain_pattern; + backend->warm_up = (warm_up_backend_fc)g_acism_backend_warm_up; + backend->build_id = (build_backend_plain_pattern_id_fc)g_acism_backend_build_plain_pattern_id; + backend->count_ids = (count_backend_plain_pattern_ids_fc)g_acism_backend_count_plain_pattern_ids; + backend->run_scan = (run_backend_scan_fc)g_acism_backend_run_scan; + backend->output = (output_backend_stats_fc)g_acism_backend_output_stats; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance à initialiser. * +* * +* Description : Initialise une instance de méthodes basée sur ACISM. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_init(GAcismBackend *backend) +{ +#ifdef __USE_BYTE_FREQ + size_t i; /* Boucle de parcours #1 */ + acism_freq_rank_t *iter; /* Boucle de parcours #2 */ +#endif + +#ifdef __USE_BYTE_FREQ + memset(backend->codes_for_bytes, 0, 256 * sizeof(acism_code_t)); +#endif + + backend->nchars = 0; + +#ifdef __USE_BYTE_FREQ + for (i = 0, iter = backend->frequencies; i < 256; i++, iter++) + { + iter->frequency = 0; + iter->rank = i; + } +#endif + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_dispose(GAcismBackend *backend) +{ + G_OBJECT_CLASS(g_acism_backend_parent_class)->dispose(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_finalize(GAcismBackend *backend) +{ + if (backend->sources != NULL) + free(backend->sources); + + if (backend->nodes != NULL) + free(backend->nodes); + + if (backend->bitmap_usage != NULL) + delete_bit_field(backend->bitmap_usage); + + if (backend->states != NULL) + free(backend->states); + + if (backend->coverages != NULL) + free(backend->coverages); + + G_OBJECT_CLASS(g_acism_backend_parent_class)->finalize(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée une méthode de recherche basée sur l'algorithme Acism. * +* * +* Retour : Méthode mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GEngineBackend *g_acism_backend_new(void) +{ + GAcismBackend *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_ACISM_BACKEND, NULL); + + return G_ENGINE_BACKEND(result); + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Indique la taille maximale des suites d'octets recherchées. * +* * +* Retour : Valeur strictement positive. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_acism_backend_get_atom_max_size(const GAcismBackend *backend) +{ + size_t result; /* Taille à faire connaître */ + + result = ACSIM_ATOM_SIZE; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* pattern = chaîne de caractères classique à intégrer. * +* len = taille de cette chaîne. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Intègre un motif limité de contenu à rechercher. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_setup_for(GAcismBackend *backend, const uint8_t *pattern, size_t len, uint32_t tmp_id[2]) +{ + size_t current; /* Indice de source courante */ + acism_source_t *source; /* Définition à mémoriser */ + + /** + * Les motifs '\x00\x00\x00\x00abcd1234' et '\x01\x01\x01\x01abcd1234' + * peuvent constituer deux cibles différentes, mais ils comportent + * normalement la même séquence atomique à rechercher : 'abcd1234'. + * + * Chaque motif 'abcd1234' proposé est enregistré ici, et se verra in fine + * attribuer un identifiant propre. Le regroupement des motifs identiques + * et la constitution des identifiants finaux sont réalisés au moment de la + * construction de l'arborescence de recherche. + */ + + /* Pré-inscription pour l'extérieur */ + + current = backend->sources_count; + + tmp_id[0] = current; + tmp_id[1] = 0; /* Non utilisé */ + + /* Inscription en interne */ + + backend->sources = realloc(backend->sources, ++backend->sources_count * sizeof(acism_source_t)); + + source = &backend->sources[current]; + + source->atoms = pattern; + source->len = len; + + backend->nchars += len; + +#ifdef __USE_BYTE_FREQ + for (i = 0; i < len; i++) + backend->frequencies[pattern[i]].frequency++; +#endif + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* plain = chaîne de caractères classique à intégrer. * +* len = taille de cette chaîne. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Inscrit dans le moteur une chaîne de caractères à rechercher.* +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_acism_backend_enroll_plain_pattern(GAcismBackend *backend, const uint8_t *plain, size_t len, uint32_t tmp_id[2]) +{ + bool result; /* Bilan à retourner */ + + assert(len <= ACSIM_ATOM_SIZE); + + result = true; + + /** + * Le traitement différé des chaînes à rechercher permet deux choses : + * - la construction d'une table de permutation ; + * - le décompte des noeuds à allouer (en une seule fois). + * + * Si l'intention du premier point est louable (densifier les champs de bits + * pour allouer moins et tenir plus facilement dans le cache du CPU), la + * permetutation est extrèmement coûteuse pendant la phase de scan + * (une lecture supplémentaire par octet de données scannées). + * + * Le second point reste valable (à priori). + * + * L'appel à la fonction g_acism_backend_setup_for() demeure donc, et l'arbre + * est construit dans un second temps. La distinction de cette fonction avec + * la procédure d'enrôlement permet potentiellement d'étuer une bascule à + * moindre coût un jour. + */ + + g_acism_backend_setup_for(backend, plain, len, tmp_id); + + return result; + +} + + +#ifdef __USE_BYTE_FREQ + + +/****************************************************************************** +* * +* Paramètres : a = premier élément à comparer. * +* b = second élément à comparer. * +* * +* Description : Compare un niveau de fréquence avec un autre. * +* * +* Retour : Bilan de la comparaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static int compare_byte_frequencies(const acism_freq_rank_t *a, const acism_freq_rank_t *b) +{ + int result; /* Bilan à retourner */ + + /** + * Afin d'obtenir les plus grosses fréquences en premier, + * l'ordre de comparaison est inversé : b < a ? + */ + + result = sort_unsigned_long(b->frequency, a->frequency); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Détermine les identifiants de chaque valeur 8 bits utile. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_define_codes(GAcismBackend *backend) +{ + size_t i; /* Boucle de parcours #1 */ + acism_freq_rank_t *iter; /* Boucle de parcours #2 */ + + /** + * La redistribution des valeurs d'octet va permettre de compacter + * par la suite les masques de cellules utilisées pour construire + * le plus petit tableau des états. + * + * L'idée est de grouper le plus possible les états (représentés + * par un indice) autour de l'état 0. + */ + + qsort(backend->frequencies, 256, sizeof(acism_freq_rank_t), (__compar_fn_t)compare_byte_frequencies); + + /* 0 == racine */ + backend->codes_count++; + + for (i = 0, iter = backend->frequencies; i < 256; i++, iter++) + { + if (iter->frequency == 0) + break; + + backend->codes_for_bytes[iter->rank] = backend->codes_count++; + + } + +} + + +#endif + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Construit l'arborescence de noeuds de lecture. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_build_trie(GAcismBackend *backend) +{ + size_t i; /* Boucle de parcours #1 */ + acism_trie_node_t *next; /* Prochain noeud disponible */ + acism_trie_node_t *node; /* Tête de parcours */ + acism_source_t *source; /* Définition à mémoriser */ + size_t k; /* Boucle de parcours #2 */ + acism_code_t code; /* Identifiant de symbole */ + acism_trie_node_t *parent; /* Sauvegarde d'un accès */ + uint32_t current_start; /* Indice de gestionnaire */ + + backend->nodes = calloc(backend->nchars + 1, sizeof(acism_trie_node_t)); + + for (i = 0; i < (backend->nchars + 1); i++) + { + backend->nodes[i].min_child_code = MAX_ACISM_CODE; + backend->nodes[i].max_child_code = MIN_ACISM_CODE; + } + + next = backend->nodes + 1; + + for (i = 0; i < backend->sources_count; i++) + { + node = backend->nodes; + + source = &backend->sources[i]; + + /* Parcours des noeuds contenus */ + + for (k = 0; k < source->len && node->child != NULL; k++) + { +#ifdef __USE_BYTE_FREQ + code = backend->codes_for_bytes[source->atoms[k]]; +#else + code = 1 + source->atoms[k]; +#endif + + /* Insertion d'un nouveau noeud au début des enfants */ + if (code < node->child->code) + { + next->parent = node; + next->suffix_link = node; + next->data = source->atoms[k]; + next->code = code; + + next->sibling = node->child; + node->child = next++; + + if (code < node->min_child_code) node->min_child_code = code; + if (code > node->max_child_code) node->max_child_code = code; + node->children_count++; + + node = node->child; + + k++; + break; + + } + + parent = node; + + /* Recherche du point d'insertion idéal */ + for (node = node->child; + node->sibling != NULL && code >= node->sibling->code; + node = node->sibling); + + /* Si le noeud idéal n'existe pas, insertion ordonnée */ + if (code > node->code) + { + next->parent = parent; + next->suffix_link = parent; + next->data = source->atoms[k]; + next->code = code; + + next->sibling = node->sibling; + node->sibling = next++; + + if (code < parent->min_child_code) parent->min_child_code = code; + if (code > parent->max_child_code) parent->max_child_code = code; + parent->children_count++; + + node = node->sibling; + + k++; + break; + + } + + } + + /* Si un atome (partiellement ?) identique a déjà été inscrit */ + if (k == source->len) + { + /** + * L'atome déjà inscrit est plus long, et on se trouve ici dans le + * parcours de l'arborescence qui mène à sa conclusion, sans + * inscription d'une fin de parcours au point courant. + */ + if (node->matched_atom == 0) + goto register_leaf; + + /** + * Rattachement au motif strictement identique. + */ + else + { + assert(backend->sources[node->matched_atom - 1].is_first); + + source->is_first = false; + source->first_source = node->matched_atom - 1; + source->index = backend->sources[source->first_source].coverage[SOURCE_COVERAGE_COUNT]++; + + } + + } + + else + { + /* Creéation d'une nouvelle branche avec le reliquat */ + for (; k < source->len; k++) + { +#ifdef __USE_BYTE_FREQ + code = backend->codes_for_bytes[source->atoms[k]]; +#else + code = 1 + source->atoms[k]; +#endif + + next->parent = node; + next->suffix_link = node; + next->data = source->atoms[k]; + next->code = code; + + node->child = next++; + + if (code < node->min_child_code) node->min_child_code = code; + if (code > node->max_child_code) node->max_child_code = code; + node->children_count++; + + node = node->child; + + } + + register_leaf: + + node->matched_atom = i + 1; + + source->is_first = true; + source->coverage[SOURCE_COVERAGE_COUNT] = 1; + + } + + } + + backend->nodes_used = next - backend->nodes; + + /* Construction des bases pour identifiants */ + + current_start = 0; + + for (i = 0; i < backend->sources_count; i++) + { + source = &backend->sources[i]; + + if (source->is_first) + { + source->coverage[SOURCE_COVERAGE_START] = current_start; + + current_start += source->coverage[SOURCE_COVERAGE_COUNT]; + + } + + } + + assert(current_start == backend->sources_count); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Construit l'arborescence de noeuds de lecture. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_build_suffix_links(GAcismBackend *backend) +{ + size_t max_pos; /* Tête de lecture finale */ + acism_trie_node_t **stack; /* Pile des noeuds à traiter */ + size_t rd_pos; /* Tête de lecture */ + size_t wr_pos; /* Tête d'écriture */ + acism_trie_node_t *node; /* Noeud à traiter */ + acism_trie_node_t *parent; /* Noeud parent de la chaîne */ + acism_trie_node_t *iter; /* Boucle de parcours */ + + max_pos = backend->nodes_used; + + stack = calloc(max_pos, sizeof(acism_trie_node_t *)); + + /* Initialisation du parcours */ + + rd_pos = 0; + wr_pos = 0; + + stack[wr_pos++] = &backend->nodes[0]; + + assert(backend->nodes->sibling == NULL); + + /* Traitement manuel de démarrage pour éviter une condition en [0] */ + + for (iter = backend->nodes->child; iter != NULL; iter = iter->sibling) + stack[wr_pos++] = iter; + + rd_pos++; + + /* Suivi des liens déjà en place */ + + while (rd_pos < max_pos) + { + assert(rd_pos < wr_pos); + + node = stack[rd_pos++]; + + /* Remontée jusqu'à la découverte d'un lien d'intérêt */ + + for (parent = node->suffix_link; parent != NULL; parent = parent->suffix_link) + { + for (iter = parent->child; iter != NULL; iter = iter->sibling) + if (iter->code == node->code && iter != node) + { + node->suffix_link = iter; + break; + } + + if (iter != NULL) + break; + + } + + if (parent == NULL /* && node != &backend->nodes [0] */) + node->suffix_link = backend->nodes; + + /* Inscription des noeuds suivants */ + + for (iter = node->child; iter != NULL; iter = iter->sibling) + stack[wr_pos++] = iter; + + } + + /* Sortie propre */ + + free(stack); + +} + + +#ifdef __SORT_BEFORE_BITMASK + + +/****************************************************************************** +* * +* Paramètres : a = premier élément à comparer. * +* b = second élément à comparer. * +* * +* Description : Compare des noeuds selon l'espace de codes couvert. * +* * +* Retour : Bilan de la comparaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static int compare_node_according_to_code_range(const acism_trie_node_t **a, const acism_trie_node_t **b) +{ + int result; /* Bilan à retourner */ + const acism_trie_node_t *_a; /* Autre vision de l'élément #1*/ + const acism_trie_node_t *_b; /* Autre vision de l'élément #1*/ + acism_code_t range_a; /* Espacement des codes #1 */ + acism_code_t range_b; /* Espacement des codes #2 */ + + result = 0; + + _a = *a; + _b = *b; + + if (_a->child == NULL) + result = (_b->child == NULL ? 0 : 1); + + else if (_b->child == NULL) + result = (_a->child == NULL ? 0 : -1); + + else + { + assert(_a->min_child_code <= _a->max_child_code); + range_a = _a->max_child_code - _a->min_child_code; + + assert(_b->min_child_code <= _b->max_child_code); + range_b = _b->max_child_code - _b->min_child_code; + + result = sort_unsigned_long(range_b, range_a); + + if (result == 0) + result = sort_unsigned_long(_b->children_count, _a->children_count); + + } + + return result; + +} + + +#endif + + +#if 1 + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Organise la convertion de l'arborescence en tableau. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_prepare_interleave_array(GAcismBackend *backend) +{ +#ifdef __SORT_BEFORE_BITMASK + acism_trie_node_t **list; /* Liste de noeuds alloués */ +#endif + size_t i; /* Boucle de parcours #1 */ + size_t last_free_state; /* Dernier emplacement dispo. */ + size_t full_size; /* Cartographie entière */ + bitfield_t *global_usage; /* Cartographie des usages */ +#ifndef NDEBUG + size_t pops[3]; /* Décomptes individuels */ + size_t bsum; /* Somme de tous les bits */ +#endif + bitfield_t *usage; /* Cartographie locale */ + acism_trie_node_t *node; /* Noeud en cours de traitement*/ + size_t highest; /* Poids du bit le plus fort */ + acism_trie_node_t *iter; /* Boucle de parcours #2 */ + size_t first_freedom_word; /* Premier mot avec des dispos.*/ + size_t free_state; /* Emplacement libre trouvé */ + + /* Préparation de la liste de noeuds à inscrire */ + +#ifdef __SORT_BEFORE_BITMASK + + list = calloc(backend->nodes_used, sizeof(acism_trie_node_t *)); + + for (i = 0; i < backend->nodes_used; i++) + list[i] = backend->nodes + i; + + qsort(list + 1, backend->nodes_used - 1, sizeof(acism_trie_node_t *), + (__compar_fn_t)compare_node_according_to_code_range); + +#endif + + /* Insertion des noeuds dans l'ordre prévu */ + + last_free_state = 257; + full_size = last_free_state + 257; + global_usage = create_bit_field(full_size, false); + +#ifndef NDEBUG + + pops[0] = 0; + pops[1] = 0; + pops[2] = 0; + + bsum = 0; + +#endif + + usage = create_bit_field(257, false); + + for (i = 0; i < backend->nodes_used; i++) + { +#ifdef __SORT_BEFORE_BITMASK + node = list[i]; +#else + node = backend->nodes + i; +#endif + + /* Préparation du masque du noeud */ + + truncate_bit_field(&usage, 257); + + reset_all_in_bit_field(usage); + + set_in_bit_field(usage, 0, 1); + +#ifndef NDEBUG + pops[0]++; +#endif + + highest = 0; + + for (iter = node->child; iter != NULL; iter = iter->sibling) + { + set_in_bit_field(usage, iter->code, 1); + +#ifndef NDEBUG + pops[0]++; +#endif + + if (iter->code > highest) + highest = iter->code; + + } + +#ifndef NDEBUG + pops[1] += popcount_for_bit_field(usage); +#endif + + assert(popcount_for_bit_field(usage) == (node->children_count + 1)); + + truncate_bit_field(&usage, ++highest); + + /* Recherche d'une position idéale */ + + if (i == 0) + { + first_freedom_word = 0; + free_state = 0; + } + + else + free_state = find_interleaving_index_for_acism(global_usage, usage, &first_freedom_word); + + /* Suivi global */ + + assert(!test_in_bit_field(global_usage, free_state)); + + or_bit_field_at(global_usage, usage, free_state); + +#ifndef NDEBUG + bsum += node->children_count + 1; + assert(popcount_for_bit_field(global_usage) == bsum); +#endif + + node->state_index = free_state; + + if ((free_state + 257) > last_free_state) + { + last_free_state += 257; + full_size += 257; + resize_bit_field(&global_usage, full_size); + } + + } + + /* Sotie encadrée */ + +#ifndef NDEBUG + + pops[2] = popcount_for_bit_field(global_usage); + + assert(pops[0] == pops[1]); + assert(pops[0] == pops[2]); + +#endif + + backend->bitmap_usage = global_usage; + + delete_bit_field(usage); + +#ifdef __SORT_BEFORE_BITMASK + free(list); +#endif + +} + + +#else + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Organise la convertion de l'arborescence en tableau. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_prepare_interleave_array(GAcismBackend *backend) +{ + size_t max_pos; /* Tête de lecture finale */ + acism_trie_node_t **stack; /* Pile des noeuds à traiter */ + size_t last_free_state; /* Dernier emplacement dispo. */ + size_t full_size; /* Cartographie entière */ + bitfield_t *global_usage; /* Cartographie des usages */ + bitfield_t *usage; /* Cartographie locale */ + size_t rd_pos; /* Tête de lecture */ + size_t wr_pos; /* Tête d'écriture */ + size_t first_freedom_word; /* Premier mot avec des dispos.*/ + acism_trie_node_t *node; /* Noeud à traiter */ + acism_trie_node_t *iter; /* Boucle de parcours */ + size_t free_state; /* Emplacement libre trouvé */ + + max_pos = backend->nodes_used; + + stack = calloc(max_pos, sizeof(acism_trie_node_t *)); + + last_free_state = 257; + full_size = last_free_state + 257; + global_usage = create_bit_field(full_size, false); + + usage = create_bit_field(257, false); + + /* Initialisation du parcours */ + + rd_pos = 0; + wr_pos = 0; + + stack[wr_pos++] = &backend->nodes[0]; + + assert(backend->nodes->sibling == NULL); + + /* Traitement manuel de démarrage pour éviter une condition en [0] */ + + set_in_bit_field(global_usage, 0, 1); + + for (iter = backend->nodes->child; iter != NULL; iter = iter->sibling) + { + set_in_bit_field(global_usage, iter->code, 1); + stack[wr_pos++] = iter; + } + + rd_pos++; + + first_freedom_word = 0; + + /* Suivi des liens déjà en place */ + + while (rd_pos < max_pos) + { + assert(rd_pos < wr_pos); + + node = stack[rd_pos++]; + + /* Préparation du masque du noeud et inscription des noeuds suivants */ + + reset_all_in_bit_field(usage); + + set_in_bit_field(usage, 0, 1); + + for (iter = node->child; iter != NULL; iter = iter->sibling) + { + set_in_bit_field(usage, iter->code, 1); + stack[wr_pos++] = iter; + } + + assert(popcount_for_bit_field(usage) == (node->children_count + 1)); + + /* Recherche d'une position idéale */ + + free_state = find_interleaving_index_for_acism(global_usage, usage, &first_freedom_word); + + /* Suivi global */ + + assert(!test_in_bit_field(global_usage, free_state)); + + or_bit_field_at(global_usage, usage, free_state); + + node->state_index = free_state; + + if ((free_state + 257) > last_free_state) + { + last_free_state += 257; + full_size += 257; + resize_bit_field(&global_usage, full_size); + } + + } + + /* Sotie encadrée */ + + backend->bitmap_usage = global_usage; + + delete_bit_field(usage); + + free(stack); + +} + + +#endif + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Compresse l'arborescence dans un tableau de position. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_build_interleave_array(GAcismBackend *backend) +{ + size_t maxsize; /* Taille maximale du tableau */ + size_t i; /* Boucle de parcours #1 */ + acism_trie_node_t *node; /* Noeud à transcrire */ + acism_state_t *base; /* Base d'une série de cellules*/ + uint32_t *coverage; /* Couverture des inscriptions */ + acism_source_t *source; /* Définition originelle */ + acism_trie_node_t *iter; /* Sous-noeud à inscrire #2 */ + acism_trie_node_t *child; /* Sous-noeud à inscrire #3 */ + uint16_t offset; /* Décalage local */ + + maxsize = get_bit_field_size(backend->bitmap_usage); + + backend->states = calloc(maxsize, sizeof(acism_state_t)); + backend->coverages = calloc(maxsize, 2 * sizeof(uint32_t)); + + for (i = 0; i < backend->nodes_used; i++) + { + node = &backend->nodes[i]; + base = backend->states + node->state_index; + + assert(base[0].code == 0); + assert(base[0].index == 0); + + if (node->matched_atom > 0) + { + source = &backend->sources[node->matched_atom - 1]; + + base[0].match = 1; + base[0].single_source = source->coverage[SOURCE_COVERAGE_COUNT] == 1 ? 1 : 0; + base[0].atom_size = backend->sources[node->matched_atom - 1].len - 1; + + coverage = &backend->coverages[node->state_index * 2]; + + coverage[SOURCE_COVERAGE_START] = source->coverage[SOURCE_COVERAGE_START]; + coverage[SOURCE_COVERAGE_END] = coverage[SOURCE_COVERAGE_START] \ + + source->coverage[SOURCE_COVERAGE_COUNT]; + + for (iter = node->parent->suffix_link; iter != NULL; iter = iter->suffix_link) + { + for (child = iter->child; child != NULL; child = child->sibling) + if (child->code == node->code && child->matched_atom > 0) + break; + + if (child != NULL) + { + base[0].suffix = 1; + break; + } + + } + + } + + base[0].index = i == 0 ? 0 : node->suffix_link->state_index; + + for (child = node->child; child != NULL; child = child->sibling) + { + offset = child->code; + + assert(base[offset].code == 0); + assert(base[offset].index == 0); + + base[offset].code = child->code; + base[offset].index = child->state_index; + + } + + } + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Met en ordre les derniers détails avant un premier scan. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_acism_backend_warm_up(GAcismBackend *backend) +{ + bool result; /* Bilan à retourner */ + + result = true; + +#ifdef __USE_BYTE_FREQ + + /** + * Attribue un identifiant unique pour chaque octet présent dans les + * motifs recherchés. + */ + g_acism_backend_define_codes(backend); + +#endif + + /** + * Construit une arborescence de lecture à partir des différents + * octets présents dans les motifs. + * + * Les couvertures des futurs tableaux de correspondances sont + * établies au passage, ouvrant la voie aux définitions d'identifiant + * pour les motifs enregistrés. + */ + g_acism_backend_build_trie(backend); + + /** + * Met en place les liens suivis en cas d'échec de correspondance + * lors de la lecture d'un octet supplémentaire. + */ + g_acism_backend_build_suffix_links(backend); + + /** + * Conversion de l'arborescence en tableau plat et compressé. + */ + + g_acism_backend_prepare_interleave_array(backend); + + g_acism_backend_build_interleave_array(backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Récupère les identifiants finaux pour un motif recherché. * +* * +* Retour : Identifiant constitué ou INVALID_PATTERN_ID en cas d'échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static patid_t g_acism_backend_build_plain_pattern_id(const GAcismBackend *backend, const uint32_t tmp_id[2]) +{ + patid_t result; /* Identifiant à retourner */ + acism_source_t *source; /* Motif d'origine concerné */ + acism_source_t *reference; /* Renvoi vers un même motif */ + + assert(tmp_id[0] < backend->sources_count); + + /** + * L'indicateur tmp_id[1] n'est pas utilisé ici. + */ + + source = backend->sources + tmp_id[0]; + + if (source->is_first) + result = source->coverage[SOURCE_COVERAGE_START]; + + else + { + reference = backend->sources + source->first_source; + + assert(source->index < reference->coverage[SOURCE_COVERAGE_COUNT]); + + result = reference->coverage[SOURCE_COVERAGE_START] + source->index; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* * +* Description : Détermine le nombre d'identifiants constitués. * +* * +* Retour : Quantité de gestionnaires de suivi à prévoir. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static size_t g_acism_backend_count_plain_pattern_ids(const GAcismBackend *backend) +{ + size_t result; /* Quantité à retourner */ + + result = backend->sources_count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_run_scan(const GAcismBackend *backend, GScanContext *context) +{ + GBinContent *content; /* Contenu binaire manipulé */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ +#ifdef __USE_BYTE_FREQ + acism_code_t codes_for_bytes[256]; /* Copie des codes d'accès */ +#endif + acism_state_t *root; /* Racine de l'arborescence */ + uint32_t *coverages; /* Bornes de suivi de positions*/ + unsigned int state; /* Tête de lecture courante */ + phys_t i; /* Boucle de parcours #1 */ + acism_code_t code; /* Code du caractère courant */ + unsigned int next; /* Prochaine tête à valider */ + acism_state_t next_state; /* Prochaine tête à valider */ + uint32_t k; /* Boucle de parcours #2 */ + uint32_t final_k; /* Dernier indice à traiter */ + unsigned int iter; /* Boucle de parcours #3 */ + acism_state_t test_state; /* Test de validité alternative*/ + acism_state_t sub_state; /* Test de validité alternative*/ + + content = g_scan_context_get_content(context); + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + /* Suivi via l'arborescence aplatie */ + +#ifdef __USE_BYTE_FREQ + memcpy(&codes_for_bytes, backend->codes_for_bytes, 256 * sizeof(acism_code_t)); +#endif + + root = backend->states; + if (root == NULL) goto done; + + coverages = backend->coverages; + + state = ROOT_STATE_INDEX; + + for (i = 0; i < dlen; i++) + { +#ifdef __USE_BYTE_FREQ + code = codes_for_bytes[data[i]]; +#else + code = 1 + data[i]; +#endif + + /* Déplacement de la tête de lecture dans l'arborescence */ + + retry: + + next = state + code; + + if (root[next].code == code) + { + next = root[next].index; + next_state = root[next]; + } + + else if (state != ROOT_STATE_INDEX) + { + state = root[state].index; + goto retry; + } + + else + continue; + + /* Remontée d'éventuels résultats */ + + if (next_state.match) + { + k = coverages[next * 2 + SOURCE_COVERAGE_START]; + + if (next_state.single_source) + g_scan_context_store_atom_match_end(context, k, i); + //g_umem_slice_put_uint64(matches[0/*k*/], i - next_state.atom_size); + + else + { + final_k = coverages[next * 2 + SOURCE_COVERAGE_END]; + + for (; k < final_k; k++) + g_scan_context_store_atom_match_end(context, k, i); + //g_umem_slice_put_uint64(matches[0/*k*/], i - next_state.atom_size); + + } + + if (next_state.suffix) + { + for (iter = root[state].index; ; iter = root[iter].index) + { + test_state = root[iter + code]; + + if (test_state.code == code) + { + sub_state = root[test_state.index]; + + if (sub_state.match) + { + assert(sub_state.atom_size < next_state.atom_size); + + k = coverages[test_state.index * 2 + SOURCE_COVERAGE_START]; + + if (sub_state.single_source) + g_scan_context_store_atom_match_end(context, k, i); + //g_umem_slice_put_uint64(matches[0/*k*/], i - sub_state.atom_size); + + else + { + final_k = coverages[test_state.index * 2 + SOURCE_COVERAGE_END]; + + for (; k < final_k; k++) + g_scan_context_store_atom_match_end(context, k, i); + //g_umem_slice_put_uint64(matches[0/*k*/], i - sub_state.atom_size); + + } + + } + + } + + if (iter == ROOT_STATE_INDEX) + break; + + } + + } + + + } + + /* Bascule au caractère suivant */ + + state = next; + + } + + done: + + g_object_unref(G_OBJECT(content)); + +} + + +/****************************************************************************** +* * +* Paramètres : node = noeud d'arborescence à traiter. * +* level = profondeur courante. * +* * +* Description : Affiche les caractéristques d'un noeud et de ses enfants. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void visit_and_output_node(const acism_trie_node_t *node, unsigned int level) +{ + unsigned int i; /* Boucle de parcours #1 */ + acism_trie_node_t *iter; /* Boucle de parcours #2 */ + + for (i = 0; i < level; i++) + printf(" "); + + printf(" '%c' (code=%hhu)\n", node->data, node->code); + + for (iter = node->child; iter != NULL; iter = iter->sibling) + visit_and_output_node(iter, level + 1); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Imprime quelques faits quant aux éléments mis en place. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_acism_backend_output_stats(const GAcismBackend *backend) +{ + printf("nodes used: %zu\n", backend->nodes_used); + + printf("full_size: %zu (real: %zu)\n", + get_bit_field_size(backend->bitmap_usage), + popcount_for_bit_field(backend->bitmap_usage)); + + visit_and_output_node(backend->nodes, 0); + +} diff --git a/src/analysis/scan/patterns/backends/acism.h b/src/analysis/scan/patterns/backends/acism.h new file mode 100644 index 0000000..837022a --- /dev/null +++ b/src/analysis/scan/patterns/backends/acism.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * acism.h - prototypes pour la méthode de recherche basée sur l'algorithme Aho-Corasick Interleaved State-transition Matrix + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKENDS_ACISM_H +#define _ANALYSIS_SCAN_PATTERNS_BACKENDS_ACISM_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "../backend.h" + + + +#define G_TYPE_ACISM_BACKEND g_acism_backend_get_type() +#define G_ACISM_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_ACISM_BACKEND, GAcismBackend)) +#define G_IS_ACISM_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_ACISM_BACKEND)) +#define G_ACISM_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_ACISM_BACKEND, GAcismBackendClass)) +#define G_IS_ACISM_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_ACISM_BACKEND)) +#define G_ACISM_BACKEND_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_ACISM_BACKEND, GAcismBackendClass)) + + +/* Méthode de recherche basée sur l'algorithme Acism (instance) */ +typedef struct _GAcismBackend GAcismBackend; + +/* Méthode de recherche basée sur l'algorithme Acism (classe) */ +typedef struct _GAcismBackendClass GAcismBackendClass; + + +/* Indique le type défini pour un moteur de recherche pour données. */ +GType g_acism_backend_get_type(void); + +/* Crée une méthode de recherche basée sur l'algorithme Acism. */ +GEngineBackend *g_acism_backend_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKENDS_ACISM_H */ diff --git a/src/analysis/scan/patterns/backends/bitap-int.h b/src/analysis/scan/patterns/backends/bitap-int.h new file mode 100644 index 0000000..ea739b4 --- /dev/null +++ b/src/analysis/scan/patterns/backends/bitap-int.h @@ -0,0 +1,132 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * bitap-int.h - prototypes internes pour la méthode de recherche basée sur l'algorithme Bitap + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKENDS_BITAP_INT_H +#define _ANALYSIS_SCAN_PATTERNS_BACKENDS_BITAP_INT_H + + +#include "bitap.h" + + +#include <immintrin.h> + + +#include "../backend-int.h" +#include "../../../../common/cpu.h" +#include "../../../../../config.h" + + + +#define BITAP_ATOM_SIZE 7 + + +#ifdef HAVE_AVX2 + +/* Suivi d'un groupe de chaînes */ +typedef struct _grouped_strings_avx2_t +{ + __m256i pattern_masks[256]; /* Programmation de détections */ + __m256i found_masks; /* Masques multiples d'alerte */ + + __m256i R; /* Résultats courants */ + + size_t m[32]; /* Taille des chaînes */ + + patid_t found_id[32]; /* Indice des résultats */ + + size_t available; /* Nombre de places disponibles*/ + size_t used; /* Quantité de places utilisées*/ + +} grouped_strings_avx2_t; + +/* Suivi de l'ensemble de chaînes */ +typedef struct _group_manager_avx2_t +{ + grouped_strings_avx2_t **strings_8; /* Chaînes de taille 8 max */ + size_t count_8; /* Quantité de ces chaînes */ + +} group_manager_avx2_t; + +#endif + +#ifdef HAVE_AVX512_F + +/* Suivi d'un groupe de chaînes */ +typedef struct _grouped_strings_avx512_t +{ + __m512i pattern_masks[256]; /* Programmation de détections */ + __m512i found_masks; /* Masques multiples d'alerte */ + + __m512i R; /* Résultats courants */ + + size_t m[64]; /* Taille des chaînes */ + + patid_t found_id[64]; /* Indice des résultats */ + + size_t used; /* Quantité de places utilisées*/ + size_t available; /* Nombre de places disponibles*/ + +} grouped_strings_avx512_t; + +/* Suivi de l'ensemble de chaînes */ +typedef struct _group_manager_avx512_t +{ + grouped_strings_avx512_t **strings_8; /* Chaînes de taille 8 max */ + size_t count_8; /* Quantité de ces chaînes */ + +} group_manager_avx512_t; + +#endif + + +/* Méthode de recherche basée sur l'algorithme Bitap (instance) */ +struct _GBitapBackend +{ + GEngineBackend parent; /* A laisser en premier */ + + CPUSMIDFeature optimization; /* Mode de calculs */ + +#if defined HAVE_AVX2 || defined HAVE_AVX512_F + union + { +# ifdef HAVE_AVX2 + group_manager_avx2_t manager_avx2; /* Gestionnaire pour AVX2 */ +# endif +# ifdef HAVE_AVX512_F + group_manager_avx512_t manager_avx512;/* Gestionnaire pour AVX-512 */ +# endif + }; +#endif + +}; + +/* Méthode de recherche basée sur l'algorithme Bitap (classe) */ +struct _GBitapBackendClass +{ + GEngineBackendClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKENDS_BITAP_INT_H */ diff --git a/src/analysis/scan/patterns/backends/bitap.c b/src/analysis/scan/patterns/backends/bitap.c new file mode 100644 index 0000000..af50c6d --- /dev/null +++ b/src/analysis/scan/patterns/backends/bitap.c @@ -0,0 +1,2785 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * bitap.c - méthode de recherche basée sur l'algorithme Bitap + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "bitap.h" + + +#include <alloca.h> +#include <assert.h> +#include <sys/mman.h> +#include <sched.h> + + +#include "bitap-int.h" +#include "../../../../core/logs.h" +//#include "../../matches/bytes.h" + + + +/* ---------------------- IMPLANTATION D'UNE NOUVELLE APPROCHE ---------------------- */ + + +/* Initialise la classe des méthodes basée sur Bitmap. */ +static void g_bitap_backend_class_init(GBitapBackendClass *); + +/* Initialise une instance de méthodes basée sur Bitmap. */ +static void g_bitap_backend_init(GBitapBackend *); + +/* Supprime toutes les références externes. */ +static void g_bitap_backend_dispose(GBitapBackend *); + +/* Procède à la libération totale de la mémoire. */ +static void g_bitap_backend_finalize(GBitapBackend *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique la taille maximale des suites d'octets recherchées. */ +size_t g_bitap_backend_get_atom_max_size(const GBitapBackend *); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +static patid_t g_bitap_backend_enroll_plain_pattern(GBitapBackend *, GScanContext *, const uint8_t *, size_t); + +/* Parcours un contenu binaire à la recherche de motifs. */ +static void g_bitap_backend_run_scan(const GBitapBackend *, GScanContext *); + +/* Imprime quelques faits quant aux éléments mis en place. */ +static void g_bitap_backend_output_stats(const GBitapBackend *); + + + +/* ---------------------- OPTIMISATIONS POUR ARCHITECTURE AVX2 ---------------------- */ + + +#ifdef HAVE_AVX2 + +/* Indique la valeur portée par une expression rationnelle. */ +static void extend_grouped_strings_avx2(grouped_strings_avx2_t ***, size_t *); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +static patid_t enroll_plain_pattern_avx2(GBitapBackend *, GScanContext *, const bin_t *, size_t); + +/* Parcours un contenu binaire à la recherche de motifs. */ +static void run_scan_avx2(const GBitapBackend *, GScanContext *, const bin_t *, phys_t); + +#endif + + + +/* --------------------- OPTIMISATIONS POUR ARCHITECTURE AVX512 --------------------- */ + + +#ifdef HAVE_AVX512_F + +/* Indique la valeur portée par une expression rationnelle. */ +static void extend_grouped_strings_avx512(grouped_strings_avx512_t ***, size_t *); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +static patid_t enroll_plain_pattern_avx512(GBitapBackend *, GScanContext *, const bin_t *, size_t); + +/* Parcours un contenu binaire à la recherche de motifs. */ +static void run_scan_avx512(const GBitapBackend *, GScanContext *, const bin_t *, phys_t); + +#endif + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLANTATION D'UNE NOUVELLE APPROCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un moteur de recherche pour données. */ +G_DEFINE_TYPE(GBitapBackend, g_bitap_backend, G_TYPE_ENGINE_BACKEND); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des méthodes basée sur Bitmap. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bitap_backend_class_init(GBitapBackendClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GEngineBackendClass *backend; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_bitap_backend_dispose; + object->finalize = (GObjectFinalizeFunc)g_bitap_backend_finalize; + + backend = G_ENGINE_BACKEND_CLASS(klass); + + backend->get_max_size = (get_backend_atom_max_size_fc)g_bitap_backend_get_atom_max_size; + backend->enroll_plain = (enroll_plain_into_backend_fc)g_bitap_backend_enroll_plain_pattern; + backend->run_scan = (run_backend_scan_fc)g_bitap_backend_run_scan; + backend->output = (output_backend_stats_fc)g_bitap_backend_output_stats; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance à initialiser. * +* * +* Description : Initialise une instance de méthodes basée sur Bitmap. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bitap_backend_init(GBitapBackend *backend) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bitap_backend_dispose(GBitapBackend *backend) +{ + G_OBJECT_CLASS(g_bitap_backend_parent_class)->dispose(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bitap_backend_finalize(GBitapBackend *backend) +{ + G_OBJECT_CLASS(g_bitap_backend_parent_class)->finalize(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée une méthode de recherche basée sur l'algorithme Bitap. * +* * +* Retour : Méthode mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GEngineBackend *g_bitap_backend_new(void) +{ + GBitapBackend *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_BITAP_BACKEND, NULL); + + return G_ENGINE_BACKEND(result); + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Indique la taille maximale des suites d'octets recherchées. * +* * +* Retour : Valeur strictement positive. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_bitap_backend_get_atom_max_size(const GBitapBackend *backend) +{ + size_t result; /* Taille à faire connaître */ + + result = BITAP_ATOM_SIZE; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = contexte de l'analyse à mener. * +* plain = chaîne de caractères classique à intégrer. * +* len = taille de cette chaîne. * +* * +* Description : Inscrit dans le moteur une chaîne de caractères à rechercher.* +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static patid_t g_bitap_backend_enroll_plain_pattern(GBitapBackend *backend, GScanContext *context, const uint8_t *plain, size_t len) +{ + patid_t result; /* Identifiant à retourner */ + +#ifdef HAVE_AVX512_F + if (0) + result = enroll_plain_pattern_avx512(backend, context, plain, len); + else +#endif + +#ifdef HAVE_AVX2 + if (0) + result = enroll_plain_pattern_avx2(backend, context, plain, len); + else +#endif + + result = INVALID_PATTERN_ID; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bitap_backend_run_scan(const GBitapBackend *backend, GScanContext *context) +{ + cpu_set_t old_mask; /* Cartographie des CPU #1 */ + int ret; /* Bilan d'un appel */ + unsigned int cpu; /* Processeur courant */ + cpu_set_t new_mask; /* Cartographie des CPU #2 */ + GBinContent *content; /* Contenu binaire manipulé */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ + + ret = sched_getaffinity(0, sizeof(cpu_set_t), &old_mask); + + if (ret != 0) + { + LOG_ERROR_N("sched_getaffinity"); + goto exit; + } + + ret = getcpu(&cpu, NULL); + + if (ret != 0) + { + LOG_ERROR_N("get_cpu"); + goto exit; + } + + CPU_ZERO(&new_mask); + CPU_SET(cpu, &new_mask); + + ret = sched_setaffinity(0, sizeof(cpu_set_t), &new_mask); + + if (ret != 0) + { + LOG_ERROR_N("sched_setaffinity"); + goto exit; + } + + content = g_scan_context_get_content(context); + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + assert(data != NULL); + + + + +#ifdef HAVE_AVX512_F + if (0) + run_scan_avx512(backend, context, data, dlen); + else +#endif + +#ifdef HAVE_AVX2 + if (0) + run_scan_avx2(backend, context, data, dlen); + else +#endif + + ; + + g_object_unref(G_OBJECT(content)); + + exit: + + ; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Imprime quelques faits quant aux éléments mis en place. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bitap_backend_output_stats(const GBitapBackend *backend) +{ + printf("hello here!\n"); + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* OPTIMISATIONS POUR ARCHITECTURE AVX2 */ +/* ---------------------------------------------------------------------------------- */ + + +/** + * Cf. https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#techs=AVX,AVX2 + */ + +#ifdef HAVE_AVX2 + +/****************************************************************************** +* * +* Paramètres : strings = ensemble de groupes constitués. [OUT] * +* count = nombre de groupes courant. [OUT] * +* * +* Description : Indique la valeur portée par une expression rationnelle. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void extend_grouped_strings_avx2(grouped_strings_avx2_t ***strings, size_t *count) +{ + grouped_strings_avx2_t *new; /* Zone supplémentaire */ + size_t i; /* Boucle de parcours */ + + /* Définition d'un nouvel élément vierge */ + + new = aligned_alloc(256, sizeof(grouped_strings_avx2_t)); + + for (i = 0; i < 256; i++) + new->pattern_masks[i] = _mm256_set1_epi8(~0); + + new->found_masks = _mm256_set1_epi8(~0); + + new->R = _mm256_set1_epi8(~1); + + for (i = 0; i < 32; i++) + { + new->m[i] = 0; + + new->found_id[i] = INVALID_PATTERN_ID; + + } + + new->available = 32; + new->used = 0; + + /* Inscription */ + + *strings = realloc(*strings, ++(*count) * sizeof(grouped_strings_avx2_t *)); + + (*strings)[*count - 1] = new; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = contexte de l'analyse à mener. * +* plain = chaîne de caractères classique à intégrer. * +* plen = taille de cette chaîne. * +* * +* Description : Inscrit dans le moteur une chaîne de caractères à rechercher.* +* * +* Retour : Indice de résultats pour le motif. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static patid_t enroll_plain_pattern_avx2(GBitapBackend *backend, GScanContext *context, const bin_t *plain, size_t plen) +{ + patid_t result; /* Identifiant à retourner */ + grouped_strings_avx2_t ***strings; /* Groupe de chaînes visé */ + size_t *count; /* Taille de ce groupe */ + grouped_strings_avx2_t *last; /* Dernier groupe à remplir */ + size_t n; /* Indice dans le groupe */ + size_t i; /* Boucle de parcours */ + __m256i *letter; /* Lettre à marquer */ + + /* Sélection du groupe de travail adéquat */ + + strings = &backend->manager_avx2.strings_8; + count = &backend->manager_avx2.count_8; + + /* Préparation de la place nécessaire */ + + if (*count == 0) + { + extend_grouped_strings_avx2(strings, count); + + last = (*strings)[0]; + + } + + else + { + last = (*strings)[*count - 1]; + + if (last->used == last->available) + { + extend_grouped_strings_avx2(strings, count); + last = (*strings)[*count - 1]; + } + + } + + /* Intégration d'une nouvelle chaîne */ + + n = last->used++; + + last->m[n] = plen; + + result = 0; // FIXME g_scan_context_get_new_pattern_id(context); + + last->found_id[n] = result; + + ((uint8_t *)&last->found_masks)[n] = (1 << plen); + + for (i = 0; i < plen; i++) + { + letter = last->pattern_masks + plain[i]; + ((uint8_t *)letter)[n] &= ~(1 << i); + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* data = données à analyser. * +* dlen = quantité de ces données. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void run_scan_avx2(const GBitapBackend *backend, GScanContext *context, const bin_t *data, phys_t dlen) +{ + const group_manager_avx2_t *manager; /* Accès simplifié */ + + register __m256i zero asm("ymm11"); /* Constante 0 sur 256 bits */ + size_t k; /* Boucle de parcours #1 */ + grouped_strings_avx2_t group; /* Copie pour accès locaux */ + + register __m256i R asm("ymm12"); /* Résultats courants */ + register __m256i found_masks asm("ymm10"); /* Vérifications accélérées */ + + //__m256i pre_shift_mask; /* Préparation de décalage */ + //phys_t i; /* Boucle de parcours #2 */ + + + + + const bin_t *iter; + const bin_t *maxiter; + //phys_t i; /* Boucle de parcours #2 */ + + volatile register __m256i xxxx; /* Test de correspondances */ + + + __m256i test; /* Test de correspondances */ + __m256i test2; /* Test de correspondances */ + __m256i status; /* Statut d'une comparaison */ + + int masks[10]; + + int mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + + int ret; + + //return; + + /* Initialisations diverses */ + + manager = &backend->manager_avx2; + + zero = _mm256_set1_epi16(0); + + asm volatile ("nop;nop;nop;nop;nop;nop;nop;nop;nop;"); + + xxxx = _mm256_set1_epi8(~1); + + asm volatile ("nop;nop;nop;nop;nop;nop;nop;nop;nop;"); + + /* Recherches des chaînes de moins de 8 caractères */ + + printf(" --- manager->count_8: %zu\n", manager->count_8); + + ret = 0; + + for (k = 0; k < manager->count_8; k++) + { + memcpy(&group, manager->strings_8[k], sizeof(grouped_strings_avx2_t)); + + //printf(" --- group.used: %zu\n", group.used); + + + asm volatile + ( + /* + * R = _mm256_set1_epi8(~1); + * + */ + + "movabs $0xfefefefefefefefe, %%rax ; " + "vpbroadcastq %%rax, %[STATE] ; " + + /* + * + */ + + "vmovdqa %[FOUND_SRC], %[FOUND_DST] ; " + + : [STATE] "=v"(R), + [FOUND_DST] "=v"(found_masks) + : [FOUND_SRC] "m"(group.found_masks) + : "memory", "rax" + + ); + + + + + //pre_shift_mask = _mm256_set1_epi8(0xef); + + maxiter = data + dlen; + + + + for (iter = data; (iter + 10) < maxiter; iter += 10) + { + + //printf("--- %llx <-> %c\n", (unsigned long long)(iter - data), *iter); + + + asm volatile + ( +#if 0 + + /* + * R = _mm256_or_si256(R, group.pattern_masks[data[i]]); + * + * Latency : 1-9 + * Throughput : 0.5 + * #Uops : 1-2 + * Port Usage : 1*p015+1*p23 + * + */ + + "vpor %[PATTERN], %[STATE], %[STATE] ; " + +#else + + /* + * %ymm = group.pattern_masks[data[i]]; + * + * Latency : 5-8 + * Throughput : 0.5 + * #Uops : 1 + * Port Usage : 1*p23 + * + */ + + "vmovdqa %[PATTERN0], %%ymm0 ; " + "vmovdqa %[PATTERN1], %%ymm1 ; " + "vmovdqa %[PATTERN2], %%ymm2 ; " + "vmovdqa %[PATTERN3], %%ymm3 ; " + "vmovdqa %[PATTERN4], %%ymm4 ; " + "vmovdqa %[PATTERN5], %%ymm5 ; " + "vmovdqa %[PATTERN6], %%ymm6 ; " + "vmovdqa %[PATTERN7], %%ymm7 ; " + "vmovdqa %[PATTERN7], %%ymm8 ; " + "vmovdqa %[PATTERN7], %%ymm9 ; " + + /* + * R = _mm256_or_si256(R, %ymm); + * + * Latency : 1 + * Throughput : 0.33 + * #Uops : 1 + * Port Usage : 1*p015 + * + */ + + "vpor %%ymm0, %[STATE], %[STATE] ; " + +#endif + + /* + * R = _mm256_add_epi8(R, R); + * + * Latency : 1 + * Throughput : 0.3 + * #Uops : 1 + * Port Usage : 1*p015 + * + */ + + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + /* + * test = _mm256_and_si256(R, group.found_masks); + * + * Latency : 1 + * Throughput : 0.33 + * #Uops : 1 + * Port Usage : 1*p015 + * + */ + + "vpand %[FOUND], %[STATE], %%ymm0 ; " + + /* Déroulemets... */ + + "vpor %%ymm1, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm2, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm3, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm4, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm5, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm6, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm7, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm8, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpor %%ymm9, %[STATE], %[STATE] ; " + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + "vpand %[FOUND], %[STATE], %%ymm1 ; " + "vpand %[FOUND], %[STATE], %%ymm2 ; " + "vpand %[FOUND], %[STATE], %%ymm3 ; " + "vpand %[FOUND], %[STATE], %%ymm4 ; " + "vpand %[FOUND], %[STATE], %%ymm5 ; " + "vpand %[FOUND], %[STATE], %%ymm6 ; " + "vpand %[FOUND], %[STATE], %%ymm7 ; " + "vpand %[FOUND], %[STATE], %%ymm8 ; " + "vpand %[FOUND], %[STATE], %%ymm9 ; " + + + + + + /* + * status = _mm256_cmpeq_epi8(test, zero); + * + * Latency : 1 + * Throughput : 0.5 + * #Uops : 1 + * Port Usage : 1*p01 + * + */ + + "vpcmpeqb %%ymm0, %[NUL], %%ymm0 ; " + + /* + * mask = _mm256_movemask_epi8(status); + * + * Latency : <5 + * Throughput : 1 + * #Uops : 1 + * Port Usage : 1*p0 + * + */ + + "vpmovmskb %%ymm0, %[MASK0] ; " + + + + + + "vpcmpeqb %%ymm1, %[NUL], %%ymm1 ; " + "vpcmpeqb %%ymm2, %[NUL], %%ymm2 ; " + "vpcmpeqb %%ymm3, %[NUL], %%ymm3 ; " + "vpcmpeqb %%ymm4, %[NUL], %%ymm4 ; " + "vpcmpeqb %%ymm5, %[NUL], %%ymm5 ; " + "vpcmpeqb %%ymm6, %[NUL], %%ymm6 ; " + "vpcmpeqb %%ymm7, %[NUL], %%ymm7 ; " + "vpcmpeqb %%ymm8, %[NUL], %%ymm8 ; " + "vpcmpeqb %%ymm9, %[NUL], %%ymm9 ; " + + + "vpmovmskb %%ymm1, %[MASK1] ; " + "vpmovmskb %%ymm2, %[MASK2] ; " + "vpmovmskb %%ymm3, %[MASK3] ; " + "vpmovmskb %%ymm4, %[MASK4] ; " + "vpmovmskb %%ymm5, %[MASK5] ; " + "vpmovmskb %%ymm6, %[MASK6] ; " + "vpmovmskb %%ymm7, %[MASK7] ; " + "vpmovmskb %%ymm8, %[MASK8] ; " + "vpmovmskb %%ymm9, %[MASK9] ; " + + + + + + + + + + + //"vmovdqa %%ymm7, %[OUTPUT] ; " + + //"vmovdqa %%ymm8, %[OUTPUT2] ; " + + : [STATE] "+v"(R), + [OUTPUT] "=v"(test), + [OUTPUT2] "=v"(test2), + [MASK0] "=r"(mask), + [MASK1] "=r"(mask), + [MASK2] "=r"(mask), + [MASK3] "=r"(mask), + [MASK4] "=r"(mask), + [MASK5] "=r"(mask), + [MASK6] "=r"(mask), + [MASK7] "=r"(mask), + [MASK8] "=r"(mask), + [MASK9] "=r"(mask), + [NUL] "+v"(zero) + : [PATTERN0] "m"(group./*manager->strings_8[k]->*/pattern_masks[*iter]), + [PATTERN1] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 1)]), + [PATTERN2] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 2)]), + [PATTERN3] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 3)]), + [PATTERN4] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 4)]), + [PATTERN5] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 5)]), + [PATTERN6] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 6)]), + [PATTERN7] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 7)]), + [PATTERN8] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 8)]), + [PATTERN9] "m"(group./*manager->strings_8[k]->*/pattern_masks[*(iter + 9)]), + [FOUND] "v"(found_masks) + : "memory", "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7", "ymm8", "ymm9" + + ); + + + /* + printf(" test: %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx ... %02hhx %02hhx %02hhx %02hhx\n", + ((uint8_t *)&test)[0], + ((uint8_t *)&test)[1], + ((uint8_t *)&test)[2], + ((uint8_t *)&test)[3], + ((uint8_t *)&test)[4], + ((uint8_t *)&test)[5], + ((uint8_t *)&test)[6], + ((uint8_t *)&test)[7], + ((uint8_t *)&test)[16], + ((uint8_t *)&test)[17], + ((uint8_t *)&test)[18], + ((uint8_t *)&test)[19]); + + printf(" test2: %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx ... %02hhx %02hhx %02hhx %02hhx\n", + ((uint8_t *)&test2)[0], + ((uint8_t *)&test2)[1], + ((uint8_t *)&test2)[2], + ((uint8_t *)&test2)[3], + ((uint8_t *)&test2)[4], + ((uint8_t *)&test2)[5], + ((uint8_t *)&test2)[6], + ((uint8_t *)&test2)[7], + ((uint8_t *)&test2)[16], + ((uint8_t *)&test2)[17], + ((uint8_t *)&test2)[18], + ((uint8_t *)&test2)[19]); + */ + +#if 0 + //printf(" > %c\n", data[i]); + + R = _mm256_or_si256(R, group.pattern_masks[*iter]); + + //printf("group pattern: %hhx\n", *((uint8_t *)&group.pattern_masks[data[i]])); + + //printf("R: %hhx\n", *((uint8_t *)&R)); + + //R = _mm256_and_si256(R, pre_shift_mask); + + //printf("R after and: %hhx\n", *((uint8_t *)&R)); + + R = _mm256_add_epi8(R, R); + //R = _mm256_slli_si256(R, 1); + + //printf("R after shift: %hhx\n", *((uint8_t *)&R)); + + test = _mm256_and_si256(R, group.found_masks); + +#if 1 + status = _mm256_cmpeq_epi8(test, zero); + + mask = _mm256_movemask_epi8(status); +#else + //mask = _mm256_movemask_epi8(test) ^ 0xffffffff; + mask = _mm256_movemask_epi8(test); +#endif + + +#endif + + + //printf(" mask : %x\n", mask); + + if (mask != 0) + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == 1) + { + //assert((i + 1) >= group.m[j]); + + /** TODO : update call + g_scan_context_register_atom_match(context, + group.found_id[j], + (iter - data) + 1 - group.m[j]); + **/ + + } + + mask >>= 1; + + } + + } + + + + + +#if 0 + for (; iter < maxiter; iter++) + { + + //printf("--- %llx <-> %c\n", (unsigned long long)(iter - data), *iter); + + + asm volatile + ( + /* + * R = _mm256_or_si256(R, group.pattern_masks[data[i]]); + * + * Latency : 1 + * Throughput : 0.33 + * #Uops : 1 + * Port Usage : 1*p015 + * + */ + + "vpor %[PATTERN], %[STATE], %[STATE] ; " + + /* + * R = _mm256_add_epi8(R, R); + * + * Latency : 1 + * Throughput : 0.3 + * #Uops : 1 + * Port Usage : 1*p015 + * + */ + + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + /* + * test = _mm256_and_si256(R, group.found_masks); + * + * Latency : 1 + * Throughput : 0.33 + * #Uops : 1 + * Port Usage : 1*p015 + * + */ + + "vpand %[FOUND], %[STATE], %%ymm7 ; " + + /* + * status = _mm256_cmpeq_epi8(test, zero); + * + * Latency : 1 + * Throughput : 0.5 + * #Uops : 1 + * Port Usage : 1*p01 + * + */ + + "vpcmpeqb %%ymm7, %[NUL], %%ymm8 ; " + + /* + * mask = _mm256_movemask_epi8(status); + * + * Latency : <5 + * Throughput : 1 + * #Uops : 1 + * Port Usage : 1*p0 + * + */ + + "vpmovmskb %%ymm8, %[MASK0] ; " + + + //"vmovdqa %%ymm7, %[OUTPUT] ; " + + //"vmovdqa %%ymm8, %[OUTPUT2] ; " + + : [STATE] "+v"(R), + [OUTPUT] "=v"(test), + [OUTPUT2] "=v"(test2), + [MASK0] "=r"(mask), + [NUL] "+v"(zero) + : [PATTERN] "m"(group./*manager->strings_8[k]->*/pattern_masks[*iter]), + [FOUND] "v"(found_masks) + : "memory", "ymm7", "ymm8" + + ); + + + /* + printf(" test: %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx ... %02hhx %02hhx %02hhx %02hhx\n", + ((uint8_t *)&test)[0], + ((uint8_t *)&test)[1], + ((uint8_t *)&test)[2], + ((uint8_t *)&test)[3], + ((uint8_t *)&test)[4], + ((uint8_t *)&test)[5], + ((uint8_t *)&test)[6], + ((uint8_t *)&test)[7], + ((uint8_t *)&test)[16], + ((uint8_t *)&test)[17], + ((uint8_t *)&test)[18], + ((uint8_t *)&test)[19]); + + printf(" test2: %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx %02hhx ... %02hhx %02hhx %02hhx %02hhx\n", + ((uint8_t *)&test2)[0], + ((uint8_t *)&test2)[1], + ((uint8_t *)&test2)[2], + ((uint8_t *)&test2)[3], + ((uint8_t *)&test2)[4], + ((uint8_t *)&test2)[5], + ((uint8_t *)&test2)[6], + ((uint8_t *)&test2)[7], + ((uint8_t *)&test2)[16], + ((uint8_t *)&test2)[17], + ((uint8_t *)&test2)[18], + ((uint8_t *)&test2)[19]); + */ + +#if 0 + //printf(" > %c\n", data[i]); + + R = _mm256_or_si256(R, group.pattern_masks[*iter]); + + //printf("group pattern: %hhx\n", *((uint8_t *)&group.pattern_masks[data[i]])); + + //printf("R: %hhx\n", *((uint8_t *)&R)); + + //R = _mm256_and_si256(R, pre_shift_mask); + + //printf("R after and: %hhx\n", *((uint8_t *)&R)); + + R = _mm256_add_epi8(R, R); + //R = _mm256_slli_si256(R, 1); + + //printf("R after shift: %hhx\n", *((uint8_t *)&R)); + + test = _mm256_and_si256(R, group.found_masks); + +#if 1 + status = _mm256_cmpeq_epi8(test, zero); + + mask = _mm256_movemask_epi8(status); +#else + //mask = _mm256_movemask_epi8(test) ^ 0xffffffff; + mask = _mm256_movemask_epi8(test); +#endif + + +#endif + + + //printf(" mask : %x\n", mask); + + if (mask != 0) + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == 1) + { + //assert((i + 1) >= group.m[j]); + + /** TODO : update call + g_scan_context_register_atom_match(context, + group.found_id[j], + (iter - data) + 1 - group.m[j]); + **/ + + } + + mask >>= 1; + + } + + } + +#endif + + + } + + +} + + + + + + + + + + + + + + +#if 0 + + +#if 0 + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* content = données binaires à analyser. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void run_scan_avx2(const GBitapBackend *backend, GScanContext *context, GBinContent *content) +{ + const group_manager_avx2_t *manager; /* Accès simplifié */ + + grouped_strings_avx2_t groups[10]; /* Copie pour accès locaux */ + + + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ + __m256i zero; /* Constante 0 sur 256 bits */ + size_t k; /* Boucle de parcours #1 */ + + grouped_strings_avx2_t group; /* Copie pour accès locaux */ + __m256i R; /* Résultats courants */ + __m256i pre_shift_mask; /* Préparation de décalage */ + phys_t i; /* Boucle de parcours #2 */ + __m256i test; /* Test de correspondances */ + __m256i status; /* Statut d'une comparaison */ + int mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + uint32_t leaves; + int ret; + + + phys_t old_i; + phys_t p; + + //return; + + /* Initialisations diverses */ + + manager = &backend->manager_avx2; + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + zero = _mm256_set1_epi16(0); + + /* Recherches des chaînes de moins de 8 caractères */ + + printf(" --- manager->count_8: %zu\n", manager->count_8); + + ret = 0; + + //for (k = 0; k < manager->count_8; k++) + // memcpy(&groups[k], manager->strings_8[k], sizeof(grouped_strings_avx2_t)); + + + for (i = 0; i < dlen; ) + { + + //printf(" --- %llx\n", (unsigned long long)i); + + p = i + 4096; + + if (p > dlen) + p = dlen; + + old_i = i; + + printf("old_i: %llx\n", (unsigned long long)old_i); + + for (k = 0; k < manager->count_8; k++) + { + + group = *manager->strings_8[k]; + + R = group.R; + + for (i = old_i ; i < p; i++) + { + + //group = &groups[k]; + + //printf(" k: %zu i: %llx\n", k, (unsigned long long)i); + + //R = group.R;//_mm256_set1_epi8(~1); + + R = _mm256_or_si256(R, group.pattern_masks[data[i]]); + + R = _mm256_add_epi8(R, R); + + test = _mm256_and_si256(R, group.found_masks); + +#if 0 + status = _mm256_cmpeq_epi8(test, zero); + + mask = _mm256_movemask_epi8(status); +#else + //mask = _mm256_movemask_epi8(test) ^ 0xffffffff; + mask = _mm256_movemask_epi8(test); +#endif + + if (mask != 0xffffffff) + { + leaves = group.leaves; + + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == 0) + { + if (leaves & 0x1) //group.leaves & (1u << j)) + ;//define_full_match_avx2(backend, context, content, &group, j, i + 1); + + } + + mask >>= 1; + + leaves >>= 1; + + } + + } + + group.R = R;//_mm256_set1_epi8(~1); + + memcpy(manager->strings_8[k], &group, sizeof(grouped_strings_avx2_t)); + + } + + + } + + } + + printf("oh: %d\n", ret); + + +} + + +#else + + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* content = données binaires à analyser. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void run_scan_avx2(const GBitapBackend *backend, GScanContext *context, GBinContent *content) +{ + const group_manager_avx2_t *manager; /* Accès simplifié */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ + __m256i zero; /* Constante 0 sur 256 bits */ + size_t k; /* Boucle de parcours #1 */ + grouped_strings_avx2_t group; /* Copie pour accès locaux */ + __m256i R; /* Résultats courants */ + __m256i pre_shift_mask; /* Préparation de décalage */ + phys_t i; /* Boucle de parcours #2 */ + __m256i test; /* Test de correspondances */ + __m256i status; /* Statut d'une comparaison */ + int mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + uint32_t leaves; + int ret; + + //return; + + /* Initialisations diverses */ + + manager = &backend->manager_avx2; + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + zero = _mm256_set1_epi16(0); + + /* Recherches des chaînes de moins de 8 caractères */ + + printf(" --- manager->count_8: %zu\n", manager->count_8); + + ret = 0; + + for (k = 0; k < manager->count_8; k++) + { + memcpy(&group, manager->strings_8[k], sizeof(grouped_strings_avx2_t)); + + //printf(" --- group.used: %zu\n", group.used); + + R = _mm256_set1_epi8(~1); + + //pre_shift_mask = _mm256_set1_epi8(0xef); + + for (i = 0; i < dlen; ++i) + { + //printf(" > %c\n", data[i]); + + R = _mm256_or_si256(R, group.pattern_masks[data[i]]); + + //printf("group pattern: %hhx\n", *((uint8_t *)&group.pattern_masks[data[i]])); + + //printf("R: %hhx\n", *((uint8_t *)&R)); + + //R = _mm256_and_si256(R, pre_shift_mask); + + //printf("R after and: %hhx\n", *((uint8_t *)&R)); + + R = _mm256_add_epi8(R, R); + //R = _mm256_slli_si256(R, 1); + + //printf("R after shift: %hhx\n", *((uint8_t *)&R)); + + test = _mm256_and_si256(R, group.found_masks); + +#if 0 + status = _mm256_cmpeq_epi8(test, zero); + + mask = _mm256_movemask_epi8(status); +#else + //mask = _mm256_movemask_epi8(test) ^ 0xffffffff; + mask = _mm256_movemask_epi8(test); +#endif + + if (mask != 0xffffffff) + { + leaves = group.leaves; + + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == 0) + { + //assert((i + 1) >= group.m[j]); + + if (leaves & 0x1) //group.leaves & (1u << j)) + define_full_match_avx2(backend, context, content, &group, j, i + 1); + //else + //{ + // ret++; + //printf("%x\n", (unsigned int)i + 1); + //} + //else + // g_scan_context_register_sub_match(context, group.found_id[j], i + 1 - group.m[j]); + + } + + mask >>= 1; + + leaves >>= 1; + + } + + } + + } + + } + + printf("oh: %d\n", ret); + + /* Recherches des chaînes de moins de 16 caractères */ + + for (k = 0; k < manager->count_16; k++) + { + memcpy(&group, manager->strings_16[k], sizeof(grouped_strings_avx2_t)); + + R = _mm256_set1_epi16(~1); + + for (i = 0; i < dlen; ++i) + { + R = _mm256_or_si256(R, group.pattern_masks[data[i]]); + R = _mm256_slli_epi16(R, 1); + + test = _mm256_and_si256(R, group.found_masks); + + status = _mm256_cmpeq_epi16(test, zero); + + mask = _mm256_movemask_epi8(status); + + if (mask != 0) + for (j = 0; j < group.used; j++) + { + if (mask & 0x3) + { + assert((i + 1) >= group.m[j]); + + if (group.leaves & (1llu << j)) + define_full_match_avx2(backend, context, content, &group, j, i + 1); + else + ;//g_scan_context_register_sub_match(context, group.found_id[j], i + 1 - group.m[j]); + + } + + mask >>= 2; + + } + + } + + } + +} + +#endif + + + +#endif + + + + + + + + + + + + + + + + + +#endif + + + +/* ---------------------------------------------------------------------------------- */ +/* OPTIMISATIONS POUR ARCHITECTURE AVX512 */ +/* ---------------------------------------------------------------------------------- */ + + +/** + * Cf. https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#techs=AVX_512 + * - https://agner.org/optimize/ + * - https://uops.info/table.html + */ + +#ifdef HAVE_AVX512_F + +/****************************************************************************** +* * +* Paramètres : strings = ensemble de groupes constitués. [OUT] * +* count = nombre de groupes courant. [OUT] * +* * +* Description : Indique la valeur portée par une expression rationnelle. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void extend_grouped_strings_avx512(grouped_strings_avx512_t ***strings, size_t *count) +{ + grouped_strings_avx512_t *new; /* Zone supplémentaire */ + size_t i; /* Boucle de parcours */ + + /* Définition d'un nouvel élément vierge */ + + new = aligned_alloc(0x1000, sizeof(grouped_strings_avx512_t)); + + for (i = 0; i < 256; i++) + new->pattern_masks[i] = _mm512_set1_epi8(~0); + + new->found_masks = _mm512_set1_epi8(~0); + + new->R = _mm512_set1_epi8(~1); + + for (i = 0; i < 64; i++) + { + new->m[i] = 0; + + new->found_id[i] = INVALID_PATTERN_ID; + + } + + new->available = 64; + new->used = 0; + + /* Inscription */ + + *strings = realloc(*strings, ++(*count) * sizeof(grouped_strings_avx512_t *)); + + (*strings)[*count - 1] = new; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = contexte de l'analyse à mener. * +* plain = chaîne de caractères classique à intégrer. * +* plen = taille de cette chaîne. * +* * +* Description : Inscrit dans le moteur une chaîne de caractères à rechercher.* +* * +* Retour : Indice de résultats pour le motif. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static patid_t enroll_plain_pattern_avx512(GBitapBackend *backend, GScanContext *context, const bin_t *plain, size_t plen) +{ + patid_t result; /* Identifiant à retourner */ + grouped_strings_avx512_t ***strings; /* Groupe de chaînes visé */ + size_t *count; /* Taille de ce groupe */ + grouped_strings_avx512_t *last; /* Dernier groupe à remplir */ + size_t n; /* Indice dans le groupe */ + size_t i; /* Boucle de parcours */ + __m512i *letter; /* Lettre à marquer */ + + /* Sélection du groupe de travail adéquat */ + + strings = &backend->manager_avx512.strings_8; + count = &backend->manager_avx512.count_8; + + /* Préparation de la place nécessaire */ + + if (*count == 0) + { + extend_grouped_strings_avx512(strings, count); + + last = (*strings)[0]; + + } + + else + { + last = (*strings)[*count - 1]; + + if (last->used == last->available) + { + extend_grouped_strings_avx512(strings, count); + last = (*strings)[*count - 1]; + } + + } + + /* Intégration d'une nouvelle chaîne */ + + n = last->used++; + + last->m[n] = plen; + + result = 0; // FIXME g_scan_context_get_new_pattern_id(context); + + last->found_id[n] = result; + + ((uint8_t *)&last->found_masks)[n] = (1 << plen); + + for (i = 0; i < plen; i++) + { + letter = last->pattern_masks + plain[i]; + ((uint8_t *)letter)[n] &= ~(1 << i); + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* data = données à analyser. * +* dlen = quantité de ces données. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void run_scan_avx512(const GBitapBackend *backend, GScanContext *context, const bin_t *data, phys_t dlen) +{ + const group_manager_avx512_t *manager; /* Accès simplifié */ + + //register __m512i zero asm("zmm19"); /* Constante 0 sur 512 bits */ + + //__m512i shift8_mask; /* Masque pour décalage manuel */ + + + size_t k; /* Boucle de parcours #1 */ + /*__attribute__((aligned(0x1000)))*/ grouped_strings_avx512_t group; /* Copie pour accès locaux */ + //void *grpptr; + //grouped_strings_avx512_t *_group; /* Copie pour accès locaux */ + + int ret; + + + register __m512i R asm("zmm28"); /* Résultats courants */ + register __m512i found_masks asm("zmm21"); /* Vérifications accélérées */ + + + register __mmask64 test_mask asm("k6"); + + + register const bin_t *iter asm("rsi"); + register const bin_t *maxiter/* asm("rdi")*/; + //phys_t i; /* Boucle de parcours #2 */ + + + //__m512i test; + + __mmask64 mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + + /* Initialisations diverses */ + + manager = &backend->manager_avx512; + + + + + /* Recherches des chaînes de moins de 8 caractères */ + + //asm volatile ("nop; nop; nop; nop; nop; nop; nop; "); + + //zero = _mm512_set1_epi8(0); + + //asm volatile ("nop; nop; nop; nop; nop; nop; nop; "); + + //shift8_mask = _mm512_set1_epi8(0x7f); + + + +#define WORK_ON_COPY + + for (k = 0; k < manager->count_8; k++) + { +#ifdef WORK_ON_COPY + memcpy(&group, manager->strings_8[k], sizeof(grouped_strings_avx512_t)); + +#else + + grpptr = alloca(sizeof(grouped_strings_avx512_t) + 0x1000); + + _group = grpptr + 0x1000 - (((unsigned long)grpptr) % 0x1000); + + //_group = manager->strings_8[k]; + + memcpy(_group, manager->strings_8[k], sizeof(grouped_strings_avx512_t)); + + ret = mlock(_group, sizeof(grouped_strings_avx512_t)); + + printf("ret = %d\n", ret); +#endif + + + + //printf(" --- group %p -- used: %zu (sz: %zu)\n", &group, group.used, sizeof(grouped_strings_avx512_t)); + //printf(" --- group.used: %zu (sz: %zu)\n", group.used, sizeof(grouped_strings_avx512_t)); + + + asm volatile + ( + /* + * R = _mm512_set1_epi8(~1); + * + */ + + "movabs $0xfefefefefefefefe, %%rax ; " + "vpbroadcastq %%rax, %[STATE] ; " + + "movabs $0xffffffffffffffff, %%rax ; " + "kmovq %%rax, %[KMASK] ; " + + /* + * + */ + + "vmovdqa64 %[FOUND_SRC], %[FOUND_DST] ; " + + : [STATE] "=v"(R), + [KMASK] "=Yk"(test_mask), + [FOUND_DST] "=v"(found_masks) +#ifdef WORK_ON_COPY + : [FOUND_SRC] "m"(group.found_masks) +#else + : [FOUND_SRC] "m"(_group->found_masks) +#endif + : "memory", "rax" + + ); + + + + + + + + //for (i = 0; i < dlen; i++) + + maxiter = data + dlen; + + for (iter = data; iter < maxiter; iter++) + { + + //printf("--- %llx <-> %c\n", (unsigned long long)(iter - data), *iter); + + + asm volatile goto + ( + /* + * R = _mm512_or_si512(R, group.pattern_masks[*iter]); + * + * Latency : 1-9 + * Throughput : 0.5 + * #Uops : 1-2 + * Port Usage : 1*p05+1*p23 + * + */ + + "vpord %[PATTERN], %[STATE], %[STATE] ; " + + /* + * R = _mm512_add_epi8(R, R); + * + * Latency : 1 + * Throughput : 0.5 + * #Uops : 1 + * Port Usage : 1*p05 + * + */ + + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + /* + * mask = _mm512_test_epi8_mask(R, group.found_masks); + * + * Latency : 3 + * Throughput : 1 + * #Uops : 2 + * Port Usage : 1*p23+1*p5 + * + */ + + /****************************** + * Version 0 + + ******************/ + + //"vptestmb %[FOUND], %[STATE], %%k7 ; " + + /****************************** + * Version 1 + + "vmovdqa64 %[STATE], %%zmm12 ; " + + "vptestmb %[FOUND], %%zmm12, %%k7 ; " + + ******************/ + + /****************************** + * Version 2 + + "vpandd %[STATE], %[FOUND], %%zmm12 ; " + + "vpcmpneqb %[NUL], %%zmm12, %%k7 ; " + + ******************/ + + + "vmovdqa64 %[STATE], %%zmm12 ; " + + "vptestmb %[FOUND], %%zmm12, %%k7 ; " + + + "ktestq %[KMASK], %%k7 ; " + + "jc %l[next_iter] ; " + + + + + + /* + * (suite) + * + * Latency : 3 + * Throughput : 1 + * #Uops : 1 + * Port Usage : 1*p5 + * + */ + + "kmovq %%k7, %[MASK0] ; " + + //"vmovdqa64 %%zmm12, %[OUTPUT] ; " + + //"nop; nop; nop; nop; nop; nop; nop; nop; " + //"nop; nop; nop; nop; nop; nop; nop; nop; " + + : [STATE] "+v"(R), + //[OUTPUT] "=v"(test), + [MASK0] "=r"(mask) + //[NUL] "=v"(zero) +#ifdef WORK_ON_COPY + : [PATTERN] "m"(group.pattern_masks[*iter]), +#else + : [PATTERN] "m"(_group->pattern_masks[*iter]), +#endif + [FOUND] "v"(found_masks), + [KMASK] "Yk"(test_mask) + : "memory", "k7", "zmm12" + : next_iter + + ); + + + + + /* + printf(" found mask: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&group.found_masks)[0], + ((uint8_t *)&group.found_masks)[1], + ((uint8_t *)&group.found_masks)[2], + ((uint8_t *)&group.found_masks)[3], + ((uint8_t *)&group.found_masks)[4], + ((uint8_t *)&group.found_masks)[5], + ((uint8_t *)&group.found_masks)[6], + ((uint8_t *)&group.found_masks)[7]); + + + printf(" test: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&test)[0], + ((uint8_t *)&test)[1], + ((uint8_t *)&test)[2], + ((uint8_t *)&test)[3], + ((uint8_t *)&test)[4], + ((uint8_t *)&test)[5], + ((uint8_t *)&test)[6], + ((uint8_t *)&test)[7]); + + + printf(" -> mask: 0x%llx\n", (unsigned long long)mask); + */ + + +#ifdef WORK_ON_COPY + + //if (mask != 0xffffffffffffffffllu) + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == 0) + { + //assert((i + 1) >= group.m[j]); + + /** TODO : update call + g_scan_context_register_atom_match(context, + group.found_id[j], + (iter - data) + 1 - group.m[j]); + **/ + + } + + mask >>= 1; + + } + +#else + +# error "WEFEF" + + if (mask != 0xffffffffffffffffllu) + for (j = 0; j < _group->used; j++) + { + if ((mask & 0x1) == 0) + { + //assert((i + 1) >= group.m[j]); + + /** TODO : update call + g_scan_context_register_atom_match(context, + _group->found_id[j], + (iter - data) + 1 - _group->m[j]); + **/ + + } + + mask >>= 1; + + } + +#endif + + + next_iter: + + //; + + //iter++; + + } + + } + +} + + + + + + + + + + + +#if 0 + + + + + + + + + + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* content = données binaires à analyser. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void run_scan_avx512____good_asm_perfs(const GBitapBackend *backend, GScanContext *context, GBinContent *content) +{ + const group_manager_avx512_t *manager; /* Accès simplifié */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ + + + //__m512i shift8_mask; /* Masque pour décalage manuel */ + + + size_t k; /* Boucle de parcours #1 */ + grouped_strings_avx512_t group; /* Copie pour accès locaux */ + + register __m512i found_masks asm("zmm21"); /* Vérifications accélérées */ + + + //register volatile __m512i zero/* asm("zmm19")*/; /* Constante 0 sur 512 bits */ + register __m512i R asm("zmm28"); /* Résultats courants */ + + //int counter; + + const bin_t *iter; + const bin_t *maxiter; + //phys_t i; /* Boucle de parcours #2 */ + + + __m512i test; + + __mmask64 mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + + //register __m512i z30 asm("zmm30"); + + + //return; + + + //counter = 0; + + //return; + + /* Initialisations diverses */ + + manager = &backend->manager_avx512; + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + /* Recherches des chaînes de moins de 8 caractères */ + + printf(" --- manager512->count_8: %zu\n", manager->count_8); + + asm volatile ("nop; nop; nop; nop; nop; nop; nop; "); + + //zero = _mm512_set1_epi8(0); + + asm volatile ("nop; nop; nop; nop; nop; nop; nop; "); + + //shift8_mask = _mm512_set1_epi8(0x7f); + + + for (k = 0; k < manager->count_8; k++) + { + memcpy(&group, manager->strings_8[k], sizeof(grouped_strings_avx512_t)); + + + + + //printf(" --- group %p -- used: %zu (sz: %zu)\n", &group, group.used, sizeof(grouped_strings_avx512_t)); + //printf(" --- group.used: %zu (sz: %zu)\n", group.used, sizeof(grouped_strings_avx512_t)); + + + asm volatile + ( + /* + * R = _mm512_set1_epi8(~1); + * + */ + + "movabs $0xfefefefefefefefe, %%rax ; " + "vpbroadcastq %%rax, %[STATE] ; " + + /* + * + */ + + "vmovdqa64 %[FOUND_SRC], %[FOUND_DST] ; " + + : [STATE] "=v"(R), + [FOUND_DST] "=v"(found_masks) + : [FOUND_SRC] "m"(group.found_masks) + : "memory", "rax" + + ); + + + + + + + + //for (i = 0; i < dlen; i++) + + maxiter = data + dlen; + + for (iter = data; iter < maxiter; iter++) + { + + //printf("--- %llx <-> %c\n", (unsigned long long)(iter - data), *iter); + + + asm volatile + ( + + /* + * R = _mm512_or_si512(R, group.pattern_masks[*iter]); + * + * Latency : 1-9 + * Throughput : 0.5 + * #Uops : 1-2 + * Port Usage : 1*p05+1*p23 + * + */ + + "vpord %[PATTERN], %[STATE], %[STATE] ; " + + /* + * R = _mm512_add_epi8(R, R); + * + * Latency : 1 + * Throughput : 0.5 + * #Uops : 1 + * Port Usage : 1*p05 + * + */ + + "vpaddb %[STATE], %[STATE], %[STATE] ; " + + /* + * mask = _mm512_test_epi8_mask(R, group.found_masks); + * + * Latency : 3 + * Throughput : 1 + * #Uops : 2 + * Port Usage : 1*p23+1*p5 + * + */ + + /****************************** + * Version 0 + + ******************/ + + "vptestmb %[FOUND], %[STATE], %%k7 ; " + + /****************************** + * Version 1 + + "vmovdqa64 %[STATE], %%zmm12 ; " + + "vptestmb %[FOUND], %%zmm12, %%k0 ; " + + ******************/ + + /****************************** + * Version 2 + + "vpandd %[STATE], %[FOUND], %%zmm12 ; " + + "vpcmpneqb %[NUL], %%zmm12, %%k7 ; " + + ******************/ + + /* + * (suite) + * + * Latency : 3 + * Throughput : 1 + * #Uops : 1 + * Port Usage : 1*p5 + * + */ + + "kmovq %%k7, %[MASK0] ; " + + //"vmovdqa64 %%zmm12, %[OUTPUT] ; " + + //"nop; nop; nop; nop; nop; nop; nop; nop; " + //"nop; nop; nop; nop; nop; nop; nop; nop; " + + : [STATE] "+v"(R), + [OUTPUT] "=v"(test), + [MASK0] "=r"(mask)/*, + [NUL] "+v"(zero)*/ + : [PATTERN] "v"(group.pattern_masks[*iter]), + [FOUND] "v"(found_masks) + : "memory", "k0", "zmm12" + + ); + + + + + /* + printf(" found mask: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&group.found_masks)[0], + ((uint8_t *)&group.found_masks)[1], + ((uint8_t *)&group.found_masks)[2], + ((uint8_t *)&group.found_masks)[3], + ((uint8_t *)&group.found_masks)[4], + ((uint8_t *)&group.found_masks)[5], + ((uint8_t *)&group.found_masks)[6], + ((uint8_t *)&group.found_masks)[7]); + + + printf(" test: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&test)[0], + ((uint8_t *)&test)[1], + ((uint8_t *)&test)[2], + ((uint8_t *)&test)[3], + ((uint8_t *)&test)[4], + ((uint8_t *)&test)[5], + ((uint8_t *)&test)[6], + ((uint8_t *)&test)[7]); + + + printf(" -> mask: 0x%llx\n", (unsigned long long)mask); + */ + +#if 0 + + /* + printf(" R: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&R)[0], + ((uint8_t *)&R)[1], + ((uint8_t *)&R)[2], + ((uint8_t *)&R)[3], + ((uint8_t *)&R)[4], + ((uint8_t *)&R)[5], + ((uint8_t *)&R)[6], + ((uint8_t *)&R)[7]); + + printf(" found mask: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&group.found_masks)[0], + ((uint8_t *)&group.found_masks)[1], + ((uint8_t *)&group.found_masks)[2], + ((uint8_t *)&group.found_masks)[3], + ((uint8_t *)&group.found_masks)[4], + ((uint8_t *)&group.found_masks)[5], + ((uint8_t *)&group.found_masks)[6], + ((uint8_t *)&group.found_masks)[7]); + */ + + /* + + printf(" test: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&test)[0], + ((uint8_t *)&test)[1], + ((uint8_t *)&test)[2], + ((uint8_t *)&test)[3], + ((uint8_t *)&test)[4], + ((uint8_t *)&test)[5], + ((uint8_t *)&test)[6], + ((uint8_t *)&test)[7]); + + */ + +#endif + + + + + +# define TEST_MASK 0xffffffffffffffffllu +# define TEST_BIT 0 + + + //printf("mask: %llx\n", (unsigned long long)mask); + + + if (mask != TEST_MASK) + { + //printf("mask: %llx\n", (unsigned long long)mask); + + //counter++; + //printf("Ouhc: %p - %x\n", &group, *((uint8_t *)&mask)); + //printf("Ouhc: %x\n", 1); + //asm("vzeroupper;"); + //printf("Ouhc: %hhx\n", R[0]); + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == TEST_BIT) + { + //assert((i + 1) >= group.m[j]); + + //printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)i + 1); + printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)(iter - data) + 1); + + + } + + mask >>= 1; + //printf("> mask: %llx\n", (unsigned long long)mask); + + } + + + + } + + + + } + + //printf("%hhx\n", ((uint8_t *)&R)[0], ((uint8_t *)&mask)[0]); + + } + + //printf("counter=%d\n", counter); + + +} + + + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* content = données binaires à analyser. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void run_scan_avx512_best_test(const GBitapBackend *backend, GScanContext *context, GBinContent *content) +{ + const group_manager_avx512_t *manager; /* Accès simplifié */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ + + + //__m512i shift8_mask; /* Masque pour décalage manuel */ + + + size_t k; /* Boucle de parcours #1 */ + grouped_strings_avx512_t group; /* Copie pour accès locaux */ + + //register __m512i zero; /* Constante 0 sur 512 bits */ + register __m512i R; /* Résultats courants */ + + //int counter; + + const bin_t *iter; + const bin_t *maxiter; + //phys_t i; /* Boucle de parcours #2 */ + + + //__m512i test; + + __mmask64 mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + //return; + + + //counter = 0; + + //return; + + /* Initialisations diverses */ + + manager = &backend->manager_avx512; + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + /* Recherches des chaînes de moins de 8 caractères */ + + printf(" --- manager512->count_8: %zu\n", manager->count_8); + + //zero = _mm512_set1_epi8(0); + + //shift8_mask = _mm512_set1_epi8(0x7f); + + + + for (k = 0; k < manager->count_8; k++) + { + memcpy(&group, manager->strings_8[k], sizeof(grouped_strings_avx512_t)); + + //printf(" --- group %p -- used: %zu (sz: %zu)\n", &group, group.used, sizeof(grouped_strings_avx512_t)); + //printf(" --- group.used: %zu (sz: %zu)\n", group.used, sizeof(grouped_strings_avx512_t)); + + R = _mm512_set1_epi8(~1); + + + + /* vpord zmm, zmm, zmm : latence 1, 1*p05 */ + //R = _mm512_or_si512(R, group.pattern_masks[data[0]]); + + //for (i = 0; i < dlen; i++) + + maxiter = data + dlen; + + for (iter = data; iter < maxiter; iter++) + { + + //printf("--- %llx <-> %c\n", (unsigned long long)(iter - data), *iter); + + + //R = _mm512_or_si512(R, group.pattern_masks[data[i]]); + R = _mm512_or_si512(R, group.pattern_masks[*iter]); + + +#if 1 + /* vpaddb zmm, zmm, zmm : latence 1, 1*p05 */ + R = _mm512_add_epi8(R, R); +#else + /* vpandd zmm, zmm, zmm : latence 1, 1*p5 */ + R = _mm512_and_si512(R, shift8_mask); + /* vpslldq zmm, zmm, imm8 : latence 1, 1*p5 */ + R = _mm512_bslli_epi128(R, 1); + +#endif + + /* + printf(" R: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&R)[0], + ((uint8_t *)&R)[1], + ((uint8_t *)&R)[2], + ((uint8_t *)&R)[3], + ((uint8_t *)&R)[4], + ((uint8_t *)&R)[5], + ((uint8_t *)&R)[6], + ((uint8_t *)&R)[7]); + + printf(" found mask: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&group.found_masks)[0], + ((uint8_t *)&group.found_masks)[1], + ((uint8_t *)&group.found_masks)[2], + ((uint8_t *)&group.found_masks)[3], + ((uint8_t *)&group.found_masks)[4], + ((uint8_t *)&group.found_masks)[5], + ((uint8_t *)&group.found_masks)[6], + ((uint8_t *)&group.found_masks)[7]); + */ + +#if 1 + /* vptestmb k, zmm, zmm : latence 3, 1*p5 */ + mask = _mm512_test_epi8_mask(R, group.found_masks); + + + //test = _mm512_add_epi64(R, zero); + + //mask = _mm512_test_epi8_mask(test, group.found_masks); + + + + + +# define TEST_MASK 0xffffffffffffffffllu +# define TEST_BIT 0 + + /* comparaison : != */ + + +#else + /* vpandd zmm, zmm, zmm : latence 1, 1*p05 */ + test = _mm512_and_si512(R, group.found_masks); + + + printf(" test: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&test)[0], + ((uint8_t *)&test)[1], + ((uint8_t *)&test)[2], + ((uint8_t *)&test)[3], + ((uint8_t *)&test)[4], + ((uint8_t *)&test)[5], + ((uint8_t *)&test)[6], + ((uint8_t *)&test)[7]); + + /* vpmovb2m k, zmm : latence 3 (au lieu de 1 !?), 1*p0 */ + //mask = _mm512_movepi8_mask(test); + +# define TEST_MASK 0 +# define TEST_BIT 0 + + + //test = _mm512_popcnt_epi8(test); + +#endif + + + //printf(" final mask: %16llx\n", (unsigned long long)mask); + + + + //R = _mm512_or_si512(R, group.pattern_masks[data[i + 1]]); + +#if 1 + + + if (mask != TEST_MASK) + { + //counter++; + //printf("Ouhc: %p - %x\n", &group, *((uint8_t *)&mask)); + printf("Ouhc: %p\n", &group); + //printf("Ouhc: %hhx\n", R[0]); + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == TEST_BIT) + { + //assert((i + 1) >= group.m[j]); + + //printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)i + 1); + printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)(iter - data) + 1); + + + } + + mask >>= 1; + + } + + + + } + + +#else + + if (_mm512_reduce_or_epi64(test) != 0) + { + for (j = 0; j < group.used; j++) + { + if (((uint8_t *)&test)[j] == 0) + { + //assert((i + 1) >= group.m[j]); + + printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)i + 1); + + } + + + } + + } + +#endif + + + } + + //printf("%hhx\n", ((uint8_t *)&R)[0], ((uint8_t *)&mask)[0]); + + } + + //printf("counter=%d\n", counter); + + +} + + + + + +static void run_scan_avx512__saved(const GBitapBackend *backend, GScanContext *context, GBinContent *content) +{ + const group_manager_avx512_t *manager; /* Accès simplifié */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ + + + __m512i shift8_mask; /* Masque pour décalage manuel */ + + + size_t k; /* Boucle de parcours #1 */ + grouped_strings_avx512_t group; /* Copie pour accès locaux */ + + + __m512i R; /* Résultats courants */ + + //int counter; + + phys_t i; /* Boucle de parcours #2 */ + + + __m512i test; + + __mmask64 mask; /* Masque d'accès rapide */ + size_t j; /* Boucle de parcours #3 */ + + + + //counter = 0; + + //return; + + /* Initialisations diverses */ + + manager = &backend->manager_avx512; + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + /* Recherches des chaînes de moins de 8 caractères */ + + printf(" --- manager512->count_8: %zu\n", manager->count_8); + + + + shift8_mask = _mm512_set1_epi8(0x7f); + + + for (k = 0; k < manager->count_8; k++) + { + memcpy(&group, manager->strings_8[k], sizeof(grouped_strings_avx512_t)); + + //printf(" --- group %p -- used: %zu (sz: %zu)\n", &group, group.used, sizeof(grouped_strings_avx512_t)); + //printf(" --- group.used: %zu (sz: %zu)\n", group.used, sizeof(grouped_strings_avx512_t)); + + R = _mm512_set1_epi8(~1); + + /* vpord zmm, zmm, zmm : latence 1, 1*p05 */ + R = _mm512_or_si512(R, group.pattern_masks[data[0]]); + + for (i = 0; i < dlen; i++) + { + + /* + printf("--- %llx <-> %c\n", (unsigned long long)i, data[i]); + + printf(" R: %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&R)[0], + ((uint8_t *)&R)[1], + ((uint8_t *)&R)[2], + ((uint8_t *)&R)[3]); + + printf(" mask: %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&group.pattern_masks[data[i]])[0], + ((uint8_t *)&group.pattern_masks[data[i]])[1], + ((uint8_t *)&group.pattern_masks[data[i]])[2], + ((uint8_t *)&group.pattern_masks[data[i]])[3]); + */ + + //R = _mm512_or_si512(R, group.pattern_masks[data[i]]); + + /* + printf(" R: %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&R)[0], + ((uint8_t *)&R)[1], + ((uint8_t *)&R)[2], + ((uint8_t *)&R)[3]); + */ + +#if 1 + /* vpaddb zmm, zmm, zmm : latence 1, 1*p05 */ + R = _mm512_add_epi8(R, R); +#else + /* vpandd zmm, zmm, zmm : latence 1, 1*p5 */ + R = _mm512_and_si512(R, shift8_mask); + /* vpslldq zmm, zmm, imm8 : latence 1, 1*p5 */ + R = _mm512_bslli_epi128(R, 1); + +#endif + +#if 1 + /* vptestmb k, zmm, zmm : latence 3, 1*p5 */ + mask = _mm512_test_epi8_mask(R, group.found_masks); +#else + test = _mm512_and_si512(R, group.found_masks); + test = _mm512_popcnt_epi8(test); + +#endif + + /* + printf(" found mask: %hhx %hhx %hhx %hhx\n", + ((uint8_t *)&group.found_masks)[0], + ((uint8_t *)&group.found_masks)[1], + ((uint8_t *)&group.found_masks)[2], + ((uint8_t *)&group.found_masks)[3]); + + printf(" final mask: %16llx\n", (unsigned long long)mask); + */ + + + R = _mm512_or_si512(R, group.pattern_masks[data[i + 1]]); + +#if 1 + + if (mask != 0xffffffffffffffffllu) + { + //counter++; + //printf("Ouhc: %p - %x\n", &group, *((uint8_t *)&mask)); + //printf("Ouhc: %p\n", &group); + for (j = 0; j < group.used; j++) + { + if ((mask & 0x1) == 0) + { + //assert((i + 1) >= group.m[j]); + + printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)i + 1); + + + } + + mask >>= 1; + + } + + + + } + + +#else + + if (_mm512_reduce_or_epi64(test) != 0) + { + for (j = 0; j < group.used; j++) + { + if (((uint8_t *)&test)[j] == 0) + { + //assert((i + 1) >= group.m[j]); + + printf(">> FOUND %zu @ %x !!!!!!!!!!!!!!\n", j, (unsigned int)i + 1); + + } + + + } + + } + +#endif + + + } + + //printf("%hhx\n", ((uint8_t *)&R)[0], ((uint8_t *)&mask)[0]); + + } + + //printf("counter=%d\n", counter); + + +} +#endif + + + +#endif diff --git a/src/analysis/scan/patterns/backends/bitap.h b/src/analysis/scan/patterns/backends/bitap.h new file mode 100644 index 0000000..1cb384c --- /dev/null +++ b/src/analysis/scan/patterns/backends/bitap.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * bitap.h - prototypes pour la méthode de recherche basée sur l'algorithme Bitap + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKENDS_BITAP_H +#define _ANALYSIS_SCAN_PATTERNS_BACKENDS_BITAP_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "../backend.h" + + + +#define G_TYPE_BITAP_BACKEND g_bitap_backend_get_type() +#define G_BITAP_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_BITAP_BACKEND, GBitapBackend)) +#define G_IS_BITAP_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_BITAP_BACKEND)) +#define G_BITAP_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_BITAP_BACKEND, GBitapBackendClass)) +#define G_IS_BITAP_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_BITAP_BACKEND)) +#define G_BITAP_BACKEND_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_BITAP_BACKEND, GBitapBackendClass)) + + +/* Méthode de recherche basée sur l'algorithme Bitap (instance) */ +typedef struct _GBitapBackend GBitapBackend; + +/* Méthode de recherche basée sur l'algorithme Bitap (classe) */ +typedef struct _GBitapBackendClass GBitapBackendClass; + + +/* Indique le type défini pour un moteur de recherche pour données. */ +GType g_bitap_backend_get_type(void); + +/* Crée une méthode de recherche basée sur l'algorithme Bitap. */ +GEngineBackend *g_bitap_backend_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKENDS_BITAP_H */ diff --git a/src/analysis/scan/patterns/backends/hyperscan-int.h b/src/analysis/scan/patterns/backends/hyperscan-int.h new file mode 100644 index 0000000..31d271b --- /dev/null +++ b/src/analysis/scan/patterns/backends/hyperscan-int.h @@ -0,0 +1,67 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hyperscan-int.h - prototypes internes pour la méthode de recherche basée sur la bibliothèque Hyperscan d'Intel + * + * Copyright (C) 2024 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKENDS_HYPERSCAN_INT_H +#define _ANALYSIS_SCAN_PATTERNS_BACKENDS_HYPERSCAN_INT_H + + +#include "hyperscan.h" + + +#include "../backend-int.h" + + + +#define EXPR_COVERAGE_START 0 +#define EXPR_COVERAGE_COUNT 1 +#define EXPR_COVERAGE_END 1 + + +/* Méthode de recherche basée sur une bibliothèque d'Intel : Hyperscan (instance) */ +struct _GHyperscanBackend +{ + GEngineBackend parent; /* A laisser en premier */ + + const uint8_t **atoms; /* Motif remarquable */ + size_t *lengths; /* Nombre d'octets considérés */ + uint32_t *coverages; /* Départ et quantité de suivis*/ + size_t allocated; /* Nombre d'éléments alloués */ + size_t used; /* Nombre d'éléments utiles */ + + unsigned int *lit_ids; /* Identifiants internes */ + + hs_database_t *database; /* Compilation d'éléments */ + hs_scratch_t *scratch; /* Espace de travail */ + +}; + +/* Méthode de recherche basée sur une bibliothèque d'Intel : Hyperscan (classe) */ +struct _GHyperscanBackendClass +{ + GEngineBackendClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKENDS_HYPERSCAN_INT_H */ diff --git a/src/analysis/scan/patterns/backends/hyperscan.c b/src/analysis/scan/patterns/backends/hyperscan.c new file mode 100644 index 0000000..40a7372 --- /dev/null +++ b/src/analysis/scan/patterns/backends/hyperscan.c @@ -0,0 +1,1063 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hyperscan.c - méthode de recherche basée sur la bibliothèque Hyperscan d'Intel + * + * Copyright (C) 2024 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "hyperscan.h" + + +#include <hs.h> +#include <string.h> + + +#include <i18n.h> + + +#include "hyperscan-int.h" +#include "../../../../core/logs.h" +#include "../../../../glibext/umemslice.h" /* REMME */ + + + +/* ---------------------- IMPLANTATION D'UNE NOUVELLE APPROCHE ---------------------- */ + + +/* Initialise la classe des méthodes basée sur Hyperscan. */ +static void g_hyperscan_backend_class_init(GHyperscanBackendClass *); + +/* Initialise une instance de méthodes basée sur Hyperscan. */ +static void g_hyperscan_backend_init(GHyperscanBackend *); + +/* Supprime toutes les références externes. */ +static void g_hyperscan_backend_dispose(GHyperscanBackend *); + +/* Procède à la libération totale de la mémoire. */ +static void g_hyperscan_backend_finalize(GHyperscanBackend *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/** + * for i in range(int(8192 / 25) + 1): + * print(','.join([ '% 5u' % (i * 25 + k) for k in range(25) ]) + ',') + */ +static const unsigned int __cached_ids[8200] = { + + 0, 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, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, + 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, + 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, + 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, + 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, + 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, + 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, + 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, + 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, + 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, + 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, + 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, + 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, + 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, + 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, + 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, + 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, + 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, + 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, + 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, + 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, + 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, + 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, + 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, + 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, + 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, + 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, + 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, + 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, + 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, + 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, + 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, + 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, + 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, + 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, + 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, + 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, + 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, + 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, + 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, + 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, + 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, + 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, + 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, + 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, + 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, + 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, + 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, + 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, + 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, + 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, + 1500, 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, + 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, + 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, 1574, + 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, + 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1623, 1624, + 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, + 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665, 1666, 1667, 1668, 1669, 1670, 1671, 1672, 1673, 1674, + 1675, 1676, 1677, 1678, 1679, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1694, 1695, 1696, 1697, 1698, 1699, + 1700, 1701, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, + 1725, 1726, 1727, 1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, + 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, + 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, + 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1820, 1821, 1822, 1823, 1824, + 1825, 1826, 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1839, 1840, 1841, 1842, 1843, 1844, 1845, 1846, 1847, 1848, 1849, + 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1872, 1873, 1874, + 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, + 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, + 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, + 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, + 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, + 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, + 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, + 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 2073, 2074, + 2075, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, + 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2111, 2112, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 2121, 2122, 2123, 2124, + 2125, 2126, 2127, 2128, 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2148, 2149, + 2150, 2151, 2152, 2153, 2154, 2155, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, + 2175, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2194, 2195, 2196, 2197, 2198, 2199, + 2200, 2201, 2202, 2203, 2204, 2205, 2206, 2207, 2208, 2209, 2210, 2211, 2212, 2213, 2214, 2215, 2216, 2217, 2218, 2219, 2220, 2221, 2222, 2223, 2224, + 2225, 2226, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2238, 2239, 2240, 2241, 2242, 2243, 2244, 2245, 2246, 2247, 2248, 2249, + 2250, 2251, 2252, 2253, 2254, 2255, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2267, 2268, 2269, 2270, 2271, 2272, 2273, 2274, + 2275, 2276, 2277, 2278, 2279, 2280, 2281, 2282, 2283, 2284, 2285, 2286, 2287, 2288, 2289, 2290, 2291, 2292, 2293, 2294, 2295, 2296, 2297, 2298, 2299, + 2300, 2301, 2302, 2303, 2304, 2305, 2306, 2307, 2308, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2324, + 2325, 2326, 2327, 2328, 2329, 2330, 2331, 2332, 2333, 2334, 2335, 2336, 2337, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348, 2349, + 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2361, 2362, 2363, 2364, 2365, 2366, 2367, 2368, 2369, 2370, 2371, 2372, 2373, 2374, + 2375, 2376, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2390, 2391, 2392, 2393, 2394, 2395, 2396, 2397, 2398, 2399, + 2400, 2401, 2402, 2403, 2404, 2405, 2406, 2407, 2408, 2409, 2410, 2411, 2412, 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2422, 2423, 2424, + 2425, 2426, 2427, 2428, 2429, 2430, 2431, 2432, 2433, 2434, 2435, 2436, 2437, 2438, 2439, 2440, 2441, 2442, 2443, 2444, 2445, 2446, 2447, 2448, 2449, + 2450, 2451, 2452, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, + 2475, 2476, 2477, 2478, 2479, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, + 2500, 2501, 2502, 2503, 2504, 2505, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, + 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2539, 2540, 2541, 2542, 2543, 2544, 2545, 2546, 2547, 2548, 2549, + 2550, 2551, 2552, 2553, 2554, 2555, 2556, 2557, 2558, 2559, 2560, 2561, 2562, 2563, 2564, 2565, 2566, 2567, 2568, 2569, 2570, 2571, 2572, 2573, 2574, + 2575, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2583, 2584, 2585, 2586, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2598, 2599, + 2600, 2601, 2602, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2623, 2624, + 2625, 2626, 2627, 2628, 2629, 2630, 2631, 2632, 2633, 2634, 2635, 2636, 2637, 2638, 2639, 2640, 2641, 2642, 2643, 2644, 2645, 2646, 2647, 2648, 2649, + 2650, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2660, 2661, 2662, 2663, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2671, 2672, 2673, 2674, + 2675, 2676, 2677, 2678, 2679, 2680, 2681, 2682, 2683, 2684, 2685, 2686, 2687, 2688, 2689, 2690, 2691, 2692, 2693, 2694, 2695, 2696, 2697, 2698, 2699, + 2700, 2701, 2702, 2703, 2704, 2705, 2706, 2707, 2708, 2709, 2710, 2711, 2712, 2713, 2714, 2715, 2716, 2717, 2718, 2719, 2720, 2721, 2722, 2723, 2724, + 2725, 2726, 2727, 2728, 2729, 2730, 2731, 2732, 2733, 2734, 2735, 2736, 2737, 2738, 2739, 2740, 2741, 2742, 2743, 2744, 2745, 2746, 2747, 2748, 2749, + 2750, 2751, 2752, 2753, 2754, 2755, 2756, 2757, 2758, 2759, 2760, 2761, 2762, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, + 2775, 2776, 2777, 2778, 2779, 2780, 2781, 2782, 2783, 2784, 2785, 2786, 2787, 2788, 2789, 2790, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, + 2800, 2801, 2802, 2803, 2804, 2805, 2806, 2807, 2808, 2809, 2810, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819, 2820, 2821, 2822, 2823, 2824, + 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839, 2840, 2841, 2842, 2843, 2844, 2845, 2846, 2847, 2848, 2849, + 2850, 2851, 2852, 2853, 2854, 2855, 2856, 2857, 2858, 2859, 2860, 2861, 2862, 2863, 2864, 2865, 2866, 2867, 2868, 2869, 2870, 2871, 2872, 2873, 2874, + 2875, 2876, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2891, 2892, 2893, 2894, 2895, 2896, 2897, 2898, 2899, + 2900, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, + 2925, 2926, 2927, 2928, 2929, 2930, 2931, 2932, 2933, 2934, 2935, 2936, 2937, 2938, 2939, 2940, 2941, 2942, 2943, 2944, 2945, 2946, 2947, 2948, 2949, + 2950, 2951, 2952, 2953, 2954, 2955, 2956, 2957, 2958, 2959, 2960, 2961, 2962, 2963, 2964, 2965, 2966, 2967, 2968, 2969, 2970, 2971, 2972, 2973, 2974, + 2975, 2976, 2977, 2978, 2979, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2988, 2989, 2990, 2991, 2992, 2993, 2994, 2995, 2996, 2997, 2998, 2999, + 3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019, 3020, 3021, 3022, 3023, 3024, + 3025, 3026, 3027, 3028, 3029, 3030, 3031, 3032, 3033, 3034, 3035, 3036, 3037, 3038, 3039, 3040, 3041, 3042, 3043, 3044, 3045, 3046, 3047, 3048, 3049, + 3050, 3051, 3052, 3053, 3054, 3055, 3056, 3057, 3058, 3059, 3060, 3061, 3062, 3063, 3064, 3065, 3066, 3067, 3068, 3069, 3070, 3071, 3072, 3073, 3074, + 3075, 3076, 3077, 3078, 3079, 3080, 3081, 3082, 3083, 3084, 3085, 3086, 3087, 3088, 3089, 3090, 3091, 3092, 3093, 3094, 3095, 3096, 3097, 3098, 3099, + 3100, 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3108, 3109, 3110, 3111, 3112, 3113, 3114, 3115, 3116, 3117, 3118, 3119, 3120, 3121, 3122, 3123, 3124, + 3125, 3126, 3127, 3128, 3129, 3130, 3131, 3132, 3133, 3134, 3135, 3136, 3137, 3138, 3139, 3140, 3141, 3142, 3143, 3144, 3145, 3146, 3147, 3148, 3149, + 3150, 3151, 3152, 3153, 3154, 3155, 3156, 3157, 3158, 3159, 3160, 3161, 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3169, 3170, 3171, 3172, 3173, 3174, + 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3182, 3183, 3184, 3185, 3186, 3187, 3188, 3189, 3190, 3191, 3192, 3193, 3194, 3195, 3196, 3197, 3198, 3199, + 3200, 3201, 3202, 3203, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3215, 3216, 3217, 3218, 3219, 3220, 3221, 3222, 3223, 3224, + 3225, 3226, 3227, 3228, 3229, 3230, 3231, 3232, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3244, 3245, 3246, 3247, 3248, 3249, + 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, + 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3288, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3299, + 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3322, 3323, 3324, + 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3333, 3334, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3346, 3347, 3348, 3349, + 3350, 3351, 3352, 3353, 3354, 3355, 3356, 3357, 3358, 3359, 3360, 3361, 3362, 3363, 3364, 3365, 3366, 3367, 3368, 3369, 3370, 3371, 3372, 3373, 3374, + 3375, 3376, 3377, 3378, 3379, 3380, 3381, 3382, 3383, 3384, 3385, 3386, 3387, 3388, 3389, 3390, 3391, 3392, 3393, 3394, 3395, 3396, 3397, 3398, 3399, + 3400, 3401, 3402, 3403, 3404, 3405, 3406, 3407, 3408, 3409, 3410, 3411, 3412, 3413, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3422, 3423, 3424, + 3425, 3426, 3427, 3428, 3429, 3430, 3431, 3432, 3433, 3434, 3435, 3436, 3437, 3438, 3439, 3440, 3441, 3442, 3443, 3444, 3445, 3446, 3447, 3448, 3449, + 3450, 3451, 3452, 3453, 3454, 3455, 3456, 3457, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467, 3468, 3469, 3470, 3471, 3472, 3473, 3474, + 3475, 3476, 3477, 3478, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3495, 3496, 3497, 3498, 3499, + 3500, 3501, 3502, 3503, 3504, 3505, 3506, 3507, 3508, 3509, 3510, 3511, 3512, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3524, + 3525, 3526, 3527, 3528, 3529, 3530, 3531, 3532, 3533, 3534, 3535, 3536, 3537, 3538, 3539, 3540, 3541, 3542, 3543, 3544, 3545, 3546, 3547, 3548, 3549, + 3550, 3551, 3552, 3553, 3554, 3555, 3556, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3566, 3567, 3568, 3569, 3570, 3571, 3572, 3573, 3574, + 3575, 3576, 3577, 3578, 3579, 3580, 3581, 3582, 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3596, 3597, 3598, 3599, + 3600, 3601, 3602, 3603, 3604, 3605, 3606, 3607, 3608, 3609, 3610, 3611, 3612, 3613, 3614, 3615, 3616, 3617, 3618, 3619, 3620, 3621, 3622, 3623, 3624, + 3625, 3626, 3627, 3628, 3629, 3630, 3631, 3632, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, 3646, 3647, 3648, 3649, + 3650, 3651, 3652, 3653, 3654, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, + 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3686, 3687, 3688, 3689, 3690, 3691, 3692, 3693, 3694, 3695, 3696, 3697, 3698, 3699, + 3700, 3701, 3702, 3703, 3704, 3705, 3706, 3707, 3708, 3709, 3710, 3711, 3712, 3713, 3714, 3715, 3716, 3717, 3718, 3719, 3720, 3721, 3722, 3723, 3724, + 3725, 3726, 3727, 3728, 3729, 3730, 3731, 3732, 3733, 3734, 3735, 3736, 3737, 3738, 3739, 3740, 3741, 3742, 3743, 3744, 3745, 3746, 3747, 3748, 3749, + 3750, 3751, 3752, 3753, 3754, 3755, 3756, 3757, 3758, 3759, 3760, 3761, 3762, 3763, 3764, 3765, 3766, 3767, 3768, 3769, 3770, 3771, 3772, 3773, 3774, + 3775, 3776, 3777, 3778, 3779, 3780, 3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3798, 3799, + 3800, 3801, 3802, 3803, 3804, 3805, 3806, 3807, 3808, 3809, 3810, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3819, 3820, 3821, 3822, 3823, 3824, + 3825, 3826, 3827, 3828, 3829, 3830, 3831, 3832, 3833, 3834, 3835, 3836, 3837, 3838, 3839, 3840, 3841, 3842, 3843, 3844, 3845, 3846, 3847, 3848, 3849, + 3850, 3851, 3852, 3853, 3854, 3855, 3856, 3857, 3858, 3859, 3860, 3861, 3862, 3863, 3864, 3865, 3866, 3867, 3868, 3869, 3870, 3871, 3872, 3873, 3874, + 3875, 3876, 3877, 3878, 3879, 3880, 3881, 3882, 3883, 3884, 3885, 3886, 3887, 3888, 3889, 3890, 3891, 3892, 3893, 3894, 3895, 3896, 3897, 3898, 3899, + 3900, 3901, 3902, 3903, 3904, 3905, 3906, 3907, 3908, 3909, 3910, 3911, 3912, 3913, 3914, 3915, 3916, 3917, 3918, 3919, 3920, 3921, 3922, 3923, 3924, + 3925, 3926, 3927, 3928, 3929, 3930, 3931, 3932, 3933, 3934, 3935, 3936, 3937, 3938, 3939, 3940, 3941, 3942, 3943, 3944, 3945, 3946, 3947, 3948, 3949, + 3950, 3951, 3952, 3953, 3954, 3955, 3956, 3957, 3958, 3959, 3960, 3961, 3962, 3963, 3964, 3965, 3966, 3967, 3968, 3969, 3970, 3971, 3972, 3973, 3974, + 3975, 3976, 3977, 3978, 3979, 3980, 3981, 3982, 3983, 3984, 3985, 3986, 3987, 3988, 3989, 3990, 3991, 3992, 3993, 3994, 3995, 3996, 3997, 3998, 3999, + 4000, 4001, 4002, 4003, 4004, 4005, 4006, 4007, 4008, 4009, 4010, 4011, 4012, 4013, 4014, 4015, 4016, 4017, 4018, 4019, 4020, 4021, 4022, 4023, 4024, + 4025, 4026, 4027, 4028, 4029, 4030, 4031, 4032, 4033, 4034, 4035, 4036, 4037, 4038, 4039, 4040, 4041, 4042, 4043, 4044, 4045, 4046, 4047, 4048, 4049, + 4050, 4051, 4052, 4053, 4054, 4055, 4056, 4057, 4058, 4059, 4060, 4061, 4062, 4063, 4064, 4065, 4066, 4067, 4068, 4069, 4070, 4071, 4072, 4073, 4074, + 4075, 4076, 4077, 4078, 4079, 4080, 4081, 4082, 4083, 4084, 4085, 4086, 4087, 4088, 4089, 4090, 4091, 4092, 4093, 4094, 4095, 4096, 4097, 4098, 4099, + 4100, 4101, 4102, 4103, 4104, 4105, 4106, 4107, 4108, 4109, 4110, 4111, 4112, 4113, 4114, 4115, 4116, 4117, 4118, 4119, 4120, 4121, 4122, 4123, 4124, + 4125, 4126, 4127, 4128, 4129, 4130, 4131, 4132, 4133, 4134, 4135, 4136, 4137, 4138, 4139, 4140, 4141, 4142, 4143, 4144, 4145, 4146, 4147, 4148, 4149, + 4150, 4151, 4152, 4153, 4154, 4155, 4156, 4157, 4158, 4159, 4160, 4161, 4162, 4163, 4164, 4165, 4166, 4167, 4168, 4169, 4170, 4171, 4172, 4173, 4174, + 4175, 4176, 4177, 4178, 4179, 4180, 4181, 4182, 4183, 4184, 4185, 4186, 4187, 4188, 4189, 4190, 4191, 4192, 4193, 4194, 4195, 4196, 4197, 4198, 4199, + 4200, 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, 4212, 4213, 4214, 4215, 4216, 4217, 4218, 4219, 4220, 4221, 4222, 4223, 4224, + 4225, 4226, 4227, 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4244, 4245, 4246, 4247, 4248, 4249, + 4250, 4251, 4252, 4253, 4254, 4255, 4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4273, 4274, + 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299, + 4300, 4301, 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, 4320, 4321, 4322, 4323, 4324, + 4325, 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4339, 4340, 4341, 4342, 4343, 4344, 4345, 4346, 4347, 4348, 4349, + 4350, 4351, 4352, 4353, 4354, 4355, 4356, 4357, 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365, 4366, 4367, 4368, 4369, 4370, 4371, 4372, 4373, 4374, + 4375, 4376, 4377, 4378, 4379, 4380, 4381, 4382, 4383, 4384, 4385, 4386, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, + 4400, 4401, 4402, 4403, 4404, 4405, 4406, 4407, 4408, 4409, 4410, 4411, 4412, 4413, 4414, 4415, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, + 4425, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4433, 4434, 4435, 4436, 4437, 4438, 4439, 4440, 4441, 4442, 4443, 4444, 4445, 4446, 4447, 4448, 4449, + 4450, 4451, 4452, 4453, 4454, 4455, 4456, 4457, 4458, 4459, 4460, 4461, 4462, 4463, 4464, 4465, 4466, 4467, 4468, 4469, 4470, 4471, 4472, 4473, 4474, + 4475, 4476, 4477, 4478, 4479, 4480, 4481, 4482, 4483, 4484, 4485, 4486, 4487, 4488, 4489, 4490, 4491, 4492, 4493, 4494, 4495, 4496, 4497, 4498, 4499, + 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4515, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4523, 4524, + 4525, 4526, 4527, 4528, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4539, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4547, 4548, 4549, + 4550, 4551, 4552, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4565, 4566, 4567, 4568, 4569, 4570, 4571, 4572, 4573, 4574, + 4575, 4576, 4577, 4578, 4579, 4580, 4581, 4582, 4583, 4584, 4585, 4586, 4587, 4588, 4589, 4590, 4591, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4599, + 4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, + 4625, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, + 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, + 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4699, + 4700, 4701, 4702, 4703, 4704, 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714, 4715, 4716, 4717, 4718, 4719, 4720, 4721, 4722, 4723, 4724, + 4725, 4726, 4727, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4744, 4745, 4746, 4747, 4748, 4749, + 4750, 4751, 4752, 4753, 4754, 4755, 4756, 4757, 4758, 4759, 4760, 4761, 4762, 4763, 4764, 4765, 4766, 4767, 4768, 4769, 4770, 4771, 4772, 4773, 4774, + 4775, 4776, 4777, 4778, 4779, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4789, 4790, 4791, 4792, 4793, 4794, 4795, 4796, 4797, 4798, 4799, + 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4824, + 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4848, 4849, + 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4857, 4858, 4859, 4860, 4861, 4862, 4863, 4864, 4865, 4866, 4867, 4868, 4869, 4870, 4871, 4872, 4873, 4874, + 4875, 4876, 4877, 4878, 4879, 4880, 4881, 4882, 4883, 4884, 4885, 4886, 4887, 4888, 4889, 4890, 4891, 4892, 4893, 4894, 4895, 4896, 4897, 4898, 4899, + 4900, 4901, 4902, 4903, 4904, 4905, 4906, 4907, 4908, 4909, 4910, 4911, 4912, 4913, 4914, 4915, 4916, 4917, 4918, 4919, 4920, 4921, 4922, 4923, 4924, + 4925, 4926, 4927, 4928, 4929, 4930, 4931, 4932, 4933, 4934, 4935, 4936, 4937, 4938, 4939, 4940, 4941, 4942, 4943, 4944, 4945, 4946, 4947, 4948, 4949, + 4950, 4951, 4952, 4953, 4954, 4955, 4956, 4957, 4958, 4959, 4960, 4961, 4962, 4963, 4964, 4965, 4966, 4967, 4968, 4969, 4970, 4971, 4972, 4973, 4974, + 4975, 4976, 4977, 4978, 4979, 4980, 4981, 4982, 4983, 4984, 4985, 4986, 4987, 4988, 4989, 4990, 4991, 4992, 4993, 4994, 4995, 4996, 4997, 4998, 4999, + 5000, 5001, 5002, 5003, 5004, 5005, 5006, 5007, 5008, 5009, 5010, 5011, 5012, 5013, 5014, 5015, 5016, 5017, 5018, 5019, 5020, 5021, 5022, 5023, 5024, + 5025, 5026, 5027, 5028, 5029, 5030, 5031, 5032, 5033, 5034, 5035, 5036, 5037, 5038, 5039, 5040, 5041, 5042, 5043, 5044, 5045, 5046, 5047, 5048, 5049, + 5050, 5051, 5052, 5053, 5054, 5055, 5056, 5057, 5058, 5059, 5060, 5061, 5062, 5063, 5064, 5065, 5066, 5067, 5068, 5069, 5070, 5071, 5072, 5073, 5074, + 5075, 5076, 5077, 5078, 5079, 5080, 5081, 5082, 5083, 5084, 5085, 5086, 5087, 5088, 5089, 5090, 5091, 5092, 5093, 5094, 5095, 5096, 5097, 5098, 5099, + 5100, 5101, 5102, 5103, 5104, 5105, 5106, 5107, 5108, 5109, 5110, 5111, 5112, 5113, 5114, 5115, 5116, 5117, 5118, 5119, 5120, 5121, 5122, 5123, 5124, + 5125, 5126, 5127, 5128, 5129, 5130, 5131, 5132, 5133, 5134, 5135, 5136, 5137, 5138, 5139, 5140, 5141, 5142, 5143, 5144, 5145, 5146, 5147, 5148, 5149, + 5150, 5151, 5152, 5153, 5154, 5155, 5156, 5157, 5158, 5159, 5160, 5161, 5162, 5163, 5164, 5165, 5166, 5167, 5168, 5169, 5170, 5171, 5172, 5173, 5174, + 5175, 5176, 5177, 5178, 5179, 5180, 5181, 5182, 5183, 5184, 5185, 5186, 5187, 5188, 5189, 5190, 5191, 5192, 5193, 5194, 5195, 5196, 5197, 5198, 5199, + 5200, 5201, 5202, 5203, 5204, 5205, 5206, 5207, 5208, 5209, 5210, 5211, 5212, 5213, 5214, 5215, 5216, 5217, 5218, 5219, 5220, 5221, 5222, 5223, 5224, + 5225, 5226, 5227, 5228, 5229, 5230, 5231, 5232, 5233, 5234, 5235, 5236, 5237, 5238, 5239, 5240, 5241, 5242, 5243, 5244, 5245, 5246, 5247, 5248, 5249, + 5250, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 5259, 5260, 5261, 5262, 5263, 5264, 5265, 5266, 5267, 5268, 5269, 5270, 5271, 5272, 5273, 5274, + 5275, 5276, 5277, 5278, 5279, 5280, 5281, 5282, 5283, 5284, 5285, 5286, 5287, 5288, 5289, 5290, 5291, 5292, 5293, 5294, 5295, 5296, 5297, 5298, 5299, + 5300, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 5308, 5309, 5310, 5311, 5312, 5313, 5314, 5315, 5316, 5317, 5318, 5319, 5320, 5321, 5322, 5323, 5324, + 5325, 5326, 5327, 5328, 5329, 5330, 5331, 5332, 5333, 5334, 5335, 5336, 5337, 5338, 5339, 5340, 5341, 5342, 5343, 5344, 5345, 5346, 5347, 5348, 5349, + 5350, 5351, 5352, 5353, 5354, 5355, 5356, 5357, 5358, 5359, 5360, 5361, 5362, 5363, 5364, 5365, 5366, 5367, 5368, 5369, 5370, 5371, 5372, 5373, 5374, + 5375, 5376, 5377, 5378, 5379, 5380, 5381, 5382, 5383, 5384, 5385, 5386, 5387, 5388, 5389, 5390, 5391, 5392, 5393, 5394, 5395, 5396, 5397, 5398, 5399, + 5400, 5401, 5402, 5403, 5404, 5405, 5406, 5407, 5408, 5409, 5410, 5411, 5412, 5413, 5414, 5415, 5416, 5417, 5418, 5419, 5420, 5421, 5422, 5423, 5424, + 5425, 5426, 5427, 5428, 5429, 5430, 5431, 5432, 5433, 5434, 5435, 5436, 5437, 5438, 5439, 5440, 5441, 5442, 5443, 5444, 5445, 5446, 5447, 5448, 5449, + 5450, 5451, 5452, 5453, 5454, 5455, 5456, 5457, 5458, 5459, 5460, 5461, 5462, 5463, 5464, 5465, 5466, 5467, 5468, 5469, 5470, 5471, 5472, 5473, 5474, + 5475, 5476, 5477, 5478, 5479, 5480, 5481, 5482, 5483, 5484, 5485, 5486, 5487, 5488, 5489, 5490, 5491, 5492, 5493, 5494, 5495, 5496, 5497, 5498, 5499, + 5500, 5501, 5502, 5503, 5504, 5505, 5506, 5507, 5508, 5509, 5510, 5511, 5512, 5513, 5514, 5515, 5516, 5517, 5518, 5519, 5520, 5521, 5522, 5523, 5524, + 5525, 5526, 5527, 5528, 5529, 5530, 5531, 5532, 5533, 5534, 5535, 5536, 5537, 5538, 5539, 5540, 5541, 5542, 5543, 5544, 5545, 5546, 5547, 5548, 5549, + 5550, 5551, 5552, 5553, 5554, 5555, 5556, 5557, 5558, 5559, 5560, 5561, 5562, 5563, 5564, 5565, 5566, 5567, 5568, 5569, 5570, 5571, 5572, 5573, 5574, + 5575, 5576, 5577, 5578, 5579, 5580, 5581, 5582, 5583, 5584, 5585, 5586, 5587, 5588, 5589, 5590, 5591, 5592, 5593, 5594, 5595, 5596, 5597, 5598, 5599, + 5600, 5601, 5602, 5603, 5604, 5605, 5606, 5607, 5608, 5609, 5610, 5611, 5612, 5613, 5614, 5615, 5616, 5617, 5618, 5619, 5620, 5621, 5622, 5623, 5624, + 5625, 5626, 5627, 5628, 5629, 5630, 5631, 5632, 5633, 5634, 5635, 5636, 5637, 5638, 5639, 5640, 5641, 5642, 5643, 5644, 5645, 5646, 5647, 5648, 5649, + 5650, 5651, 5652, 5653, 5654, 5655, 5656, 5657, 5658, 5659, 5660, 5661, 5662, 5663, 5664, 5665, 5666, 5667, 5668, 5669, 5670, 5671, 5672, 5673, 5674, + 5675, 5676, 5677, 5678, 5679, 5680, 5681, 5682, 5683, 5684, 5685, 5686, 5687, 5688, 5689, 5690, 5691, 5692, 5693, 5694, 5695, 5696, 5697, 5698, 5699, + 5700, 5701, 5702, 5703, 5704, 5705, 5706, 5707, 5708, 5709, 5710, 5711, 5712, 5713, 5714, 5715, 5716, 5717, 5718, 5719, 5720, 5721, 5722, 5723, 5724, + 5725, 5726, 5727, 5728, 5729, 5730, 5731, 5732, 5733, 5734, 5735, 5736, 5737, 5738, 5739, 5740, 5741, 5742, 5743, 5744, 5745, 5746, 5747, 5748, 5749, + 5750, 5751, 5752, 5753, 5754, 5755, 5756, 5757, 5758, 5759, 5760, 5761, 5762, 5763, 5764, 5765, 5766, 5767, 5768, 5769, 5770, 5771, 5772, 5773, 5774, + 5775, 5776, 5777, 5778, 5779, 5780, 5781, 5782, 5783, 5784, 5785, 5786, 5787, 5788, 5789, 5790, 5791, 5792, 5793, 5794, 5795, 5796, 5797, 5798, 5799, + 5800, 5801, 5802, 5803, 5804, 5805, 5806, 5807, 5808, 5809, 5810, 5811, 5812, 5813, 5814, 5815, 5816, 5817, 5818, 5819, 5820, 5821, 5822, 5823, 5824, + 5825, 5826, 5827, 5828, 5829, 5830, 5831, 5832, 5833, 5834, 5835, 5836, 5837, 5838, 5839, 5840, 5841, 5842, 5843, 5844, 5845, 5846, 5847, 5848, 5849, + 5850, 5851, 5852, 5853, 5854, 5855, 5856, 5857, 5858, 5859, 5860, 5861, 5862, 5863, 5864, 5865, 5866, 5867, 5868, 5869, 5870, 5871, 5872, 5873, 5874, + 5875, 5876, 5877, 5878, 5879, 5880, 5881, 5882, 5883, 5884, 5885, 5886, 5887, 5888, 5889, 5890, 5891, 5892, 5893, 5894, 5895, 5896, 5897, 5898, 5899, + 5900, 5901, 5902, 5903, 5904, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912, 5913, 5914, 5915, 5916, 5917, 5918, 5919, 5920, 5921, 5922, 5923, 5924, + 5925, 5926, 5927, 5928, 5929, 5930, 5931, 5932, 5933, 5934, 5935, 5936, 5937, 5938, 5939, 5940, 5941, 5942, 5943, 5944, 5945, 5946, 5947, 5948, 5949, + 5950, 5951, 5952, 5953, 5954, 5955, 5956, 5957, 5958, 5959, 5960, 5961, 5962, 5963, 5964, 5965, 5966, 5967, 5968, 5969, 5970, 5971, 5972, 5973, 5974, + 5975, 5976, 5977, 5978, 5979, 5980, 5981, 5982, 5983, 5984, 5985, 5986, 5987, 5988, 5989, 5990, 5991, 5992, 5993, 5994, 5995, 5996, 5997, 5998, 5999, + 6000, 6001, 6002, 6003, 6004, 6005, 6006, 6007, 6008, 6009, 6010, 6011, 6012, 6013, 6014, 6015, 6016, 6017, 6018, 6019, 6020, 6021, 6022, 6023, 6024, + 6025, 6026, 6027, 6028, 6029, 6030, 6031, 6032, 6033, 6034, 6035, 6036, 6037, 6038, 6039, 6040, 6041, 6042, 6043, 6044, 6045, 6046, 6047, 6048, 6049, + 6050, 6051, 6052, 6053, 6054, 6055, 6056, 6057, 6058, 6059, 6060, 6061, 6062, 6063, 6064, 6065, 6066, 6067, 6068, 6069, 6070, 6071, 6072, 6073, 6074, + 6075, 6076, 6077, 6078, 6079, 6080, 6081, 6082, 6083, 6084, 6085, 6086, 6087, 6088, 6089, 6090, 6091, 6092, 6093, 6094, 6095, 6096, 6097, 6098, 6099, + 6100, 6101, 6102, 6103, 6104, 6105, 6106, 6107, 6108, 6109, 6110, 6111, 6112, 6113, 6114, 6115, 6116, 6117, 6118, 6119, 6120, 6121, 6122, 6123, 6124, + 6125, 6126, 6127, 6128, 6129, 6130, 6131, 6132, 6133, 6134, 6135, 6136, 6137, 6138, 6139, 6140, 6141, 6142, 6143, 6144, 6145, 6146, 6147, 6148, 6149, + 6150, 6151, 6152, 6153, 6154, 6155, 6156, 6157, 6158, 6159, 6160, 6161, 6162, 6163, 6164, 6165, 6166, 6167, 6168, 6169, 6170, 6171, 6172, 6173, 6174, + 6175, 6176, 6177, 6178, 6179, 6180, 6181, 6182, 6183, 6184, 6185, 6186, 6187, 6188, 6189, 6190, 6191, 6192, 6193, 6194, 6195, 6196, 6197, 6198, 6199, + 6200, 6201, 6202, 6203, 6204, 6205, 6206, 6207, 6208, 6209, 6210, 6211, 6212, 6213, 6214, 6215, 6216, 6217, 6218, 6219, 6220, 6221, 6222, 6223, 6224, + 6225, 6226, 6227, 6228, 6229, 6230, 6231, 6232, 6233, 6234, 6235, 6236, 6237, 6238, 6239, 6240, 6241, 6242, 6243, 6244, 6245, 6246, 6247, 6248, 6249, + 6250, 6251, 6252, 6253, 6254, 6255, 6256, 6257, 6258, 6259, 6260, 6261, 6262, 6263, 6264, 6265, 6266, 6267, 6268, 6269, 6270, 6271, 6272, 6273, 6274, + 6275, 6276, 6277, 6278, 6279, 6280, 6281, 6282, 6283, 6284, 6285, 6286, 6287, 6288, 6289, 6290, 6291, 6292, 6293, 6294, 6295, 6296, 6297, 6298, 6299, + 6300, 6301, 6302, 6303, 6304, 6305, 6306, 6307, 6308, 6309, 6310, 6311, 6312, 6313, 6314, 6315, 6316, 6317, 6318, 6319, 6320, 6321, 6322, 6323, 6324, + 6325, 6326, 6327, 6328, 6329, 6330, 6331, 6332, 6333, 6334, 6335, 6336, 6337, 6338, 6339, 6340, 6341, 6342, 6343, 6344, 6345, 6346, 6347, 6348, 6349, + 6350, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6358, 6359, 6360, 6361, 6362, 6363, 6364, 6365, 6366, 6367, 6368, 6369, 6370, 6371, 6372, 6373, 6374, + 6375, 6376, 6377, 6378, 6379, 6380, 6381, 6382, 6383, 6384, 6385, 6386, 6387, 6388, 6389, 6390, 6391, 6392, 6393, 6394, 6395, 6396, 6397, 6398, 6399, + 6400, 6401, 6402, 6403, 6404, 6405, 6406, 6407, 6408, 6409, 6410, 6411, 6412, 6413, 6414, 6415, 6416, 6417, 6418, 6419, 6420, 6421, 6422, 6423, 6424, + 6425, 6426, 6427, 6428, 6429, 6430, 6431, 6432, 6433, 6434, 6435, 6436, 6437, 6438, 6439, 6440, 6441, 6442, 6443, 6444, 6445, 6446, 6447, 6448, 6449, + 6450, 6451, 6452, 6453, 6454, 6455, 6456, 6457, 6458, 6459, 6460, 6461, 6462, 6463, 6464, 6465, 6466, 6467, 6468, 6469, 6470, 6471, 6472, 6473, 6474, + 6475, 6476, 6477, 6478, 6479, 6480, 6481, 6482, 6483, 6484, 6485, 6486, 6487, 6488, 6489, 6490, 6491, 6492, 6493, 6494, 6495, 6496, 6497, 6498, 6499, + 6500, 6501, 6502, 6503, 6504, 6505, 6506, 6507, 6508, 6509, 6510, 6511, 6512, 6513, 6514, 6515, 6516, 6517, 6518, 6519, 6520, 6521, 6522, 6523, 6524, + 6525, 6526, 6527, 6528, 6529, 6530, 6531, 6532, 6533, 6534, 6535, 6536, 6537, 6538, 6539, 6540, 6541, 6542, 6543, 6544, 6545, 6546, 6547, 6548, 6549, + 6550, 6551, 6552, 6553, 6554, 6555, 6556, 6557, 6558, 6559, 6560, 6561, 6562, 6563, 6564, 6565, 6566, 6567, 6568, 6569, 6570, 6571, 6572, 6573, 6574, + 6575, 6576, 6577, 6578, 6579, 6580, 6581, 6582, 6583, 6584, 6585, 6586, 6587, 6588, 6589, 6590, 6591, 6592, 6593, 6594, 6595, 6596, 6597, 6598, 6599, + 6600, 6601, 6602, 6603, 6604, 6605, 6606, 6607, 6608, 6609, 6610, 6611, 6612, 6613, 6614, 6615, 6616, 6617, 6618, 6619, 6620, 6621, 6622, 6623, 6624, + 6625, 6626, 6627, 6628, 6629, 6630, 6631, 6632, 6633, 6634, 6635, 6636, 6637, 6638, 6639, 6640, 6641, 6642, 6643, 6644, 6645, 6646, 6647, 6648, 6649, + 6650, 6651, 6652, 6653, 6654, 6655, 6656, 6657, 6658, 6659, 6660, 6661, 6662, 6663, 6664, 6665, 6666, 6667, 6668, 6669, 6670, 6671, 6672, 6673, 6674, + 6675, 6676, 6677, 6678, 6679, 6680, 6681, 6682, 6683, 6684, 6685, 6686, 6687, 6688, 6689, 6690, 6691, 6692, 6693, 6694, 6695, 6696, 6697, 6698, 6699, + 6700, 6701, 6702, 6703, 6704, 6705, 6706, 6707, 6708, 6709, 6710, 6711, 6712, 6713, 6714, 6715, 6716, 6717, 6718, 6719, 6720, 6721, 6722, 6723, 6724, + 6725, 6726, 6727, 6728, 6729, 6730, 6731, 6732, 6733, 6734, 6735, 6736, 6737, 6738, 6739, 6740, 6741, 6742, 6743, 6744, 6745, 6746, 6747, 6748, 6749, + 6750, 6751, 6752, 6753, 6754, 6755, 6756, 6757, 6758, 6759, 6760, 6761, 6762, 6763, 6764, 6765, 6766, 6767, 6768, 6769, 6770, 6771, 6772, 6773, 6774, + 6775, 6776, 6777, 6778, 6779, 6780, 6781, 6782, 6783, 6784, 6785, 6786, 6787, 6788, 6789, 6790, 6791, 6792, 6793, 6794, 6795, 6796, 6797, 6798, 6799, + 6800, 6801, 6802, 6803, 6804, 6805, 6806, 6807, 6808, 6809, 6810, 6811, 6812, 6813, 6814, 6815, 6816, 6817, 6818, 6819, 6820, 6821, 6822, 6823, 6824, + 6825, 6826, 6827, 6828, 6829, 6830, 6831, 6832, 6833, 6834, 6835, 6836, 6837, 6838, 6839, 6840, 6841, 6842, 6843, 6844, 6845, 6846, 6847, 6848, 6849, + 6850, 6851, 6852, 6853, 6854, 6855, 6856, 6857, 6858, 6859, 6860, 6861, 6862, 6863, 6864, 6865, 6866, 6867, 6868, 6869, 6870, 6871, 6872, 6873, 6874, + 6875, 6876, 6877, 6878, 6879, 6880, 6881, 6882, 6883, 6884, 6885, 6886, 6887, 6888, 6889, 6890, 6891, 6892, 6893, 6894, 6895, 6896, 6897, 6898, 6899, + 6900, 6901, 6902, 6903, 6904, 6905, 6906, 6907, 6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917, 6918, 6919, 6920, 6921, 6922, 6923, 6924, + 6925, 6926, 6927, 6928, 6929, 6930, 6931, 6932, 6933, 6934, 6935, 6936, 6937, 6938, 6939, 6940, 6941, 6942, 6943, 6944, 6945, 6946, 6947, 6948, 6949, + 6950, 6951, 6952, 6953, 6954, 6955, 6956, 6957, 6958, 6959, 6960, 6961, 6962, 6963, 6964, 6965, 6966, 6967, 6968, 6969, 6970, 6971, 6972, 6973, 6974, + 6975, 6976, 6977, 6978, 6979, 6980, 6981, 6982, 6983, 6984, 6985, 6986, 6987, 6988, 6989, 6990, 6991, 6992, 6993, 6994, 6995, 6996, 6997, 6998, 6999, + 7000, 7001, 7002, 7003, 7004, 7005, 7006, 7007, 7008, 7009, 7010, 7011, 7012, 7013, 7014, 7015, 7016, 7017, 7018, 7019, 7020, 7021, 7022, 7023, 7024, + 7025, 7026, 7027, 7028, 7029, 7030, 7031, 7032, 7033, 7034, 7035, 7036, 7037, 7038, 7039, 7040, 7041, 7042, 7043, 7044, 7045, 7046, 7047, 7048, 7049, + 7050, 7051, 7052, 7053, 7054, 7055, 7056, 7057, 7058, 7059, 7060, 7061, 7062, 7063, 7064, 7065, 7066, 7067, 7068, 7069, 7070, 7071, 7072, 7073, 7074, + 7075, 7076, 7077, 7078, 7079, 7080, 7081, 7082, 7083, 7084, 7085, 7086, 7087, 7088, 7089, 7090, 7091, 7092, 7093, 7094, 7095, 7096, 7097, 7098, 7099, + 7100, 7101, 7102, 7103, 7104, 7105, 7106, 7107, 7108, 7109, 7110, 7111, 7112, 7113, 7114, 7115, 7116, 7117, 7118, 7119, 7120, 7121, 7122, 7123, 7124, + 7125, 7126, 7127, 7128, 7129, 7130, 7131, 7132, 7133, 7134, 7135, 7136, 7137, 7138, 7139, 7140, 7141, 7142, 7143, 7144, 7145, 7146, 7147, 7148, 7149, + 7150, 7151, 7152, 7153, 7154, 7155, 7156, 7157, 7158, 7159, 7160, 7161, 7162, 7163, 7164, 7165, 7166, 7167, 7168, 7169, 7170, 7171, 7172, 7173, 7174, + 7175, 7176, 7177, 7178, 7179, 7180, 7181, 7182, 7183, 7184, 7185, 7186, 7187, 7188, 7189, 7190, 7191, 7192, 7193, 7194, 7195, 7196, 7197, 7198, 7199, + 7200, 7201, 7202, 7203, 7204, 7205, 7206, 7207, 7208, 7209, 7210, 7211, 7212, 7213, 7214, 7215, 7216, 7217, 7218, 7219, 7220, 7221, 7222, 7223, 7224, + 7225, 7226, 7227, 7228, 7229, 7230, 7231, 7232, 7233, 7234, 7235, 7236, 7237, 7238, 7239, 7240, 7241, 7242, 7243, 7244, 7245, 7246, 7247, 7248, 7249, + 7250, 7251, 7252, 7253, 7254, 7255, 7256, 7257, 7258, 7259, 7260, 7261, 7262, 7263, 7264, 7265, 7266, 7267, 7268, 7269, 7270, 7271, 7272, 7273, 7274, + 7275, 7276, 7277, 7278, 7279, 7280, 7281, 7282, 7283, 7284, 7285, 7286, 7287, 7288, 7289, 7290, 7291, 7292, 7293, 7294, 7295, 7296, 7297, 7298, 7299, + 7300, 7301, 7302, 7303, 7304, 7305, 7306, 7307, 7308, 7309, 7310, 7311, 7312, 7313, 7314, 7315, 7316, 7317, 7318, 7319, 7320, 7321, 7322, 7323, 7324, + 7325, 7326, 7327, 7328, 7329, 7330, 7331, 7332, 7333, 7334, 7335, 7336, 7337, 7338, 7339, 7340, 7341, 7342, 7343, 7344, 7345, 7346, 7347, 7348, 7349, + 7350, 7351, 7352, 7353, 7354, 7355, 7356, 7357, 7358, 7359, 7360, 7361, 7362, 7363, 7364, 7365, 7366, 7367, 7368, 7369, 7370, 7371, 7372, 7373, 7374, + 7375, 7376, 7377, 7378, 7379, 7380, 7381, 7382, 7383, 7384, 7385, 7386, 7387, 7388, 7389, 7390, 7391, 7392, 7393, 7394, 7395, 7396, 7397, 7398, 7399, + 7400, 7401, 7402, 7403, 7404, 7405, 7406, 7407, 7408, 7409, 7410, 7411, 7412, 7413, 7414, 7415, 7416, 7417, 7418, 7419, 7420, 7421, 7422, 7423, 7424, + 7425, 7426, 7427, 7428, 7429, 7430, 7431, 7432, 7433, 7434, 7435, 7436, 7437, 7438, 7439, 7440, 7441, 7442, 7443, 7444, 7445, 7446, 7447, 7448, 7449, + 7450, 7451, 7452, 7453, 7454, 7455, 7456, 7457, 7458, 7459, 7460, 7461, 7462, 7463, 7464, 7465, 7466, 7467, 7468, 7469, 7470, 7471, 7472, 7473, 7474, + 7475, 7476, 7477, 7478, 7479, 7480, 7481, 7482, 7483, 7484, 7485, 7486, 7487, 7488, 7489, 7490, 7491, 7492, 7493, 7494, 7495, 7496, 7497, 7498, 7499, + 7500, 7501, 7502, 7503, 7504, 7505, 7506, 7507, 7508, 7509, 7510, 7511, 7512, 7513, 7514, 7515, 7516, 7517, 7518, 7519, 7520, 7521, 7522, 7523, 7524, + 7525, 7526, 7527, 7528, 7529, 7530, 7531, 7532, 7533, 7534, 7535, 7536, 7537, 7538, 7539, 7540, 7541, 7542, 7543, 7544, 7545, 7546, 7547, 7548, 7549, + 7550, 7551, 7552, 7553, 7554, 7555, 7556, 7557, 7558, 7559, 7560, 7561, 7562, 7563, 7564, 7565, 7566, 7567, 7568, 7569, 7570, 7571, 7572, 7573, 7574, + 7575, 7576, 7577, 7578, 7579, 7580, 7581, 7582, 7583, 7584, 7585, 7586, 7587, 7588, 7589, 7590, 7591, 7592, 7593, 7594, 7595, 7596, 7597, 7598, 7599, + 7600, 7601, 7602, 7603, 7604, 7605, 7606, 7607, 7608, 7609, 7610, 7611, 7612, 7613, 7614, 7615, 7616, 7617, 7618, 7619, 7620, 7621, 7622, 7623, 7624, + 7625, 7626, 7627, 7628, 7629, 7630, 7631, 7632, 7633, 7634, 7635, 7636, 7637, 7638, 7639, 7640, 7641, 7642, 7643, 7644, 7645, 7646, 7647, 7648, 7649, + 7650, 7651, 7652, 7653, 7654, 7655, 7656, 7657, 7658, 7659, 7660, 7661, 7662, 7663, 7664, 7665, 7666, 7667, 7668, 7669, 7670, 7671, 7672, 7673, 7674, + 7675, 7676, 7677, 7678, 7679, 7680, 7681, 7682, 7683, 7684, 7685, 7686, 7687, 7688, 7689, 7690, 7691, 7692, 7693, 7694, 7695, 7696, 7697, 7698, 7699, + 7700, 7701, 7702, 7703, 7704, 7705, 7706, 7707, 7708, 7709, 7710, 7711, 7712, 7713, 7714, 7715, 7716, 7717, 7718, 7719, 7720, 7721, 7722, 7723, 7724, + 7725, 7726, 7727, 7728, 7729, 7730, 7731, 7732, 7733, 7734, 7735, 7736, 7737, 7738, 7739, 7740, 7741, 7742, 7743, 7744, 7745, 7746, 7747, 7748, 7749, + 7750, 7751, 7752, 7753, 7754, 7755, 7756, 7757, 7758, 7759, 7760, 7761, 7762, 7763, 7764, 7765, 7766, 7767, 7768, 7769, 7770, 7771, 7772, 7773, 7774, + 7775, 7776, 7777, 7778, 7779, 7780, 7781, 7782, 7783, 7784, 7785, 7786, 7787, 7788, 7789, 7790, 7791, 7792, 7793, 7794, 7795, 7796, 7797, 7798, 7799, + 7800, 7801, 7802, 7803, 7804, 7805, 7806, 7807, 7808, 7809, 7810, 7811, 7812, 7813, 7814, 7815, 7816, 7817, 7818, 7819, 7820, 7821, 7822, 7823, 7824, + 7825, 7826, 7827, 7828, 7829, 7830, 7831, 7832, 7833, 7834, 7835, 7836, 7837, 7838, 7839, 7840, 7841, 7842, 7843, 7844, 7845, 7846, 7847, 7848, 7849, + 7850, 7851, 7852, 7853, 7854, 7855, 7856, 7857, 7858, 7859, 7860, 7861, 7862, 7863, 7864, 7865, 7866, 7867, 7868, 7869, 7870, 7871, 7872, 7873, 7874, + 7875, 7876, 7877, 7878, 7879, 7880, 7881, 7882, 7883, 7884, 7885, 7886, 7887, 7888, 7889, 7890, 7891, 7892, 7893, 7894, 7895, 7896, 7897, 7898, 7899, + 7900, 7901, 7902, 7903, 7904, 7905, 7906, 7907, 7908, 7909, 7910, 7911, 7912, 7913, 7914, 7915, 7916, 7917, 7918, 7919, 7920, 7921, 7922, 7923, 7924, + 7925, 7926, 7927, 7928, 7929, 7930, 7931, 7932, 7933, 7934, 7935, 7936, 7937, 7938, 7939, 7940, 7941, 7942, 7943, 7944, 7945, 7946, 7947, 7948, 7949, + 7950, 7951, 7952, 7953, 7954, 7955, 7956, 7957, 7958, 7959, 7960, 7961, 7962, 7963, 7964, 7965, 7966, 7967, 7968, 7969, 7970, 7971, 7972, 7973, 7974, + 7975, 7976, 7977, 7978, 7979, 7980, 7981, 7982, 7983, 7984, 7985, 7986, 7987, 7988, 7989, 7990, 7991, 7992, 7993, 7994, 7995, 7996, 7997, 7998, 7999, + 8000, 8001, 8002, 8003, 8004, 8005, 8006, 8007, 8008, 8009, 8010, 8011, 8012, 8013, 8014, 8015, 8016, 8017, 8018, 8019, 8020, 8021, 8022, 8023, 8024, + 8025, 8026, 8027, 8028, 8029, 8030, 8031, 8032, 8033, 8034, 8035, 8036, 8037, 8038, 8039, 8040, 8041, 8042, 8043, 8044, 8045, 8046, 8047, 8048, 8049, + 8050, 8051, 8052, 8053, 8054, 8055, 8056, 8057, 8058, 8059, 8060, 8061, 8062, 8063, 8064, 8065, 8066, 8067, 8068, 8069, 8070, 8071, 8072, 8073, 8074, + 8075, 8076, 8077, 8078, 8079, 8080, 8081, 8082, 8083, 8084, 8085, 8086, 8087, 8088, 8089, 8090, 8091, 8092, 8093, 8094, 8095, 8096, 8097, 8098, 8099, + 8100, 8101, 8102, 8103, 8104, 8105, 8106, 8107, 8108, 8109, 8110, 8111, 8112, 8113, 8114, 8115, 8116, 8117, 8118, 8119, 8120, 8121, 8122, 8123, 8124, + 8125, 8126, 8127, 8128, 8129, 8130, 8131, 8132, 8133, 8134, 8135, 8136, 8137, 8138, 8139, 8140, 8141, 8142, 8143, 8144, 8145, 8146, 8147, 8148, 8149, + 8150, 8151, 8152, 8153, 8154, 8155, 8156, 8157, 8158, 8159, 8160, 8161, 8162, 8163, 8164, 8165, 8166, 8167, 8168, 8169, 8170, 8171, 8172, 8173, 8174, + 8175, 8176, 8177, 8178, 8179, 8180, 8181, 8182, 8183, 8184, 8185, 8186, 8187, 8188, 8189, 8190, 8191, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, + +}; + + + +/* Indique la taille maximale des suites d'octets recherchées. */ +size_t g_hyperscan_backend_get_atom_max_size(const GHyperscanBackend *); + +/* Inscrit dans le moteur une chaîne de caractères à rechercher. */ +static bool g_hyperscan_backend_enroll_plain_pattern(GHyperscanBackend *, const uint8_t *, size_t, uint32_t [2]); + +/* Met en ordre les derniers détails avant un premier scan. */ +static bool g_hyperscan_backend_warm_up(GHyperscanBackend *); + +/* Récupère les identifiants finaux pour un motif recherché. */ +static patid_t g_hyperscan_backend_build_plain_pattern_id(const GHyperscanBackend *, const uint32_t [2]); + +/* Détermine le nombre d'identifiants constitués. */ +static size_t g_hyperscan_backend_count_plain_pattern_ids(const GHyperscanBackend *); + +/* Informations utiles au traitement d'un événement */ +typedef struct _hyperscan_context_t +{ + const size_t *lengths; /* Nombre d'octets considérés */ + const uint32_t *coverages; /* Départ et quantité de suivis*/ + +#ifndef NDEBUG + size_t used; /* Nombre d'éléments utiles */ + const unsigned int *lit_ids; /* Identifiants internes */ +#endif + + GUMemSlice **matches; /* Zones d'enregistrements */ + +} hyperscan_context_t; + +/* Prend note d'une correspondance trouvée par Hyperscan. */ +static int handle_hyperscan_match_event(unsigned int, unsigned long long, unsigned long long, unsigned int, GScanContext *context/*const hyperscan_context_t *context*/); + +/* Parcours un contenu binaire à la recherche de motifs. */ +static void g_hyperscan_backend_run_scan(const GHyperscanBackend *, GScanContext *); + +/* Imprime quelques faits quant aux éléments mis en place. */ +static void g_hyperscan_backend_output_stats(const GHyperscanBackend *); + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLANTATION D'UNE NOUVELLE APPROCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un moteur de recherche pour données. */ +G_DEFINE_TYPE(GHyperscanBackend, g_hyperscan_backend, G_TYPE_ENGINE_BACKEND); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des méthodes basée sur Hyperscan. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_hyperscan_backend_class_init(GHyperscanBackendClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GEngineBackendClass *backend; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_hyperscan_backend_dispose; + object->finalize = (GObjectFinalizeFunc)g_hyperscan_backend_finalize; + + backend = G_ENGINE_BACKEND_CLASS(klass); + + backend->get_max_size = (get_backend_atom_max_size_fc)g_hyperscan_backend_get_atom_max_size; + backend->enroll_plain = (enroll_plain_into_backend_fc)g_hyperscan_backend_enroll_plain_pattern; + backend->warm_up = (warm_up_backend_fc)g_hyperscan_backend_warm_up; + backend->build_id = (build_backend_plain_pattern_id_fc)g_hyperscan_backend_build_plain_pattern_id; + backend->count_ids = (count_backend_plain_pattern_ids_fc)g_hyperscan_backend_count_plain_pattern_ids; + backend->run_scan = (run_backend_scan_fc)g_hyperscan_backend_run_scan; + backend->output = (output_backend_stats_fc)g_hyperscan_backend_output_stats; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance à initialiser. * +* * +* Description : Initialise une instance de méthodes basée sur Hyperscan. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_hyperscan_backend_init(GHyperscanBackend *backend) +{ + backend->atoms = NULL; + backend->lengths = NULL; + backend->coverages = NULL; + backend->allocated = 0; + backend->used = 0; + + backend->database = NULL; + backend->scratch = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_hyperscan_backend_dispose(GHyperscanBackend *backend) +{ + G_OBJECT_CLASS(g_hyperscan_backend_parent_class)->dispose(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_hyperscan_backend_finalize(GHyperscanBackend *backend) +{ + if (backend->atoms != NULL) + free(backend->atoms); + + if (backend->lengths != NULL) + free(backend->lengths); + + if (backend->coverages != NULL) + free(backend->coverages); + + if (backend->scratch != NULL) + hs_free_scratch(backend->scratch); + + if (backend->database != NULL) + hs_free_database(backend->database); + + G_OBJECT_CLASS(g_hyperscan_backend_parent_class)->finalize(G_OBJECT(backend)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Crée une méthode de recherche avec la bibliothèque Hyperscan.* +* * +* Retour : Méthode mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GEngineBackend *g_hyperscan_backend_new(void) +{ + GHyperscanBackend *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_HYPERSCAN_BACKEND, NULL); + + return G_ENGINE_BACKEND(result); + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Indique la taille maximale des suites d'octets recherchées. * +* * +* Retour : Valeur strictement positive. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_hyperscan_backend_get_atom_max_size(const GHyperscanBackend *backend) +{ + size_t result; /* Taille à faire connaître */ + + result = ~0; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* plain = chaîne de caractères classique à intégrer. * +* len = taille de cette chaîne. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Inscrit dans le moteur une chaîne de caractères à rechercher.* +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_hyperscan_backend_enroll_plain_pattern(GHyperscanBackend *backend, const uint8_t *plain, size_t len, uint32_t tmp_id[2]) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + int ret; /* Bilan d'une comparaison */ + + result = true; + + /*Recherche d'un motif déjà sollicité */ + + i = backend->used; + + /* + for (i = 0; i < backend->used; i++) + { + if (backend->lengths[i] != len) + continue; + + ret = memcmp(backend->atoms[i], plain, backend->lengths[i]); + + if (ret == 0) + { + tmp_id[0] = i; + tmp_id[1] = backend->coverages[i * 2 + EXPR_COVERAGE_COUNT]; + + backend->coverages[i * 2 + EXPR_COVERAGE_COUNT]++; + break; + + } + + } + */ + + /* Introduction d'un nouveau motif au besoin */ + + if (i == backend->used) + { + if (backend->used == backend->allocated) + { + if (backend->allocated == 0) + backend->allocated = 6400; + else + backend->allocated *= 2; + + backend->atoms = realloc(backend->atoms, backend->allocated * sizeof(const uint8_t *)); + backend->lengths = realloc(backend->lengths, backend->allocated * sizeof(size_t)); + backend->coverages = realloc(backend->coverages, backend->allocated * 2 * sizeof(uint32_t)); + + } + + backend->atoms[i] = plain; + backend->lengths[i] = len; + backend->coverages[i * 2 + EXPR_COVERAGE_COUNT] = 1; + + backend->used++; + + tmp_id[0] = i; + tmp_id[1] = 0; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à préparer. * +* * +* Description : Met en ordre les derniers détails avant un premier scan. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +#include <fcntl.h> +#include "../../../../common/io.h" + +static bool g_hyperscan_backend_warm_up(GHyperscanBackend *backend) +{ + bool result; /* Bilan à retourner */ + uint32_t current_start; /* Indice de gestionnaire */ + size_t i; /* Boucle de parcours */ + hs_compile_error_t *error; /* Compléments d'information */ + hs_error_t ret; /* Code de retour */ + + hs_platform_info_t platform; + + result = false; + + /* Mise à jour de la couverture des gestionnaires de suivi */ + + current_start = 0; + + for (i = 0; i < backend->used; i++) + { + backend->coverages[i * 2 + EXPR_COVERAGE_START] = current_start; + backend->coverages[i * 2 + EXPR_COVERAGE_END] += current_start; + + current_start = backend->coverages[i * 2 + EXPR_COVERAGE_END]; + + } + + /* Enregistrement des expressions à prendre en compte */ + +#if 0 + backend->lit_ids = malloc(backend->used * sizeof(unsigned)); + + for (i = 0; i < backend->used; i++) + backend->lit_ids[i] = i; + +#else + + backend->lit_ids = __cached_ids; + +#endif + + + //hs_populate_platform(&platform); + + //platform.tune = 1; + + //platform.cpu_features = HS_CPU_FEATURES_AVX512; + +#if 0 + + ret = hs_compile_lit_multi((const char *const *)backend->atoms, NULL, backend->lit_ids, backend->lengths, + backend->used, HS_MODE_BLOCK, NULL, &backend->database, &error); + + + //printf("ret: %d -vs- %d\n", ret, HS_SUCCESS); + + if (ret != HS_SUCCESS) + { + log_variadic_message(LMT_EXT_ERROR, _("Unable to compile %zu patterns: \"%s\""), + backend->used, error->message); + printf("FAILED: %s\n", error->message); + hs_free_compile_error(error); + goto exit; + } + + do + { + char *bytes; + size_t length; + int fd; + + ret = hs_serialize_database(backend->database, &bytes, &length); + printf("ret: %d -vs- %d\n", ret, HS_SUCCESS); + + fd = open("/tmp/compiled.bin", O_WRONLY | O_CREAT | O_TRUNC, 0600); + + safe_write(fd, bytes, length); + + close(fd); + + } + while (0); + + +#else + + char *bytes; + size_t length; + bool status; + int fd; + + length = 674216; + bytes = malloc(length); + + fd = open("/tmp/compiled.bin", O_RDONLY); + + status = safe_read(fd, bytes, length); + + close(fd); + + //printf("status: %d\n", status); + + ret = hs_deserialize_database(bytes, length, &backend->database); + //printf("ret: %d -vs- %d\n", ret, HS_SUCCESS); + + + +#endif + + + +#if 0 + do + { + //hs_platform_info_t platform; + char *__info; + + //hs_populate_platform(&platform); + + printf("TUNE: %u\n", platform.tune); + + printf("CPU: %llx - AVX2? %d - AVX512? %d\n", platform.cpu_features, + platform.cpu_features & HS_CPU_FEATURES_AVX2, + platform.cpu_features & HS_CPU_FEATURES_AVX512); + + hs_database_info(backend->database, &__info); + + printf("INFO: %s\n", __info); + + } + while (0); +#endif + + /* Création d'un espace de travail */ + + ret = hs_alloc_scratch(backend->database, &backend->scratch); + + //printf("ret: %d -vs- %d\n", ret, HS_SUCCESS); + + if (ret != HS_SUCCESS) + { + log_variadic_message(LMT_EXT_ERROR, _("Unable to allocate scratch space")); + goto exit; + } + + result = true; + + exit: + + //printf("result: %d\n", result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* tmp_id = identifiants temporaires vers le motif. [OUT] * +* * +* Description : Récupère les identifiants finaux pour un motif recherché. * +* * +* Retour : Identifiant constitué ou INVALID_PATTERN_ID en cas d'échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static patid_t g_hyperscan_backend_build_plain_pattern_id(const GHyperscanBackend *backend, const uint32_t tmp_id[2]) +{ + patid_t result; /* Identifiant à retourner */ + size_t index; /* Indice reconstitué */ + + assert(tmp_id[0] < backend->used); + + index = tmp_id[0] * 2; + + result = backend->coverages[index + EXPR_COVERAGE_START] + tmp_id[1]; + + assert(result < backend->coverages[index + EXPR_COVERAGE_END]); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* * +* Description : Détermine le nombre d'identifiants constitués. * +* * +* Retour : Quantité de gestionnaires de suivi à prévoir. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static size_t g_hyperscan_backend_count_plain_pattern_ids(const GHyperscanBackend *backend) +{ + size_t result; /* Quantité à retourner */ + + if (backend->used == 0) + result = 0; + else + result = backend->coverages[(backend->used - 1) * 2 + EXPR_COVERAGE_END]; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* * +* Description : Prend note d'une correspondance trouvée par Hyperscan. * +* * +* Retour : 0 afin de poursuivre les recherches. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static int handle_hyperscan_match_event(unsigned int id, unsigned long long from, unsigned long long to, unsigned int flags, GScanContext *context/*const hyperscan_context_t *context*/) +{ + + g_scan_context_store_atom_match_end(context, id, to); + + return 0; + +#if 0 + + phys_t offset; /* Point de départ établi */ + const uint32_t *coverage_base; /* Base des suivis */ + uint32_t k; /* Boucle de parcours */ + uint32_t final_k; /* Dernier indice à traiter */ + + //return 0; + +#ifndef NDEBUG + assert(id < context->used); + assert(id == context->lit_ids[id]); +#endif + + offset = to - context->lengths[id]; + + coverage_base = context->coverages + id * 2; + + k = coverage_base[EXPR_COVERAGE_START]; + final_k = coverage_base[EXPR_COVERAGE_END]; + + for (; k < final_k; k++) + g_umem_slice_put_uint64(context->matches[0/*k*/], offset); + + return 0; + +#endif + +} + + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à manipuler. * +* context = lieu d'enregistrement des résultats. * +* * +* Description : Parcours un contenu binaire à la recherche de motifs. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_hyperscan_backend_run_scan(const GHyperscanBackend *backend, GScanContext *context) +{ + GBinContent *content; /* Contenu binaire manipulé */ + phys_t dlen; /* Quantité de données */ + vmpa2t pos; /* Point de départ ciblé */ + const bin_t *data; /* Données à analyser */ +#ifndef NDEBUG + size_t count; /* Nombre de zones prévues */ +#endif + hyperscan_context_t hcontext; /* Rassemblement d'informations*/ + GUMemSlice **matches; /* Zones d'enregistrements */ + hs_error_t ret; /* Code de retour */ + + /* Récupération d'un accès aux données */ + + content = g_scan_context_get_content(context); + + dlen = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &pos); + data = g_binary_content_get_raw_access(content, &pos, dlen); + + /* Préparation de l'accès aux éléments utiles */ + + hcontext.lengths = backend->lengths; + hcontext.coverages = backend->coverages; + +#ifndef NDEBUG + hcontext.used = backend->used; + hcontext.lit_ids = backend->lit_ids; +#endif + + /* +#ifndef NDEBUG + matches = g_scan_context_get_match_storages(context, &count); + assert(count == backend->used); +#else + matches = g_scan_context_get_match_storages(context, (size_t []){ 0 }); +#endif + */ + matches = NULL; /* REMME */ + + hcontext.matches = matches; + + /* Lancement de l'analyse */ + + ret = hs_scan(backend->database, (const char *)data, dlen, + 0 /* Arg. inutilisé */, backend->scratch, + (match_event_handler)handle_hyperscan_match_event, /*&h*/context); + + + //printf("ret ok? %d\n", ret == HS_SUCCESS); + + + + g_object_unref(G_OBJECT(content)); + +} + + +/****************************************************************************** +* * +* Paramètres : backend = moteur de recherche à consulter. * +* * +* Description : Imprime quelques faits quant aux éléments mis en place. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_hyperscan_backend_output_stats(const GHyperscanBackend *backend) +{ + printf("TODO: %s\n", __FUNCTION__); + +} diff --git a/src/analysis/scan/patterns/backends/hyperscan.h b/src/analysis/scan/patterns/backends/hyperscan.h new file mode 100644 index 0000000..d8c0f92 --- /dev/null +++ b/src/analysis/scan/patterns/backends/hyperscan.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hyperscan.h - prototypes pour la méthode de recherche basée sur la bibliothèque Hyperscan d'Intel + * + * Copyright (C) 2024 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_BACKENDS_HYPERSCAN_H +#define _ANALYSIS_SCAN_PATTERNS_BACKENDS_HYPERSCAN_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "../backend.h" + + + +#define G_TYPE_HYPERSCAN_BACKEND g_hyperscan_backend_get_type() +#define G_HYPERSCAN_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_HYPERSCAN_BACKEND, GHyperscanBackend)) +#define G_IS_HYPERSCAN_BACKEND(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_HYPERSCAN_BACKEND)) +#define G_HYPERSCAN_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_HYPERSCAN_BACKEND, GHyperscanBackendClass)) +#define G_IS_HYPERSCAN_BACKEND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_HYPERSCAN_BACKEND)) +#define G_HYPERSCAN_BACKEND_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_HYPERSCAN_BACKEND, GHyperscanBackendClass)) + + +/* Méthode de recherche basée sur une bibliothèque d'Intel : Hyperscan (instance) */ +typedef struct _GHyperscanBackend GHyperscanBackend; + +/* Méthode de recherche basée sur une bibliothèque d'Intel : Hyperscan (classe) */ +typedef struct _GHyperscanBackendClass GHyperscanBackendClass; + + +/* Indique le type défini pour un moteur de recherche pour données. */ +GType g_hyperscan_backend_get_type(void); + +/* Crée une méthode de recherche avec la bibliothèque Hyperscan. */ +GEngineBackend *g_hyperscan_backend_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_BACKENDS_HYPERSCAN_H */ diff --git a/src/analysis/scan/patterns/customizer-int.h b/src/analysis/scan/patterns/customizer-int.h new file mode 100644 index 0000000..9d49ab6 --- /dev/null +++ b/src/analysis/scan/patterns/customizer-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * customizer-int.h - prototypes internes pour la modification paramétrée d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_CUSTOMIZER_INT_H +#define _ANALYSIS_SCAN_CUSTOMIZER_INT_H + + +#include "customizer.h" +#include "modifier-int.h" + + + +/* Encadrement de transformation paramétrée d'une séquence d'octets (instance) */ +struct _GScanTokenCustomizer +{ + GScanTokenModifier parent; /* A laisser en premier */ + + GScanTokenModifier *effective; /* Modificateur effectif */ + + modifier_arg_t *args; /* Paramètres de transformation*/ + size_t count; /* Quantité de ces paramètres */ + +}; + +/* Encadrement de transformation paramétrée d'une séquence d'octets (classe) */ +struct _GScanTokenCustomizerClass +{ + GScanTokenModifierClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un encadrement de transformation de motifs. */ +bool g_scan_token_customizer_create(GScanTokenCustomizer *, const modifier_arg_t *); + + + +#endif /* _ANALYSIS_SCAN_CUSTOMIZER_INT_H */ diff --git a/src/analysis/scan/patterns/customizer.c b/src/analysis/scan/patterns/customizer.c new file mode 100644 index 0000000..9659957 --- /dev/null +++ b/src/analysis/scan/patterns/customizer.c @@ -0,0 +1,377 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * customizer.c - modification paramétrée d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "customizer.h" + + +#include <malloc.h> + + +#include "customizer-int.h" + + + +/* --------------------- TRANSFORMATION PERSONNALISEE DE MOTIFS --------------------- */ + + +/* Initialise la classe des transformations paramétrée. */ +static void g_scan_token_customizer_class_init(GScanTokenCustomizerClass *); + +/* Initialise une instance de transformation paramétrée. */ +static void g_scan_token_customizer_init(GScanTokenCustomizer *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_customizer_dispose(GScanTokenCustomizer *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_customizer_finalize(GScanTokenCustomizer *); + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_token_customizer_get_name(const GScanTokenCustomizer *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_token_customizer_transform(const GScanTokenCustomizer *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* TRANSFORMATION PERSONNALISEE DE MOTIFS */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transformation personnalisée d'une séquence d'octets. */ +G_DEFINE_TYPE(GScanTokenCustomizer, g_scan_token_customizer, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transformations paramétrée. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_customizer_class_init(GScanTokenCustomizerClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_customizer_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_customizer_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_token_customizer_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_token_customizer_transform; + +} + + +/****************************************************************************** +* * +* Paramètres : customizer = instance à initialiser. * +* * +* Description : Initialise une instance de transformation paramétrée. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_customizer_init(GScanTokenCustomizer *customizer) +{ + customizer->effective = NULL; + + customizer->args = NULL; + customizer->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : customizer = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_customizer_dispose(GScanTokenCustomizer *customizer) +{ + g_clear_object(&customizer->effective); + + G_OBJECT_CLASS(g_scan_token_customizer_parent_class)->dispose(G_OBJECT(customizer)); + +} + + +/****************************************************************************** +* * +* Paramètres : customizer = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_customizer_finalize(GScanTokenCustomizer *customizer) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < customizer->count; i++) + exit_mod_arg(&customizer->args[i]); + + if (customizer->args != NULL) + free(customizer->args); + + G_OBJECT_CLASS(g_scan_token_customizer_parent_class)->finalize(G_OBJECT(customizer)); + +} + + +/****************************************************************************** +* * +* Paramètres : arg = premier argument pour personnaliser l'opération. * +* * +* Description : Construit un encadrement de transformation de motifs. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_token_customizer_new(const modifier_arg_t *arg) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_CUSTOMIZER, NULL); + + if (!g_scan_token_customizer_create(G_SCAN_TOKEN_CUSTOMIZER(result), arg)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : customizer = encadrement de motif à initialiser pleinement. * +* arg = premier argument pour personnaliser l'opération.* +* * +* Description : Met en place un encadrement de transformation de motifs. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_customizer_create(GScanTokenCustomizer *customizer, const modifier_arg_t *arg) +{ + g_scan_token_customizer_add_extra_arg(customizer, arg); + + return true; + +} + + +/****************************************************************************** +* * +* Paramètres : customizer = encadrement de motif à compléter. * +* arg = nouvel argument pour personnaliser l'opération. * +* * +* Description : Ajoute un argument à l'encadrement de transformation. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_customizer_add_extra_arg(GScanTokenCustomizer *customizer, const modifier_arg_t *arg) +{ + customizer->args = realloc(customizer->args, ++customizer->count * sizeof(modifier_arg_t)); + + copy_mod_arg(&customizer->args[customizer->count - 1], arg); + +} + + +/****************************************************************************** +* * +* Paramètres : customizer = encadrement de motif à compléter. * +* modifier = modificateur de motifs à employer en sous-main. * +* * +* Description : Définit le transformateur effectif pour les motifs. * +* * +* Retour : true si le motificateur accepte les arguments courants. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_customizer_attach_modifier(GScanTokenCustomizer *customizer, GScanTokenModifier *modifier) +{ + bool result; /* Validation à retourner */ + size_t i; /* Boucle de parcours */ + + result = true; + + for (i = 0; i < customizer->count && result; i++) + result = g_scan_token_modifier_can_handle_arg(modifier, &customizer->args[i]); + + if (!result) goto exit; + + customizer->effective = modifier; + g_object_ref(G_OBJECT(modifier)); + + exit: + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_token_customizer_get_name(const GScanTokenCustomizer *modifier) +{ + char *result; /* Désignation à retourner */ + + if (modifier->effective == NULL) + result = NULL; + + else + result = g_scan_token_modifier_get_name(modifier->effective); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_customizer_transform(const GScanTokenCustomizer *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + size_t i; /* Boucle de parcours #1 */ + sized_binary_t *extra; /* Motifs supplémentaires */ + size_t extra_count; /* Quantité de ces motifs */ + size_t old_dcount; /* Mémorisation avant avancées */ + sized_binary_t *new; /* Nouvel emplacement libre */ + size_t k; /* Boucle de parcours #2 */ + + *dest = NULL; + *dcount = 0; + + for (i = 0; i < modifier->count; i++) + { + result = g_scan_token_modifier_transform_with_arg(modifier->effective, + src, scount, + &modifier->args[i], + &extra, &extra_count); + if (!result) goto exit; + + old_dcount = *dcount; + + *dcount += extra_count; + *dest = realloc(*dest, *dcount * sizeof(sized_binary_t)); + + new = (*dest) + old_dcount; + + for (k = 0; k < extra_count; k++, new++) + copy_szstr(*new, extra[k]); + + free(extra); + + } + + exit: + + if (!result) + { + for (i = 0; i < *dcount; i++) + exit_szstr(dest[i]); + + if (*dest != NULL) + free(*dest); + + *dest = NULL; + *dcount = 0; + + } + + return result; + +} diff --git a/src/analysis/scan/patterns/customizer.h b/src/analysis/scan/patterns/customizer.h new file mode 100644 index 0000000..845d9ff --- /dev/null +++ b/src/analysis/scan/patterns/customizer.h @@ -0,0 +1,65 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * customizer.h - prototypes pour la modification paramétrée d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_CUSTOMIZER_H +#define _ANALYSIS_SCAN_CUSTOMIZER_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "modifier.h" + + + +#define G_TYPE_SCAN_TOKEN_CUSTOMIZER g_scan_token_customizer_get_type() +#define G_SCAN_TOKEN_CUSTOMIZER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_CUSTOMIZER, GScanTokenCustomizer)) +#define G_IS_SCAN_TOKEN_CUSTOMIZER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_CUSTOMIZER)) +#define G_SCAN_TOKEN_CUSTOMIZER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_CUSTOMIZER, GScanTokenCustomizerClass)) +#define G_IS_SCAN_TOKEN_CUSTOMIZER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_CUSTOMIZER)) +#define G_SCAN_TOKEN_CUSTOMIZER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_CUSTOMIZER, GScanTokenCustomizerClass)) + + +/* Encadrement de transformation paramétrée d'une séquence d'octets (instance) */ +typedef struct _GScanTokenCustomizer GScanTokenCustomizer; + +/* Encadrement de transformation paramétrée d'une séquence d'octets (classe) */ +typedef struct _GScanTokenCustomizerClass GScanTokenCustomizerClass; + + +/* Indique le type défini pour une transformation personnalisée d'une séquence d'octets. */ +GType g_scan_token_customizer_get_type(void); + +/* Construit un encadrement de transformation de motifs. */ +GScanTokenModifier *g_scan_token_customizer_new(const modifier_arg_t *); + +/* Ajoute un argument à l'encadrement de transformation. */ +void g_scan_token_customizer_add_extra_arg(GScanTokenCustomizer *, const modifier_arg_t *); + +/* Définit le transformateur effectif pour les motifs. */ +bool g_scan_token_customizer_attach_modifier(GScanTokenCustomizer *, GScanTokenModifier *); + + + +#endif /* _ANALYSIS_SCAN_CUSTOMIZER_H */ diff --git a/src/analysis/scan/patterns/modarg.h b/src/analysis/scan/patterns/modarg.h new file mode 100644 index 0000000..d96e137 --- /dev/null +++ b/src/analysis/scan/patterns/modarg.h @@ -0,0 +1,91 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * modarg.h - prototypes pour la conservation d'arguments pour modificateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODARG_H +#define _ANALYSIS_SCAN_MODARG_H + + +#include <stdbool.h> + + +#include "../../../common/szstr.h" + + + +/* Types d'arguments pris en charge */ +typedef enum _ModifierArgType +{ + MAT_BOOLEAN, /* Valeur booléenne */ + MAT_SIGNED_INTEGER, /* Nombre entier 64 bits #1 */ + MAT_UNSIGNED_INTEGER, /* Nombre entier 64 bits #2 */ + MAT_STRING, /* Chaîne de caractères */ + MAT_RANGE, /* Séquence d'entiers */ + +} ModifierArgType; + +/* Argument pour modificateur de motif */ +typedef struct _modifier_arg_t +{ + ModifierArgType type; /* Type de valeur portée */ + + union + { + bool boolean; /* Valeur booléenne */ + long long s_integer; /* Valeur entière 64 bits */ + unsigned long long u_integer; /* Valeur entière 64 bits */ + sized_string_t string; /* Chaîne de caractères */ + + struct + { + long long start; /* Point de départ */ + long long end; /* Point d'arrivée */ + + } range; + + } value; + +} modifier_arg_t; + + +#define exit_mod_arg(a) \ + do \ + { \ + if ((a)->type == MAT_STRING) \ + exit_szstr(&(a)->value.string); \ + } \ + while (0) + +#define copy_mod_arg(d, s) \ + do \ + { \ + (d)->type = (s)->type; \ + if ((s)->type == MAT_STRING) \ + szstrdup(&(d)->value.string, &(s)->value.string); \ + else \ + *(d) = *(s); \ + } \ + while (0) + + + +#endif /* _ANALYSIS_SCAN_MODARG_H */ diff --git a/src/analysis/scan/patterns/modifier-int.h b/src/analysis/scan/patterns/modifier-int.h new file mode 100644 index 0000000..c9b3a36 --- /dev/null +++ b/src/analysis/scan/patterns/modifier-int.h @@ -0,0 +1,71 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * modifier-int.h - prototypes internes pour la modification d'une séquence d'octets pour un motif recherché + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODIFIER_INT_H +#define _ANALYSIS_SCAN_MODIFIER_INT_H + + +#include "modifier.h" + + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +typedef char * (* get_scan_modifier_name_fc) (const GScanTokenModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +typedef bool (* transform_scan_token_fc) (const GScanTokenModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Détermine si un argument est bien toléré par un modificateur. */ +typedef bool (* can_token_modifier_handle_arg) (const GScanTokenModifier *, const modifier_arg_t *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +typedef bool (* transform_scan_token_with_fc) (const GScanTokenModifier *, const sized_binary_t *, size_t, const modifier_arg_t *, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +typedef char * (* get_modifier_path) (const GScanTokenModifier *, size_t *); + + +/* Transformation d'une séquence d'octets en une ou plusieurs autres formes (instance) */ +struct _GScanTokenModifier +{ + GObject parent; /* A laisser en premier */ + +}; + +/* Transformation d'une séquence d'octets en une ou plusieurs autres formes (classe) */ +struct _GScanTokenModifierClass +{ + GObjectClass parent; /* A laisser en premier */ + + get_scan_modifier_name_fc get_name; /* Fourniture du nom d'appel */ + + transform_scan_token_fc transform; /* Opération de transformation */ + can_token_modifier_handle_arg can_handle; /* Support d'argument donné */ + transform_scan_token_with_fc transform_with; /* Opération encadrée */ + get_modifier_path get_path; /* Rappel d'une combinaison */ + +}; + + + +#endif /* _ANALYSIS_SCAN_MODIFIER_INT_H */ diff --git a/src/analysis/scan/patterns/modifier.c b/src/analysis/scan/patterns/modifier.c new file mode 100644 index 0000000..9efd404 --- /dev/null +++ b/src/analysis/scan/patterns/modifier.c @@ -0,0 +1,278 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * modifier.c - modification d'une séquence d'octets pour un motif recherché + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "modifier.h" + + +#include "modifier-int.h" + + + +/* Initialise la classe des transformations d'octets. */ +static void g_scan_token_modifier_class_init(GScanTokenModifierClass *); + +/* Initialise une instance de transformation d'octets. */ +static void g_scan_token_modifier_init(GScanTokenModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_modifier_dispose(GScanTokenModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_modifier_finalize(GScanTokenModifier *); + + + +/* Indique le type défini pour une transformation d'une séquence d'octets. */ +G_DEFINE_TYPE(GScanTokenModifier, g_scan_token_modifier, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transformations d'octets. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_modifier_class_init(GScanTokenModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_modifier_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transformation d'octets. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_modifier_init(GScanTokenModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_modifier_dispose(GScanTokenModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_token_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_modifier_finalize(GScanTokenModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_token_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_token_modifier_get_name(const GScanTokenModifier *modifier) +{ + char *result; /* Désignation à retourner */ + GScanTokenModifierClass *class; /* Classe à activer */ + + class = G_SCAN_TOKEN_MODIFIER_GET_CLASS(modifier); + + result = class->get_name(modifier); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_modifier_transform(const GScanTokenModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + GScanTokenModifierClass *class; /* Classe à activer */ + + class = G_SCAN_TOKEN_MODIFIER_GET_CLASS(modifier); + + result = class->transform(modifier, src, scount, dest, dcount); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* arg = argument de personnalisation. * +* * +* Description : Détermine si un argument est bien toléré par un modificateur.* +* * +* Retour : Bilan de la consultation : support ou non. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_modifier_can_handle_arg(const GScanTokenModifier *modifier, const modifier_arg_t *arg) +{ + bool result; /* Bilan d'opération à renvoyer*/ + GScanTokenModifierClass *class; /* Classe à activer */ + + class = G_SCAN_TOKEN_MODIFIER_GET_CLASS(modifier); + + if (class->can_handle == NULL) + result = false; + else + result = class->can_handle(modifier, arg); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* arg = argument de personnalisation. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_modifier_transform_with_arg(const GScanTokenModifier *modifier, const sized_binary_t *src, size_t scount, const modifier_arg_t *arg, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + GScanTokenModifierClass *class; /* Classe à activer */ + + result = false; + + if (!g_scan_token_modifier_can_handle_arg(modifier, arg)) + goto exit; + + class = G_SCAN_TOKEN_MODIFIER_GET_CLASS(modifier); + + if (class->transform_with != NULL) + result = class->transform_with(modifier, src, scount, arg, dest, dcount); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_token_modifier_get_path(const GScanTokenModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + GScanTokenModifierClass *class; /* Classe à activer */ + + class = G_SCAN_TOKEN_MODIFIER_GET_CLASS(modifier); + + result = class->get_path(modifier, index); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifier.h b/src/analysis/scan/patterns/modifier.h new file mode 100644 index 0000000..9030a72 --- /dev/null +++ b/src/analysis/scan/patterns/modifier.h @@ -0,0 +1,73 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * modifier.h - prototypes pour la modification d'une séquence d'octets pour un motif recherché + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODIFIER_H +#define _ANALYSIS_SCAN_MODIFIER_H + + +#include <glib-object.h> +#include <stdbool.h> + + + +#include "modarg.h" +#include "../../../common/szstr.h" + + + +#define G_TYPE_SCAN_TOKEN_MODIFIER g_scan_token_modifier_get_type() +#define G_SCAN_TOKEN_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_MODIFIER, GScanTokenModifier)) +#define G_IS_SCAN_TOKEN_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_MODIFIER)) +#define G_SCAN_TOKEN_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_MODIFIER, GScanTokenModifierClass)) +#define G_IS_SCAN_TOKEN_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_MODIFIER)) +#define G_SCAN_TOKEN_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_MODIFIER, GScanTokenModifierClass)) + + +/* Transformation d'une séquence d'octets en une ou plusieurs autres formes (instance) */ +typedef struct _GScanTokenModifier GScanTokenModifier; + +/* Transformation d'une séquence d'octets en une ou plusieurs autres formes (classe) */ +typedef struct _GScanTokenModifierClass GScanTokenModifierClass; + + +/* Indique le type défini pour une transformation d'une séquence d'octets. */ +GType g_scan_token_modifier_get_type(void); + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +char *g_scan_token_modifier_get_name(const GScanTokenModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +bool g_scan_token_modifier_transform(const GScanTokenModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Détermine si un argument est bien toléré par un modificateur. */ +bool g_scan_token_modifier_can_handle_arg(const GScanTokenModifier *, const modifier_arg_t *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +bool g_scan_token_modifier_transform_with_arg(const GScanTokenModifier *, const sized_binary_t *, size_t, const modifier_arg_t *, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +char *g_scan_token_modifier_get_path(const GScanTokenModifier *, size_t *); + + + +#endif /* _ANALYSIS_SCAN_MODIFIER_H */ diff --git a/src/analysis/scan/patterns/modifiers/Makefile.am b/src/analysis/scan/patterns/modifiers/Makefile.am new file mode 100644 index 0000000..da046b9 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/Makefile.am @@ -0,0 +1,23 @@ + +noinst_LTLIBRARIES = libanalysisscanpatternsmodifiers.la + + +libanalysisscanpatternsmodifiers_la_SOURCES = \ + hex.h hex.c \ + list-int.h \ + list.h list.c \ + lower.h lower.c \ + pipe-int.h \ + pipe.h pipe.c \ + plain.h plain.c \ + rev.h rev.c \ + upper.h upper.c \ + wide.h wide.c \ + xor.h xor.c + +libanalysisscanpatternsmodifiers_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanpatternsmodifiers_la_SOURCES:%c=) diff --git a/src/analysis/scan/patterns/modifiers/hex.c b/src/analysis/scan/patterns/modifiers/hex.c new file mode 100644 index 0000000..4a41c7d --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/hex.c @@ -0,0 +1,296 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hex.c - transformation en version hexadécimale d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "hex.h" + + +#include <malloc.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transformations en hexadécimal. */ +static void g_scan_hex_modifier_class_init(GScanHexModifierClass *klass); + +/* Initialise une instance de transformation en hexadécimal. */ +static void g_scan_hex_modifier_init(GScanHexModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_hex_modifier_dispose(GScanHexModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_hex_modifier_finalize(GScanHexModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_hex_modifier_get_name(const GScanHexModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_hex_modifier_transform(const GScanHexModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_hex_modifier_get_path(const GScanHexModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transformation d'une séquence d'octets dans sa version hexadécimale. */ +G_DEFINE_TYPE(GScanHexModifier, g_scan_hex_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transformations en hexadécimal. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_modifier_class_init(GScanHexModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_hex_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_hex_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_hex_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_hex_modifier_transform; + modifier->get_path = (get_modifier_path)g_scan_hex_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transformation en hexadécimal. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_modifier_init(GScanHexModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_modifier_dispose(GScanHexModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_hex_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_modifier_finalize(GScanHexModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_hex_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur fournistant une vue hexadécimale. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_hex_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_HEX_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_hex_modifier_get_name(const GScanHexModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("hex"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_hex_modifier_transform(const GScanHexModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + size_t k; /* Boucle de parcours #2 */ + + static char *alphabet = "0123456789abcdef"; + + result = true; + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++, binary++) + { + _src = src + i; + + binary->len = _src->len * 2; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + { + binary->data[k * 2 + 0] = alphabet[_src->data[k] >> 4]; + binary->data[k * 2 + 1] = alphabet[_src->data[k] & 0xf]; + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_hex_modifier_get_path(const GScanHexModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + + if (*index > 0) + { + result = NULL; + (*index)--; + } + + else + result = strdup("hex"); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/hex.h b/src/analysis/scan/patterns/modifiers/hex.h new file mode 100644 index 0000000..1a9b410 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/hex.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hex.h - prototypes pour la transformation en version hexadécimale d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_HEX_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_HEX_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_HEX_MODIFIER g_scan_hex_modifier_get_type() +#define G_SCAN_HEX_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_HEX_MODIFIER, GScanHexModifier)) +#define G_IS_SCAN_HEX_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_HEX_MODIFIER)) +#define G_SCAN_HEX_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_HEX_MODIFIER, GScanHexModifierClass)) +#define G_IS_SCAN_HEX_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_HEX_MODIFIER)) +#define G_SCAN_HEX_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_HEX_MODIFIER, GScanHexModifierClass)) + + +/* Transformation d'une séquence d'octets dans sa version hexadécimale (instance) */ +typedef GScanTokenModifier GScanHexModifier; + +/* Transformation d'une séquence d'octets dans sa version hexadécimale (classe) */ +typedef GScanTokenModifierClass GScanHexModifierClass; + + +/* Indique le type défini pour une transformation d'une séquence d'octets dans sa version hexadécimale. */ +GType g_scan_hex_modifier_get_type(void); + +/* Construit un modificateur fournistant une vue hexadécimale. */ +GScanTokenModifier *g_scan_hex_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_HEX_H */ diff --git a/src/analysis/scan/patterns/modifiers/list-int.h b/src/analysis/scan/patterns/modifiers/list-int.h new file mode 100644 index 0000000..3ba253e --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/list-int.h @@ -0,0 +1,54 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * list-int.h - prototypes internes pour la gestion d'une liste de transformateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODIFIERS_LIST_INT_H +#define _ANALYSIS_SCAN_MODIFIERS_LIST_INT_H + + +#include "list.h" + + +#include "../modifier-int.h" + + + +/* Liste de transformations d'une séquence d'octets (instance) */ +struct _GScanModifierList +{ + GScanTokenModifier parent; /* A laisser en premier */ + + GScanTokenModifier **modifiers; /* Liste de transformateurs */ + size_t count; /* Taille de cette liste */ + +}; + +/* Liste de transformations d'une séquence d'octets (classe) */ +struct _GScanModifierListClass +{ + GScanTokenModifierClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_MODIFIERS_LIST_INT_H */ diff --git a/src/analysis/scan/patterns/modifiers/list.c b/src/analysis/scan/patterns/modifiers/list.c new file mode 100644 index 0000000..86fd19f --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/list.c @@ -0,0 +1,438 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * list.c - gestion d'une liste de transformateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "list.h" + + +#include <assert.h> +#include <malloc.h> + + +#include "list-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des liste de transformations d'octets. */ +static void g_scan_modifier_list_class_init(GScanModifierListClass *); + +/* Initialise une instance de liste de transformations d'octets. */ +static void g_scan_modifier_list_init(GScanModifierList *); + +/* Supprime toutes les références externes. */ +static void g_scan_modifier_list_dispose(GScanModifierList *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_modifier_list_finalize(GScanModifierList *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_modifier_list_get_name(const GScanModifierList *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_modifier_list_transform(const GScanModifierList *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_modifier_list_get_path(const GScanModifierList *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une série de transformations d'octets. */ +G_DEFINE_TYPE(GScanModifierList, g_scan_modifier_list, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des liste de transformations d'octets. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_list_class_init(GScanModifierListClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_modifier_list_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_modifier_list_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_modifier_list_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_modifier_list_transform; + modifier->get_path = (get_modifier_path)g_scan_modifier_list_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : list = instance à initialiser. * +* * +* Description : Initialise une instance de liste de transformations d'octets.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_list_init(GScanModifierList *list) +{ + list->modifiers = NULL; + list->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : list = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_list_dispose(GScanModifierList *list) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < list->count; i++) + g_clear_object(&list->modifiers[i]); + + G_OBJECT_CLASS(g_scan_modifier_list_parent_class)->dispose(G_OBJECT(list)); + +} + + +/****************************************************************************** +* * +* Paramètres : list = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_list_finalize(GScanModifierList *list) +{ + if (list->modifiers != NULL) + free(list->modifiers); + + G_OBJECT_CLASS(g_scan_modifier_list_parent_class)->finalize(G_OBJECT(list)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit une liste de modificateurs d'octets. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_modifier_list_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MODIFIER_LIST, NULL); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : list = liste de modificateurs à étendre. * +* modifier = modificateur à intégrer. * +* * +* Description : Intègre un nouveau transformateur dans une liste. * +* * +* Retour : Bilan de l'ajout : false si un élément similaire est déjà là.* +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_modifier_list_add(GScanModifierList *list, GScanTokenModifier *modifier) +{ + bool result; /* Bilan à retourner */ + char *name; /* Désignation du modificateur */ + size_t i; /* Boucle de parcours */ + char *other; /* Désignation de ses collègues*/ + + /* Recherche d'une redondance */ + + /** + * Note : deux listes identiques passent sans soucis. + * TODO : comparer les transformateurs ? + */ + + result = true; + + if (!G_IS_SCAN_MODIFIER_LIST(modifier)) + { + name = g_scan_token_modifier_get_name(modifier); + + for (i = 0; i < list->count && result; i++) + { + if (G_IS_SCAN_MODIFIER_LIST(list->modifiers[i])) + continue; + + other = g_scan_token_modifier_get_name(list->modifiers[i]); + + result = (strcmp(name, other) != 0); + + free(other); + + } + + free(name); + + } + + if (!result) + goto done; + + /* Inclusion dans la liste */ + + list->modifiers = realloc(list->modifiers, ++list->count * sizeof(GScanTokenModifier *)); + + list->modifiers[list->count - 1] = modifier; + g_object_ref(G_OBJECT(modifier)); + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : list = série à consulter. * +* * +* Description : Indique le nombre de transformateurs intégrés dans la liste. * +* * +* Retour : Nombre de modificateurs représentés. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_scan_modifier_list_count(const GScanModifierList *list) +{ + size_t result; /* Quantité à retourner */ + + result = list->count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : list = série à consulter. * +* index = indice du paramètre à retourner. * +* * +* Description : Fournit un transformateur donné de la liste. * +* * +* Retour : Modificateur inclus dans la liste ou NULL si mauvais indice. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_modifier_list_get(const GScanModifierList *list, size_t index) +{ + GScanTokenModifier *result; /* Instance à retourner */ + + assert(index < list->count); + + if (index < list->count) + { + result = list->modifiers[index]; + g_object_ref(G_OBJECT(result)); + } + + else + result = NULL; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_modifier_list_get_name(const GScanModifierList *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("(list)"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_modifier_list_transform(const GScanModifierList *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + size_t i; /* Boucle de parcours #1 */ + sized_binary_t *extra; /* Motifs supplémentaires */ + size_t extra_count; /* Quantité de ces motifs */ + sized_binary_t *new; /* Nouvel emplacement libre */ + size_t k; /* Boucle de parcours #2 */ + + *dest = NULL; + *dcount = 0; + + for (i = 0; i < modifier->count; i++) + { + result = g_scan_token_modifier_transform(modifier->modifiers[i], src, scount, &extra, &extra_count); + if (!result) goto exit; + + *dcount += extra_count; + *dest = realloc(*dest, *dcount * sizeof(sized_binary_t)); + + new = (*dest) + *dcount - extra_count; + + for (k = 0; k < extra_count; k++, new++) + copy_szstr(*new, extra[k]); + + free(extra); + + } + + exit: + + if (!result) + { + for (i = 0; i < *dcount; i++) + exit_szstr(dest[i]); + + if (*dest != NULL) + free(*dest); + + *dest = NULL; + *dcount = 0; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_modifier_list_get_path(const GScanModifierList *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + size_t i; /* Boucle de parcours #1 */ + + result = NULL; + + for (i = 0; i < modifier->count && result == NULL; i++) + result = g_scan_token_modifier_get_path(modifier->modifiers[i], index); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/list.h b/src/analysis/scan/patterns/modifiers/list.h new file mode 100644 index 0000000..abd1eae --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/list.h @@ -0,0 +1,68 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * list.h - prototypes pour la gestion d'une liste de transformateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODIFIERS_LIST_H +#define _ANALYSIS_SCAN_MODIFIERS_LIST_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_MODIFIER_LIST g_scan_modifier_list_get_type() +#define G_SCAN_MODIFIER_LIST(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MODIFIER_LIST, GScanModifierList)) +#define G_IS_SCAN_MODIFIER_LIST(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MODIFIER_LIST)) +#define G_SCAN_MODIFIER_LIST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MODIFIER_LIST, GScanModifierListClass)) +#define G_IS_SCAN_MODIFIER_LIST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MODIFIER_LIST)) +#define G_SCAN_MODIFIER_LIST_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MODIFIER_LIST, GScanModifierListClass)) + + +/* Liste de transformations d'une séquence d'octets (instance) */ +typedef struct _GScanModifierList GScanModifierList; + +/* Liste de transformations d'une séquence d'octets (classe) */ +typedef struct _GScanModifierListClass GScanModifierListClass; + + +/* Indique le type défini pour une série de transformations d'octets. */ +GType g_scan_modifier_list_get_type(void); + +/* Construit une liste de modificateurs d'octets. */ +GScanTokenModifier *g_scan_modifier_list_new(void); + +/* Intègre un nouveau transformateur dans une liste. */ +bool g_scan_modifier_list_add(GScanModifierList *, GScanTokenModifier *); + +/* Indique le nombre de transformateurs intégrés dans la liste. */ +size_t g_scan_modifier_list_count(const GScanModifierList *); + +/* Fournit un transformateur donné de la liste. */ +GScanTokenModifier *g_scan_modifier_list_get(const GScanModifierList *, size_t); + + + +#endif /* _ANALYSIS_SCAN_MODIFIERS_LIST_H */ diff --git a/src/analysis/scan/patterns/modifiers/lower.c b/src/analysis/scan/patterns/modifiers/lower.c new file mode 100644 index 0000000..3904c52 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/lower.c @@ -0,0 +1,301 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * lower.c - transformation d'une séquence d'octets par passage en minuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "lower.h" + + +#include <malloc.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transmissions en minuscules. */ +static void g_scan_lower_modifier_class_init(GScanLowerModifierClass *klass); + +/* Initialise une instance de transmission en minuscules. */ +static void g_scan_lower_modifier_init(GScanLowerModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_lower_modifier_dispose(GScanLowerModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_lower_modifier_finalize(GScanLowerModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_lower_modifier_get_name(const GScanLowerModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_lower_modifier_transform(const GScanLowerModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_lower_modifier_get_path(const GScanLowerModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transformation par bascule en minuscules. */ +G_DEFINE_TYPE(GScanLowerModifier, g_scan_lower_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transmissions en minuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_lower_modifier_class_init(GScanLowerModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_lower_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_lower_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_lower_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_lower_modifier_transform; + modifier->get_path = (get_modifier_path)g_scan_lower_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transmission en minuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_lower_modifier_init(GScanLowerModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_lower_modifier_dispose(GScanLowerModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_lower_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_lower_modifier_finalize(GScanLowerModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_lower_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur livrant des octets en minuscules. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_lower_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_LOWER_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_lower_modifier_get_name(const GScanLowerModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("lower"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_lower_modifier_transform(const GScanLowerModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + size_t k; /* Boucle de parcours #2 */ + + result = true; + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++, binary++) + { + _src = src + i; + + binary->len = _src->len; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + switch (_src->data[k]) + { + case 'A' ... 'Z': + binary->data[k] = _src->data[k] + 0x20; + break; + + default: + binary->data[k] = _src->data[k]; + break; + + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_lower_modifier_get_path(const GScanLowerModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + + if (*index > 0) + { + result = NULL; + (*index)--; + } + + else + result = strdup("lower"); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/lower.h b/src/analysis/scan/patterns/modifiers/lower.h new file mode 100644 index 0000000..d361340 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/lower.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * lower.h - prototypes pour la transformation d'une séquence d'octets par passage en minuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_LOWER_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_LOWER_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_LOWER_MODIFIER g_scan_lower_modifier_get_type() +#define G_SCAN_LOWER_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_LOWER_MODIFIER, GScanLowerModifier)) +#define G_IS_SCAN_LOWER_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_LOWER_MODIFIER)) +#define G_SCAN_LOWER_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_LOWER_MODIFIER, GScanLowerModifierClass)) +#define G_IS_SCAN_LOWER_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_LOWER_MODIFIER)) +#define G_SCAN_LOWER_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_LOWER_MODIFIER, GScanLowerModifierClass)) + + +/* Transformation d'une séquence d'octets par passage en minuscules (instance) */ +typedef GScanTokenModifier GScanLowerModifier; + +/* Transformation d'une séquence d'octets par passage en minuscules (classe) */ +typedef GScanTokenModifierClass GScanLowerModifierClass; + + +/* Indique le type défini pour une transformation par bascule en minuscules. */ +GType g_scan_lower_modifier_get_type(void); + +/* Construit un modificateur livrant des octets en minuscules. */ +GScanTokenModifier *g_scan_lower_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_LOWER_H */ diff --git a/src/analysis/scan/patterns/modifiers/pipe-int.h b/src/analysis/scan/patterns/modifiers/pipe-int.h new file mode 100644 index 0000000..63c4d97 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/pipe-int.h @@ -0,0 +1,54 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pipe-int.h - prototypes internes pour la gestion de combinaisons de transformateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODIFIERS_PIPE_INT_H +#define _ANALYSIS_SCAN_MODIFIERS_PIPE_INT_H + + +#include "pipe.h" + + +#include "../modifier-int.h" + + + +/* Enchainement combinatoire de transformations d'octets (instance) */ +struct _GScanModifierPipe +{ + GScanTokenModifier parent; /* A laisser en premier */ + + GScanTokenModifier **modifiers; /* Pipee de transformateurs */ + size_t count; /* Taille de cette pipee */ + +}; + +/* Enchainement combinatoire de transformations d'octets (classe) */ +struct _GScanModifierPipeClass +{ + GScanTokenModifierClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_MODIFIERS_PIPE_INT_H */ diff --git a/src/analysis/scan/patterns/modifiers/pipe.c b/src/analysis/scan/patterns/modifiers/pipe.c new file mode 100644 index 0000000..7c659ea --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/pipe.c @@ -0,0 +1,405 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pipe.c - gestion de combinaisons de transformateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "pipe.h" + + +#include <assert.h> +#include <malloc.h> + + +#include "pipe-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des pipee de transformations d'octets. */ +static void g_scan_modifier_pipe_class_init(GScanModifierPipeClass *); + +/* Initialise une instance de pipee de transformations d'octets. */ +static void g_scan_modifier_pipe_init(GScanModifierPipe *); + +/* Supprime toutes les références externes. */ +static void g_scan_modifier_pipe_dispose(GScanModifierPipe *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_modifier_pipe_finalize(GScanModifierPipe *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_modifier_pipe_get_name(const GScanModifierPipe *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_modifier_pipe_transform(const GScanModifierPipe *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_modifier_pipe_get_path(const GScanModifierPipe *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une série de transformations d'octets. */ +G_DEFINE_TYPE(GScanModifierPipe, g_scan_modifier_pipe, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des pipee de transformations d'octets. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_pipe_class_init(GScanModifierPipeClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_modifier_pipe_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_modifier_pipe_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_modifier_pipe_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_modifier_pipe_transform; + modifier->get_path = (get_modifier_path)g_scan_modifier_pipe_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : pipe = instance à initialiser. * +* * +* Description : Initialise une instance de pipee de transformations d'octets.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_pipe_init(GScanModifierPipe *pipe) +{ + pipe->modifiers = NULL; + pipe->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : pipe = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_pipe_dispose(GScanModifierPipe *pipe) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < pipe->count; i++) + g_clear_object(&pipe->modifiers[i]); + + G_OBJECT_CLASS(g_scan_modifier_pipe_parent_class)->dispose(G_OBJECT(pipe)); + +} + + +/****************************************************************************** +* * +* Paramètres : pipe = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_modifier_pipe_finalize(GScanModifierPipe *pipe) +{ + if (pipe->modifiers != NULL) + free(pipe->modifiers); + + G_OBJECT_CLASS(g_scan_modifier_pipe_parent_class)->finalize(G_OBJECT(pipe)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit une pipee de modificateurs d'octets. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_modifier_pipe_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_MODIFIER_PIPE, NULL); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : pipe = pipee de modificateurs à étendre. * +* modifier = modificateur à intégrer. * +* * +* Description : Intègre un nouveau transformateur à enchaîner. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_modifier_pipe_add(GScanModifierPipe *pipe, GScanTokenModifier *modifier) +{ + pipe->modifiers = realloc(pipe->modifiers, ++pipe->count * sizeof(GScanTokenModifier *)); + + pipe->modifiers[pipe->count - 1] = modifier; + g_object_ref(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : pipe = série à consulter. * +* * +* Description : Indique le nombre de transformateurs intégrés dans la série. * +* * +* Retour : Nombre de modificateurs représentés. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_scan_modifier_pipe_count(const GScanModifierPipe *pipe) +{ + size_t result; /* Quantité à retourner */ + + result = pipe->count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : pipe = série à consulter. * +* index = indice du paramètre à retourner. * +* * +* Description : Fournit un transformateur donné de la série. * +* * +* Retour : Modificateur inclus dans la pipee ou NULL si mauvais indice. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_modifier_pipe_get(const GScanModifierPipe *pipe, size_t index) +{ + GScanTokenModifier *result; /* Instance à retourner */ + + assert(index < pipe->count); + + if (index < pipe->count) + { + result = pipe->modifiers[index]; + g_object_ref(G_OBJECT(result)); + } + + else + result = NULL; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_modifier_pipe_get_name(const GScanModifierPipe *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("(pipe)"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_modifier_pipe_transform(const GScanModifierPipe *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + size_t i; /* Boucle de parcours #1 */ + sized_binary_t *tmp_in; /* Motifs supplémentaires */ + size_t tmp_in_count; /* Quantité de ces motifs */ + sized_binary_t *tmp_out; /* Motifs supplémentaires */ + size_t tmp_out_count; /* Quantité de ces motifs */ + size_t k; /* Boucle de parcours #2 */ + + for (i = 0; i < modifier->count; i++) + { + if (i == 0) + result = g_scan_token_modifier_transform(modifier->modifiers[i], + src, scount, &tmp_out, &tmp_out_count); + + else + { + tmp_in = tmp_out; + tmp_in_count = tmp_out_count; + + result = g_scan_token_modifier_transform(modifier->modifiers[i], + tmp_in, tmp_in_count, &tmp_out, &tmp_out_count); + + for (k = 0; k < tmp_in_count; k++) + exit_szstr(&tmp_in[k]); + + if (tmp_in != NULL) + free(tmp_in); + + } + + if (!result) + break; + + } + + if (!result) + { + for (k = 0; k < tmp_out_count; k++) + exit_szstr(&tmp_out[k]); + + if (tmp_out != NULL) + free(tmp_out); + + *dest = NULL; + *dcount = 0; + + } + else + { + *dcount += tmp_out_count; + *dest = tmp_out; + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_modifier_pipe_get_path(const GScanModifierPipe *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + size_t i; /* Boucle de parcours #1 */ + + result = NULL; + + for (i = 0; i < modifier->count && result == NULL; i++) + result = g_scan_token_modifier_get_path(modifier->modifiers[i], index); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/pipe.h b/src/analysis/scan/patterns/modifiers/pipe.h new file mode 100644 index 0000000..8f9ca48 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/pipe.h @@ -0,0 +1,68 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * pipe.h - prototypes pour la gestion de combinaisons de transformateurs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_MODIFIERS_PIPE_H +#define _ANALYSIS_SCAN_MODIFIERS_PIPE_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_MODIFIER_PIPE g_scan_modifier_pipe_get_type() +#define G_SCAN_MODIFIER_PIPE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_MODIFIER_PIPE, GScanModifierPipe)) +#define G_IS_SCAN_MODIFIER_PIPE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_MODIFIER_PIPE)) +#define G_SCAN_MODIFIER_PIPE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_MODIFIER_PIPE, GScanModifierPipeClass)) +#define G_IS_SCAN_MODIFIER_PIPE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_MODIFIER_PIPE)) +#define G_SCAN_MODIFIER_PIPE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_MODIFIER_PIPE, GScanModifierPipeClass)) + + +/* Enchainement combinatoire de transformations d'octets (instance) */ +typedef struct _GScanModifierPipe GScanModifierPipe; + +/* Enchainement combinatoire de transformations d'octets (classe) */ +typedef struct _GScanModifierPipeClass GScanModifierPipeClass; + + +/* Indique le type défini pour une série de transformations d'octets. */ +GType g_scan_modifier_pipe_get_type(void); + +/* Construit une pipee de modificateurs d'octets. */ +GScanTokenModifier *g_scan_modifier_pipe_new(void); + +/* Intègre un nouveau transformateur à enchaîner. */ +void g_scan_modifier_pipe_add(GScanModifierPipe *, GScanTokenModifier *); + +/* Indique le nombre de transformateurs intégrés dans la série. */ +size_t g_scan_modifier_pipe_count(const GScanModifierPipe *); + +/* Fournit un transformateur donné de la pipee. */ +GScanTokenModifier *g_scan_modifier_pipe_get(const GScanModifierPipe *, size_t); + + + +#endif /* _ANALYSIS_SCAN_MODIFIERS_PIPE_H */ diff --git a/src/analysis/scan/patterns/modifiers/plain.c b/src/analysis/scan/patterns/modifiers/plain.c new file mode 100644 index 0000000..ad09129 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/plain.c @@ -0,0 +1,289 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain.c - transmission à l'identique d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "plain.h" + + +#include <malloc.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transmissions à l'identique. */ +static void g_scan_plain_modifier_class_init(GScanPlainModifierClass *klass); + +/* Initialise une instance de transmission à l'identique. */ +static void g_scan_plain_modifier_init(GScanPlainModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_plain_modifier_dispose(GScanPlainModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_plain_modifier_finalize(GScanPlainModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_plain_modifier_get_name(const GScanPlainModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_plain_modifier_transform(const GScanPlainModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_plain_modifier_get_path(const GScanPlainModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transmission à l'identique d'une séquence d'octets. */ +G_DEFINE_TYPE(GScanPlainModifier, g_scan_plain_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transmissions à l'identique. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_modifier_class_init(GScanPlainModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_plain_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_plain_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_plain_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_plain_modifier_transform; + modifier->get_path = (get_modifier_path)g_scan_plain_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transmission à l'identique. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_modifier_init(GScanPlainModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_modifier_dispose(GScanPlainModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_plain_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_modifier_finalize(GScanPlainModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_plain_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur livrant des octets à l'identique. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_plain_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_PLAIN_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_plain_modifier_get_name(const GScanPlainModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("plain"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_plain_modifier_transform(const GScanPlainModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours */ + const sized_binary_t *_src; /* Source courante */ + + result = true; + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++, binary++) + { + _src = src + i; + + binary->len = _src->len; + binary->data = malloc(binary->len); + + memcpy(binary->data, _src->data, _src->len); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_plain_modifier_get_path(const GScanPlainModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + + if (*index > 0) + { + result = NULL; + (*index)--; + } + + else + result = strdup("plain"); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/plain.h b/src/analysis/scan/patterns/modifiers/plain.h new file mode 100644 index 0000000..ecabefd --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/plain.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain.h - prototypes pour la transmission à l'identique d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_PLAIN_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_PLAIN_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_PLAIN_MODIFIER g_scan_plain_modifier_get_type() +#define G_SCAN_PLAIN_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_PLAIN_MODIFIER, GScanPlainModifier)) +#define G_IS_SCAN_PLAIN_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_PLAIN_MODIFIER)) +#define G_SCAN_PLAIN_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_PLAIN_MODIFIER, GScanPlainModifierClass)) +#define G_IS_SCAN_PLAIN_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_PLAIN_MODIFIER)) +#define G_SCAN_PLAIN_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_PLAIN_MODIFIER, GScanPlainModifierClass)) + + +/* Transmission à l'identique d'une séquence d'octets (instance) */ +typedef GScanTokenModifier GScanPlainModifier; + +/* Transmission à l'identique d'une séquence d'octets (classe) */ +typedef GScanTokenModifierClass GScanPlainModifierClass; + + +/* Indique le type défini pour une transmission à l'identique d'une séquence d'octets. */ +GType g_scan_plain_modifier_get_type(void); + +/* Construit un modificateur livrant des octets à l'identique. */ +GScanTokenModifier *g_scan_plain_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_PLAIN_H */ diff --git a/src/analysis/scan/patterns/modifiers/rev.c b/src/analysis/scan/patterns/modifiers/rev.c new file mode 100644 index 0000000..ef4d5fa --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/rev.c @@ -0,0 +1,291 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * rev.c - transormation via inversement d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "rev.h" + + +#include <malloc.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transmissions via inversement. */ +static void g_scan_reverse_modifier_class_init(GScanReverseModifierClass *klass); + +/* Initialise une instance de transmission via inversement. */ +static void g_scan_reverse_modifier_init(GScanReverseModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_reverse_modifier_dispose(GScanReverseModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_reverse_modifier_finalize(GScanReverseModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_reverse_modifier_get_name(const GScanReverseModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_reverse_modifier_transform(const GScanReverseModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_reverse_modifier_get_path(const GScanReverseModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transormation via inversement d'une séquence d'octets. */ +G_DEFINE_TYPE(GScanReverseModifier, g_scan_reverse_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transmissions via inversement. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_reverse_modifier_class_init(GScanReverseModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_reverse_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_reverse_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_reverse_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_reverse_modifier_transform; + modifier->get_path = (get_modifier_path)g_scan_reverse_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transmission via inversement. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_reverse_modifier_init(GScanReverseModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_reverse_modifier_dispose(GScanReverseModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_reverse_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_reverse_modifier_finalize(GScanReverseModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_reverse_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur livrant des octets inversés. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_reverse_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_REVERSE_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_reverse_modifier_get_name(const GScanReverseModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("rev"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_reverse_modifier_transform(const GScanReverseModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + size_t k; /* Boucle de parcours #2 */ + + result = true; + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++, binary++) + { + _src = src + i; + + binary->len = _src->len; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + binary->data[_src->len - k - 1] = _src->data[k]; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_reverse_modifier_get_path(const GScanReverseModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + + if (*index > 0) + { + result = NULL; + (*index)--; + } + + else + result = strdup("rev"); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/rev.h b/src/analysis/scan/patterns/modifiers/rev.h new file mode 100644 index 0000000..5b4e398 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/rev.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * rev.h - prototypes pour la transormation via inversement d'une séquence d'octets + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_REV_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_REV_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_REVERSE_MODIFIER g_scan_reverse_modifier_get_type() +#define G_SCAN_REVERSE_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_REVERSE_MODIFIER, GScanReverseModifier)) +#define G_IS_SCAN_REVERSE_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_REVERSE_MODIFIER)) +#define G_SCAN_REVERSE_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_REVERSE_MODIFIER, GScanReverseModifierClass)) +#define G_IS_SCAN_REVERSE_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_REVERSE_MODIFIER)) +#define G_SCAN_REVERSE_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_REVERSE_MODIFIER, GScanReverseModifierClass)) + + +/* Transormation via inversement d'une séquence d'octets (instance) */ +typedef GScanTokenModifier GScanReverseModifier; + +/* Transormation via inversement d'une séquence d'octets (classe) */ +typedef GScanTokenModifierClass GScanReverseModifierClass; + + +/* Indique le type défini pour une transormation via inversement d'une séquence d'octets. */ +GType g_scan_reverse_modifier_get_type(void); + +/* Construit un modificateur livrant des octets inversés. */ +GScanTokenModifier *g_scan_reverse_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_REV_H */ diff --git a/src/analysis/scan/patterns/modifiers/upper.c b/src/analysis/scan/patterns/modifiers/upper.c new file mode 100644 index 0000000..9d1086b --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/upper.c @@ -0,0 +1,301 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * upper.c - transformation d'une séquence d'octets par passage en majuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "upper.h" + + +#include <malloc.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transmissions en majuscules. */ +static void g_scan_upper_modifier_class_init(GScanUpperModifierClass *klass); + +/* Initialise une instance de transmission en majuscules. */ +static void g_scan_upper_modifier_init(GScanUpperModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_upper_modifier_dispose(GScanUpperModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_upper_modifier_finalize(GScanUpperModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_upper_modifier_get_name(const GScanUpperModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_upper_modifier_transform(const GScanUpperModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_upper_modifier_get_path(const GScanUpperModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transformation par bascule en majuscules. */ +G_DEFINE_TYPE(GScanUpperModifier, g_scan_upper_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transmissions en majuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_upper_modifier_class_init(GScanUpperModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_upper_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_upper_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_upper_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_upper_modifier_transform; + modifier->get_path = (get_modifier_path)g_scan_upper_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transmission en majuscules. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_upper_modifier_init(GScanUpperModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_upper_modifier_dispose(GScanUpperModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_upper_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_upper_modifier_finalize(GScanUpperModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_upper_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur livrant des octets en majuscules. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_upper_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_UPPER_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_upper_modifier_get_name(const GScanUpperModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("upper"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_upper_modifier_transform(const GScanUpperModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + size_t k; /* Boucle de parcours #2 */ + + result = true; + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++, binary++) + { + _src = src + i; + + binary->len = _src->len; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + switch (_src->data[k]) + { + case 'a' ... 'z': + binary->data[k] = _src->data[k] - 0x20; + break; + + default: + binary->data[k] = _src->data[k]; + break; + + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_upper_modifier_get_path(const GScanUpperModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + + if (*index > 0) + { + result = NULL; + (*index)--; + } + + else + result = strdup("upper"); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/upper.h b/src/analysis/scan/patterns/modifiers/upper.h new file mode 100644 index 0000000..4666312 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/upper.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * upper.h - prototypes pour la transformation d'une séquence d'octets par passage en majuscules + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_UPPER_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_UPPER_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_UPPER_MODIFIER g_scan_upper_modifier_get_type() +#define G_SCAN_UPPER_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_UPPER_MODIFIER, GScanUpperModifier)) +#define G_IS_SCAN_UPPER_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_UPPER_MODIFIER)) +#define G_SCAN_UPPER_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_UPPER_MODIFIER, GScanUpperModifierClass)) +#define G_IS_SCAN_UPPER_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_UPPER_MODIFIER)) +#define G_SCAN_UPPER_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_UPPER_MODIFIER, GScanUpperModifierClass)) + + +/* Transformation d'une séquence d'octets par passage en majuscules (instance) */ +typedef GScanTokenModifier GScanUpperModifier; + +/* Transformation d'une séquence d'octets par passage en majuscules (classe) */ +typedef GScanTokenModifierClass GScanUpperModifierClass; + + +/* Indique le type défini pour une transformation par bascule en majuscules. */ +GType g_scan_upper_modifier_get_type(void); + +/* Construit un modificateur livrant des octets en majuscules. */ +GScanTokenModifier *g_scan_upper_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_UPPER_H */ diff --git a/src/analysis/scan/patterns/modifiers/wide.c b/src/analysis/scan/patterns/modifiers/wide.c new file mode 100644 index 0000000..ef252d9 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/wide.c @@ -0,0 +1,291 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * wide.c - transcription d'une séquence d'octets en UTF-16 + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "wide.h" + + +#include <malloc.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transcriptions en UTF-16. */ +static void g_scan_wide_modifier_class_init(GScanWideModifierClass *klass); + +/* Initialise une instance de transcription en UTF-16. */ +static void g_scan_wide_modifier_init(GScanWideModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_wide_modifier_dispose(GScanWideModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_wide_modifier_finalize(GScanWideModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_wide_modifier_get_name(const GScanWideModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_wide_modifier_transform(const GScanWideModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_wide_modifier_get_path(const GScanWideModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transcription d'une séquence d'octets en UTF-16. */ +G_DEFINE_TYPE(GScanWideModifier, g_scan_wide_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transcriptions en UTF-16. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_wide_modifier_class_init(GScanWideModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_wide_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_wide_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_wide_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_wide_modifier_transform; + modifier->get_path = (get_modifier_path)g_scan_wide_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transcription en UTF-16. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_wide_modifier_init(GScanWideModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_wide_modifier_dispose(GScanWideModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_wide_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_wide_modifier_finalize(GScanWideModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_wide_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur livrant des octets en UTF-16. * +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_wide_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_WIDE_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_wide_modifier_get_name(const GScanWideModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("wide"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_wide_modifier_transform(const GScanWideModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + size_t k; /* Boucle de parcours #2 */ + + result = true; + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++, binary++) + { + _src = src + i; + + binary->len = _src->len * 2; + binary->data = calloc(binary->len * 2, sizeof(bin_t)); + + for (k = 0; k < _src->len; k++) + binary->data[k * 2] = _src->data[k]; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_wide_modifier_get_path(const GScanWideModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + + if (*index > 0) + { + result = NULL; + (*index)--; + } + + else + result = strdup("wide"); + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/wide.h b/src/analysis/scan/patterns/modifiers/wide.h new file mode 100644 index 0000000..deb92a4 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/wide.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * wide.h - prototypes pour la transcription d'une séquence d'octets en UTF-16 + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_WIDE_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_WIDE_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_WIDE_MODIFIER g_scan_wide_modifier_get_type() +#define G_SCAN_WIDE_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_WIDE_MODIFIER, GScanWideModifier)) +#define G_IS_SCAN_WIDE_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_WIDE_MODIFIER)) +#define G_SCAN_WIDE_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_WIDE_MODIFIER, GScanWideModifierClass)) +#define G_IS_SCAN_WIDE_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_WIDE_MODIFIER)) +#define G_SCAN_WIDE_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_WIDE_MODIFIER, GScanWideModifierClass)) + + +/* Transcription d'une séquence d'octets en UTF-16 (instance) */ +typedef GScanTokenModifier GScanWideModifier; + +/* Transcription d'une séquence d'octets en UTF-16 (classe) */ +typedef GScanTokenModifierClass GScanWideModifierClass; + + +/* Indique le type défini pour une transcription d'une séquence d'octets en UTF-16. */ +GType g_scan_wide_modifier_get_type(void); + +/* Construit un modificateur livrant des octets en UTF-16. */ +GScanTokenModifier *g_scan_wide_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_WIDE_H */ diff --git a/src/analysis/scan/patterns/modifiers/xor.c b/src/analysis/scan/patterns/modifiers/xor.c new file mode 100644 index 0000000..d932c82 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/xor.c @@ -0,0 +1,438 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * xor.c - transormation via opération XOR + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "xor.h" + + +#include <assert.h> +#include <malloc.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> + + +#include "../modifier-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des transmissions via opération XOR. */ +static void g_scan_xor_modifier_class_init(GScanXorModifierClass *klass); + +/* Initialise une instance de transmission via opération XOR. */ +static void g_scan_xor_modifier_init(GScanXorModifier *); + +/* Supprime toutes les références externes. */ +static void g_scan_xor_modifier_dispose(GScanXorModifier *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_xor_modifier_finalize(GScanXorModifier *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Fournit le nom d'appel d'un modificateur pour motif. */ +static char *g_scan_xor_modifier_get_name(const GScanXorModifier *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_xor_modifier_transform(const GScanXorModifier *, const sized_binary_t *, size_t, sized_binary_t **, size_t *); + +/* Détermine si un argument est bien toléré par un modificateur. */ +static bool g_scan_xor_modifier_can_handle_arg(const GScanXorModifier *, const modifier_arg_t *); + +/* Transforme une séquence d'octets pour motif de recherche. */ +static bool g_scan_xor_modifier_transform_with_arg(const GScanXorModifier *, const sized_binary_t *, size_t, const modifier_arg_t *, sized_binary_t **, size_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +static char *g_scan_xor_modifier_get_path(const GScanXorModifier *, size_t *); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une transormation via une opération XOR. */ +G_DEFINE_TYPE(GScanXorModifier, g_scan_xor_modifier, G_TYPE_SCAN_TOKEN_MODIFIER); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des transmissions via opération XOR. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_xor_modifier_class_init(GScanXorModifierClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenModifierClass *modifier; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_xor_modifier_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_xor_modifier_finalize; + + modifier = G_SCAN_TOKEN_MODIFIER_CLASS(klass); + + modifier->get_name = (get_scan_modifier_name_fc)g_scan_xor_modifier_get_name; + + modifier->transform = (transform_scan_token_fc)g_scan_xor_modifier_transform; + modifier->can_handle = (can_token_modifier_handle_arg)g_scan_xor_modifier_can_handle_arg; + modifier->transform_with = (transform_scan_token_with_fc)g_scan_xor_modifier_transform_with_arg; + modifier->get_path = (get_modifier_path)g_scan_xor_modifier_get_path; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance à initialiser. * +* * +* Description : Initialise une instance de transmission via opération XOR. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_xor_modifier_init(GScanXorModifier *modifier) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_xor_modifier_dispose(GScanXorModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_xor_modifier_parent_class)->dispose(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_xor_modifier_finalize(GScanXorModifier *modifier) +{ + G_OBJECT_CLASS(g_scan_xor_modifier_parent_class)->finalize(G_OBJECT(modifier)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit un modificateur livrant des octets traités par XOR.* +* * +* Retour : Mécanisme mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenModifier *g_scan_xor_modifier_new(void) +{ + GScanTokenModifier *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_XOR_MODIFIER, NULL); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* * +* Description : Fournit le nom d'appel d'un modificateur pour motif. * +* * +* Retour : Désignation humaine. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_xor_modifier_get_name(const GScanXorModifier *modifier) +{ + char *result; /* Désignation à retourner */ + + result = strdup("xor"); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_xor_modifier_transform(const GScanXorModifier *modifier, const sized_binary_t *src, size_t scount, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + long long x; /* Boucle de parcours #2 */ + size_t k; /* Boucle de parcours #3 */ + + result = true; + + *dcount = scount * 256; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++) + { + _src = src + i; + + for (x = 0; x <= 0xff; x++, binary++) + { + binary->len = _src->len; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + binary->data[k] = _src->data[k] ^ x; + + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* arg = argument de personnalisation. * +* * +* Description : Détermine si un argument est bien toléré par un modificateur.* +* * +* Retour : Bilan de la consultation : support ou non. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_xor_modifier_can_handle_arg(const GScanXorModifier *modifier, const modifier_arg_t *arg) +{ + bool result; /* Bilan d'opération à renvoyer*/ + + switch (arg->type) + { + case MAT_UNSIGNED_INTEGER: + result = (arg->value.u_integer <= UINT8_MAX); + break; + + case MAT_RANGE: + result = (INT8_MIN <= arg->value.range.start && arg->value.range.end <= INT8_MAX); + break; + + default: + result = false; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à solliciter. * +* src = séquences d'octets à traiter. * +* scount = quantité de ces séquences. * +* arg = argument de personnalisation. * +* dest = nouvelle(s) séquence(s) d'octets obtenue(s) [OUT] * +* dcount = quantité de ces séquences. * +* * +* Description : Transforme une séquence d'octets pour motif de recherche. * +* * +* Retour : Bilan de l'opération : succès ou échec. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_xor_modifier_transform_with_arg(const GScanXorModifier *modifier, const sized_binary_t *src, size_t scount, const modifier_arg_t *arg, sized_binary_t **dest, size_t *dcount) +{ + bool result; /* Bilan d'opération à renvoyer*/ + sized_binary_t *binary; /* Raccourci vers le stockage */ + size_t i; /* Boucle de parcours #1 */ + const sized_binary_t *_src; /* Source courante */ + long long x; /* Boucle de parcours #2 */ + size_t k; /* Boucle de parcours #3 */ + + result = true; + + switch (arg->type) + { + case MAT_UNSIGNED_INTEGER: + + *dcount = scount; + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++) + { + _src = src + i; + + binary->len = _src->len; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + binary->data[k] = _src->data[k] ^ arg->value.u_integer; + + } + + break; + + case MAT_RANGE: + + *dcount = scount * (arg->value.range.end - arg->value.range.start + 1); + *dest = malloc(*dcount * sizeof(sized_binary_t)); + + binary = &(*dest)[0]; + + for (i = 0; i < scount; i++) + { + _src = src + i; + + for (x = arg->value.range.start; x <= arg->value.range.end; x++, binary++) + { + binary->len = _src->len; + binary->data = malloc(binary->len); + + for (k = 0; k < _src->len; k++) + binary->data[k] = _src->data[k] ^ x; + + } + + } + + break; + + default: + assert(false); + result = false; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : modifier = modificateur à consulter. * +* index = indice de la combinaison ciblée. [OUT] * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_xor_modifier_get_path(const GScanXorModifier *modifier, size_t *index) +{ + char *result; /* Combinaison à retourner */ + int ret; /* Bilan intermédiaire */ + + if (*index > 255) + { + result = NULL; + (*index) -= 256; + } + + else + { + ret = asprintf(&result, "xor(0x%02hhx)", (unsigned char)*index); + + if (ret == -1) + result = strdup("xor(0x?)"); + + } + + return result; + +} diff --git a/src/analysis/scan/patterns/modifiers/xor.h b/src/analysis/scan/patterns/modifiers/xor.h new file mode 100644 index 0000000..1a3e7e6 --- /dev/null +++ b/src/analysis/scan/patterns/modifiers/xor.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * xor.h - prototypes pour la transormation via opération XOR + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_MODIFIERS_XOR_H +#define _ANALYSIS_SCAN_PATTERNS_MODIFIERS_XOR_H + + +#include <glib-object.h> + + +#include "../modifier.h" + + + +#define G_TYPE_SCAN_XOR_MODIFIER g_scan_xor_modifier_get_type() +#define G_SCAN_XOR_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_XOR_MODIFIER, GScanXorModifier)) +#define G_IS_SCAN_XOR_MODIFIER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_XOR_MODIFIER)) +#define G_SCAN_XOR_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_XOR_MODIFIER, GScanXorModifierClass)) +#define G_IS_SCAN_XOR_MODIFIER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_XOR_MODIFIER)) +#define G_SCAN_XOR_MODIFIER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_XOR_MODIFIER, GScanXorModifierClass)) + + +/* Transormation via inversement d'une séquence d'octets (instance) */ +typedef GScanTokenModifier GScanXorModifier; + +/* Transormation via inversement d'une séquence d'octets (classe) */ +typedef GScanTokenModifierClass GScanXorModifierClass; + + +/* Indique le type défini pour une transormation via une opération XOR. */ +GType g_scan_xor_modifier_get_type(void); + +/* Construit un modificateur livrant des octets traités par XOR. */ +GScanTokenModifier *g_scan_xor_modifier_new(void); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_MODIFIERS_XOR_H */ diff --git a/src/analysis/scan/patterns/patid.h b/src/analysis/scan/patterns/patid.h new file mode 100644 index 0000000..e8b7eee --- /dev/null +++ b/src/analysis/scan/patterns/patid.h @@ -0,0 +1,36 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * patid.h - prototypes pour la définition d'un identifiant de motif partiel + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_PATID_H +#define _ANALYSIS_SCAN_PATTERNS_PATID_H + + + +/* Identifiant de motif intégré */ +typedef uint32_t patid_t; + +#define INVALID_PATTERN_ID 0xffffffff + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_PATID_H */ diff --git a/src/analysis/scan/patterns/token-int.h b/src/analysis/scan/patterns/token-int.h new file mode 100644 index 0000000..7ba0aa4 --- /dev/null +++ b/src/analysis/scan/patterns/token-int.h @@ -0,0 +1,62 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * token-int.h - prototypes internes pour les bribes de recherche textuelle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKEN_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKEN_INT_H + + +#include "token.h" + + +#include "../pattern-int.h" + + + +/* Encadrement d'une bribe de recherche textuelle (instance) */ +struct _GBytesToken +{ + GSearchPattern parent; /* A laisser en premier */ + + GScanTokenNode *root; /* Motif à rechercher */ + size_t slow; /* Surcoût du motif */ + bool need_backward; /* Besoin d'une seconde passe */ + + bool fullword; /* Cible de mots entiers ? */ + bool private; /* Vocation privée ? */ + +}; + +/* Encadrement d'une bribe de recherche textuelle (classe) */ +struct _GBytesTokenClass +{ + GSearchPatternClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un gestionnaire de recherche de binaire. */ +bool g_bytes_token_create(GBytesToken *, GScanTokenNode *, bool, bool); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKEN_INT_H */ diff --git a/src/analysis/scan/patterns/token.c b/src/analysis/scan/patterns/token.c new file mode 100644 index 0000000..b3c6d53 --- /dev/null +++ b/src/analysis/scan/patterns/token.c @@ -0,0 +1,491 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * token.c - bribes de recherche textuelle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "token.h" + + +#include <assert.h> +#include <ctype.h> +#include <stdio.h> + + +#include "token-int.h" +#include "tokens/nodes/plain.h" +#include "../../../common/cpp.h" +#include "../../../core/logs.h" + + + +/* ------------------------- CIBLAGE DES SEQUENCES D'OCTETS ------------------------- */ + + +/* Initialise la classe des bribes de recherche textuelle. */ +static void g_bytes_token_class_init(GBytesTokenClass *); + +/* Initialise une instance de bribe de recherche textuelle. */ +static void g_bytes_token_init(GBytesToken *); + +/* Supprime toutes les références externes. */ +static void g_bytes_token_dispose(GBytesToken *); + +/* Procède à la libération totale de la mémoire. */ +static void g_bytes_token_finalize(GBytesToken *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Affiche un motif de recherche au format texte. */ +static void g_bytes_token_output_to_text(const GBytesToken *, GScanContext *, int); + +/* Affiche un motif de recherche au format JSON. */ +static void g_bytes_token_output_to_json(const GBytesToken *, GScanContext *, const sized_string_t *, unsigned int, int); + + + +/* ---------------------------------------------------------------------------------- */ +/* CIBLAGE DES SEQUENCES D'OCTETS */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une bribe de recherche textuelle. */ +G_DEFINE_TYPE(GBytesToken, g_bytes_token, G_TYPE_SEARCH_PATTERN); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des bribes de recherche textuelle. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bytes_token_class_init(GBytesTokenClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GSearchPatternClass *pattern; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_bytes_token_dispose; + object->finalize = (GObjectFinalizeFunc)g_bytes_token_finalize; + + pattern = G_SEARCH_PATTERN_CLASS(klass); + + pattern->to_text = (output_pattern_to_text_fc)g_bytes_token_output_to_text; + pattern->to_json = (output_pattern_to_json_fc)g_bytes_token_output_to_json; + +} + + +/****************************************************************************** +* * +* Paramètres : token = instance à initialiser. * +* * +* Description : Initialise une instance de bribe de recherche textuelle. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bytes_token_init(GBytesToken *token) +{ + token->root = NULL; + token->slow = 0; + token->need_backward = false; + + token->fullword = false; + token->private = false; + +} + + +/****************************************************************************** +* * +* Paramètres : token = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bytes_token_dispose(GBytesToken *token) +{ + g_clear_object(&token->root); + + G_OBJECT_CLASS(g_bytes_token_parent_class)->dispose(G_OBJECT(token)); + +} + + +/****************************************************************************** +* * +* Paramètres : token = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bytes_token_finalize(GBytesToken *token) +{ + G_OBJECT_CLASS(g_bytes_token_parent_class)->finalize(G_OBJECT(token)); + +} + + +/****************************************************************************** +* * +* Paramètres : token = encadrement de motif à initialiser pleinement. * +* root = représentation du motif à recherche. * +* fullword = limite les correspondances à des mots entiers. * +* private = donne une vocation privée au motif de recherche. * +* * +* Description : Met en place un gestionnaire de recherche de binaire. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_bytes_token_create(GBytesToken *token, GScanTokenNode *root, bool fullword, bool private) +{ + bool result; /* Bilan à retourner */ + + result = true; + + token->root = root; + g_object_ref(G_OBJECT(root)); + + token->fullword = fullword; + token->private = private; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : token = encadrement de motif à consulter. * +* * +* Description : Indique si seuls des mots entiers sont retenus des analyses. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_bytes_token_target_fullword(const GBytesToken *token) +{ + bool result; /* Statut à renvoyer */ + + result = token->fullword; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : token = encadrement de motif à consulter. * +* * +* Description : Détermine si le gestionnaire est à vocation privée. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_bytes_token_is_private(const GBytesToken *token) +{ + bool result; /* Statut à renvoyer */ + + result = token->private; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : token = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_bytes_token_enroll(GBytesToken *token, GEngineBackend *backend, size_t maxsize) +{ + bool result; /* Statut à retourner */ + + token->need_backward = g_scan_token_node_setup_tree(token->root); + + result = g_scan_token_node_enroll(token->root, backend, maxsize, &token->slow); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : token = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère les identifiants finaux pour un motif recherché. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_bytes_token_build_id(GBytesToken *token, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + + result = g_scan_token_node_build_id(token->root, backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : token = définition de la bribe à manipuler. * +* matches = suivi des correspondances à consolider. * +* params = paramètres des opérations de validation. * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_bytes_token_check(const GBytesToken *token, GScanBytesMatches *matches, scan_node_check_params_t *params) +{ + match_area_t *area; /* Correspondance à valider */ + match_area_t *next; /* Correspondance suivante */ + vmpa2t pos; /* Tête de lecture */ + const bin_t *byte; /* Octet à valider */ + + /* Réinitialisation */ + + // TODO: offset + + params->initialized = false; + + params->main_areas = NULL; + params->main_count = 0; + + params->created_areas = NULL; + params->created_count = 0; + + params->kept_areas = NULL; + params->kept_count = 0; + + /* Lancement des analyses */ + + g_scan_token_node_check_forward(token->root, params); + + if (token->need_backward) + g_scan_token_node_check_backward(token->root, params); + + // REMME ? sort_and_filter_pending_matches(matches); + + if (token->fullword) + { + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + /* Validation de l'octet précédent, s'il existe */ + if (area->start > params->content_start) + { + init_vmpa(&pos, area->start - 1, VMPA_NO_VIRTUAL); + + byte = g_binary_content_get_raw_access(params->content, &pos, 1); + + if (isalnum(*byte)) + { + del_match_area(area, ¶ms->main_areas); + assert(¶ms->main_count > 0); + params->main_count--; + continue; + } + + } + + /* Validation de l'octet suivant, s'il existe */ + if (area->end < params->content_end) + { + init_vmpa(&pos, area->end, VMPA_NO_VIRTUAL); + + byte = g_binary_content_get_raw_access(params->content, &pos, 1); + + if (isalnum(*byte)) + { + del_match_area(area, ¶ms->main_areas); + assert(¶ms->main_count > 0); + params->main_count--; + continue; + } + + } + + } + + } + + g_scan_bytes_matches_set_list(matches, params->main_areas, params->main_count); + +} + + +/****************************************************************************** +* * +* Paramètres : token = définition de la bribe à consulter. * +* index = indice de la combinaison de modificateurs ciblée. * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison gagnante. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_bytes_token_get_modifier_path(const GBytesToken *token, size_t index) +{ + char *result; /* Combinaison à retourner */ + + if (G_IS_SCAN_TOKEN_NODE_PLAIN(token->root)) + result = g_scan_token_node_plain_get_modifier_path(G_SCAN_TOKEN_NODE_PLAIN(token->root), index); + else + result = NULL; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bytes_token_output_to_text(const GBytesToken *pattern, GScanContext *context, int fd) +{ + GScanMatches *matches; /* Correspondances établies */ + + if (g_bytes_token_is_private(pattern)) + return; + + matches = g_scan_context_get_full_matches(context, G_SEARCH_PATTERN(pattern)); + + if (matches != NULL) + { + g_scan_matches_output_to_text(matches, fd); + + g_object_unref(G_OBJECT(matches)); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_bytes_token_output_to_json(const GBytesToken *pattern, GScanContext *context, const sized_string_t *padding, unsigned int level, int fd) +{ + GScanMatches *matches; /* Correspondances établies */ + + if (g_bytes_token_is_private(pattern)) + return; + + matches = g_scan_context_get_full_matches(context, G_SEARCH_PATTERN(pattern)); + + if (matches != NULL) + { + g_scan_matches_output_to_json(matches, padding, level, fd); + + g_object_unref(G_OBJECT(matches)); + + } + +} diff --git a/src/analysis/scan/patterns/token.h b/src/analysis/scan/patterns/token.h new file mode 100644 index 0000000..f5b78f6 --- /dev/null +++ b/src/analysis/scan/patterns/token.h @@ -0,0 +1,75 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * token.h - prototypes pour les bribes de recherche textuelle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKEN_H +#define _ANALYSIS_SCAN_PATTERNS_TOKEN_H + + +#include <glib-object.h> + + +#include "backend.h" +#include "tokens/node.h" +#include "../matches/bytes.h" + + + +#define G_TYPE_BYTES_TOKEN g_bytes_token_get_type() +#define G_BYTES_TOKEN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_BYTES_TOKEN, GBytesToken)) +#define G_IS_BYTES_TOKEN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_BYTES_TOKEN)) +#define G_BYTES_TOKEN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_BYTES_TOKEN, GBytesTokenClass)) +#define G_IS_BYTES_TOKEN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_BYTES_TOKEN)) +#define G_BYTES_TOKEN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_BYTES_TOKEN, GBytesTokenClass)) + + +/* Encadrement d'une bribe de recherche textuelle (instance) */ +typedef struct _GBytesToken GBytesToken; + +/* Encadrement d'une bribe de recherche textuelle (classe) */ +typedef struct _GBytesTokenClass GBytesTokenClass; + + +/* Indique le type défini pour une bribe de recherche textuelle. */ +GType g_bytes_token_get_type(void); + +/* Indique si seuls des mots entiers sont retenus des analyses. */ +bool g_bytes_token_target_fullword(const GBytesToken *); + +/* Détermine si le gestionnaire est à vocation privée. */ +bool g_bytes_token_is_private(const GBytesToken *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +bool g_bytes_token_enroll(GBytesToken *, GEngineBackend *, size_t); + +/* Récupère les identifiants finaux pour un motif recherché. */ +bool g_bytes_token_build_id(GBytesToken *, GEngineBackend *); + +/* Transforme les correspondances locales en trouvailles. */ +void g_bytes_token_check(const GBytesToken *, GScanBytesMatches *, scan_node_check_params_t *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +char *g_bytes_token_get_modifier_path(const GBytesToken *, size_t); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKEN_H */ diff --git a/src/analysis/scan/patterns/tokens/Makefile.am b/src/analysis/scan/patterns/tokens/Makefile.am new file mode 100644 index 0000000..f0ab3d5 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/Makefile.am @@ -0,0 +1,26 @@ + +noinst_LTLIBRARIES = libanalysisscanpatternstokens.la + + +libanalysisscanpatternstokens_la_SOURCES = \ + atom.h atom.c \ + hex-int.h \ + hex.h hex.c \ + node-int.h \ + node.h node.c \ + offset.h offset.c \ + plain-int.h \ + plain.h plain.c + +libanalysisscanpatternstokens_la_LIBADD = \ + nodes/libanalysisscanpatternstokensnodes.la + +libanalysisscanpatternstokens_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanpatternstokens_la_SOURCES:%c=) + + +SUBDIRS = nodes diff --git a/src/analysis/scan/patterns/tokens/atom.c b/src/analysis/scan/patterns/tokens/atom.c new file mode 100644 index 0000000..4f2ad67 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/atom.c @@ -0,0 +1,543 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * atom.c - détermination d'atomes à partir de motifs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "atom.h" + + +#include <assert.h> +#include <malloc.h> +#include <math.h> + + + +/** + * Remplacement des fonctions de <ctypes.h> dans support des locales. + */ + +#define IS_CH_LETTER(ch) (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) + +#define MAKE_CH_UPPER(ch) (ch & 0xdf) +#define MAKE_CH_LOWER(ch) (ch | 0x20) + + + +/****************************************************************************** +* * +* Paramètres : ch = octet dont la valeur est à analyser. * +* seen = suivi des octets déjà rencontrés. [OUT] * +* uniq = volume d'octets originaux à actualiser. [OUT] * +* letters = nombre de lettres rencontrées. [OUT] * +* * +* Description : Note l'intêret de rechercher un octet particulier. * +* * +* Retour : Note positive ou négative. * +* * +* Remarques : - * +* * +******************************************************************************/ + +int rate_byte_quality(bin_t ch, uint8_t *seen, size_t *uniq, size_t *letters) +{ + int result; /* Note à retourner */ + + switch (ch) + { + case 0x00: + case 0x20: + case 0x90: + case 0xcc: + case 0xff: + result = 12; + break; + + case 'A' ... 'Z': + case 'a' ... 'z': + if (letters == NULL) + result = 20; + else + { + result = 18; + (*letters)++; + } + break; + + default: + result = 20; + break; + + } + + if (seen[ch]++ == 0) + (*uniq)++; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : ch = octet dont la valeur est à analyser. * +* seen = suivi des octets déjà rencontrés. [OUT] * +* uniq = volume d'octets originaux à actualiser. [OUT] * +* letters = nombre de lettres rencontrées. [OUT] * +* * +* Description : Annihile l'intêret de rechercher un octet particulier. * +* * +* Retour : Note positive ou négative. * +* * +* Remarques : - * +* * +******************************************************************************/ + +int unrate_byte_quality(bin_t ch, uint8_t *seen, size_t *uniq, size_t *letters) +{ + int result; /* Note à retourner */ + + switch (ch) + { + case 0x00: + case 0x20: + case 0x90: + case 0xcc: + case 0xff: + result = 12; + break; + + case 'A' ... 'Z': + case 'a' ... 'z': + if (letters == NULL) + result = 20; + else + { + result = 18; + assert(*letters > 0); + (*letters)--; + } + break; + + default: + result = 20; + break; + + } + + if (--seen[ch] == 0) + { + assert(*uniq > 0); + (*uniq)--; + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rating = note d'évaluation courante. * +* uniq = volume d'octets originaux relevés. * +* max = nombre d'octets considérés à la base. * +* * +* Description : Termine la notation d'un ensemble d'octets. * +* * +* Retour : Note positive ou négative. * +* * +* Remarques : - * +* * +******************************************************************************/ + +int finish_quality_rating(int rating, size_t uniq, size_t max) +{ + int result; /* Note à retourner */ + bool bad; /* Indice de mauvaise qualité */ + + if (uniq == 1) + { + bad = (rating % 12) == 0; + + result = (bad ? -10 * max : 2); + + } + + else + result = uniq * 2; + + result += rating; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : raw = définition de la bribe à enregistrer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* atom = informations de suivi constituées. [OUT] * +* letters = nombre de lettres rencontrées. [OUT] * +* * +* Description : Détermine la portion idéale de recherche. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void find_best_atom(const sized_binary_t *raw, size_t maxsize, tracked_scan_atom_t *atom, size_t *letters) +{ + size_t i; /* Boucle de parcours #1 */ + bin_t ch; /* Octets à étudier */ + size_t best_letters; /* Mémorisation de décompte */ + size_t *ptr_letters; /* Pointeur vers le décompte */ + int raw_rating; /* Notation brute de séquence */ + uint8_t seen[256]; /* Mémorisation des passages */ + size_t uniq; /* Nombre d'octets originaux */ + const bin_t *last; /* Dernier caractère étudié */ + int best_rating; /* Meilleur notation obtenue */ + size_t max_loop; /* Limitation des itérations */ + size_t k; /* Boucle de parcours #2 */ + size_t local_letters; /* Décompte courant des lettres*/ + int local_rating; /* Notation courante */ + const bin_t *first; /* Premier caractère étudié */ + + /* Si la chaîne fournie est plus petite que la taille d'un atome... */ + if (raw->len <= maxsize) + { + atom->pos = 0; + atom->len = raw->len; + atom->rem = 0; + + atom->fast_check = true; + + if (letters != NULL) + { + *letters = 0; + + for (i = 0; i < raw->len; i++) + { + ch = raw->data[i]; + + if (IS_CH_LETTER(ch)) + (*letters)++; + + } + + } + + } + + /* ... ou si une sélection doit s'opérer */ + else + { + /* Etablissement d'une mesure de référence à la position 0 */ + + atom->pos = 0; + atom->len = maxsize; + + ptr_letters = (letters != NULL ? &best_letters : NULL); + + best_letters = 0; + raw_rating = 0; + + memset(seen, 0, sizeof(seen)); + uniq = 0; + + last = raw->static_bin_data; + + for (k = 0; k < maxsize; k++) + raw_rating += rate_byte_quality(*last++, seen, &uniq, ptr_letters); + + best_rating = finish_quality_rating(raw_rating, uniq, maxsize); + + /* Parcours du reste du contenu */ + + max_loop = (raw->len - maxsize); + + ptr_letters = (letters != NULL ? &local_letters : NULL); + + local_letters = best_letters; + local_rating = best_rating; + + first = raw->static_bin_data; + + for (i = 0; i < max_loop; i++) + { + raw_rating += rate_byte_quality(*last++, seen, &uniq, ptr_letters); + raw_rating -= unrate_byte_quality(*first++, seen, &uniq, ptr_letters); + + local_rating = finish_quality_rating(raw_rating , uniq, maxsize); + + if (local_rating > best_rating) + { + atom->pos = i + 1; + + best_letters = local_letters; + best_rating = local_rating; + + } + + } + + /* Conclusion */ + + atom->rem = raw->len - atom->pos - maxsize; + + atom->fast_check = false; + + if (letters != NULL) + *letters = best_letters; + + } + + assert((atom->fast_check && atom->pos == 0 && atom->rem == 0) + || (!atom->fast_check && (atom->pos != 0 || atom->rem != 0))); + +} + + +/****************************************************************************** +* * +* Paramètres : src = chaîne ed référence à dupliquer. * +* atom = préselection opérée en amont. * +* count = nombre de lettres présentes. * +* * +* Description : Etablit la liste des cas de figures ignorant la casse. * +* * +* Retour : Liste de toutes les combinaisons possibles. * +* * +* Remarques : - * +* * +******************************************************************************/ + +sized_binary_t *make_atoms_case_insensitive(const sized_binary_t *src, const tracked_scan_atom_t *atom, size_t count) +{ + sized_binary_t *result; /* Liste à retourner */ + size_t i; /* Boucle de parcours #1 */ + size_t replaced; /* 2^(alternatives créées) */ +#ifndef NDEBUG + size_t check; /* Validation du compte max. */ +#endif + bin_t ch; /* Octet à recopier */ + size_t k; /* Boucle de parcours #2 */ + size_t divisor; /* Taille de la découpe */ + size_t quotient; /* Reste de la position */ + + /* Création du réceptacle */ + + result = malloc(count * sizeof(tracked_scan_atom_t)); + + assert(src->len == (atom->pos + atom->len + atom->rem)); + + for (i = 0; i < count; i++) + { + result[i].data = malloc(src->len); + result[i].len = src->len; + + memcpy(result[i].data, src->data, atom->pos); + memcpy(&result[i].data[atom->pos + atom->len], &src->data[atom->pos + atom->len], atom->rem); + + } + + /* Remplissage */ + + replaced = 2; + +#ifndef NDEBUG + check = 1; +#endif + + for (i = atom->pos; i < (atom->pos + atom->len); i++) + { + ch = src->data[i]; + + if (IS_CH_LETTER(ch)) + { + for (k = 0; k < count; k++) + { + divisor = count / replaced; + quotient = k / divisor; + + if ((quotient % 2) == 0) + result[k].data[i] = MAKE_CH_UPPER(ch); + else + result[k].data[i] = MAKE_CH_LOWER(ch); + + } + + replaced *= 2; + +#ifndef NDEBUG + check *= 2; + assert(check <= count); +#endif + + } + else + for (k = 0; k < count; k++) + result[k].data[i] = ch; + + } + + assert(check == count); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = octets partiels avec leur masque à interpréter. * +* len = quantité d'octets à interpréter. * +* produced = nombre de contenus générés. [OUT] * +* * +* Description : Etablit la liste des cas de figures avec des octets partiels.* +* * +* Retour : Liste de toutes les combinaisons possibles. * +* * +* Remarques : - * +* * +******************************************************************************/ + +sized_binary_t *make_atoms_from_masked_bytes(const masked_byte_t *bytes, size_t len, size_t *produced) +{ + sized_binary_t *result; /* Liste à retourner */ + size_t seq_len; /* Taille de séquence retenue */ + size_t repeat_times; /* Répétitions pour remplissage*/ + sized_binary_t *maxiter; /* Borne de fin de parcours */ + size_t i; /* Boucle de parcours #1 */ + sized_binary_t *iter; /* Boucle de parcours #2 */ + size_t j; /* Boucle de parcours #3 */ + size_t k; /* Boucle de parcours #4 */ + + seq_len = (len > MASK_MAX_LEN_FOR_ATOMS ? MASK_MAX_LEN_FOR_ATOMS : len); + + /** + * Si l'usage de la fonction pow() disparaît, la bibliothèque m + * peut être retirée de libchrysacore_la_LDFLAGS dans le Makefile + * principal. + */ + repeat_times = pow(16, seq_len - 1); + + *produced = 16 * repeat_times; + + /* Création du réceptacle */ + + result = malloc(*produced * sizeof(tracked_scan_atom_t)); + + maxiter = result + *produced; + + /* Remplissage */ + + for (i = 0; i < seq_len; i++) + { + for (iter = result; iter < maxiter; ) + { + for (j = 0; j < 16; j++) + { + assert(bytes[i].mask == 0x0f || bytes[i].mask == 0xf0); + + for (k = 0; k < repeat_times; k++) + { + if (i == 0) + { + iter->data = malloc(seq_len); + iter->len = seq_len; + } + + if (bytes[i].mask == 0x0f) + iter->data[i] = bytes[i].value | (j << 4); + else + iter->data[i] = bytes[i].value | j; + + iter++; + + } + + } + + } + + repeat_times /= 16; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : raw = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* atom = informations de suivi constituées. [OUT] * +* * +* Description : Amorce l'insertion de l'atome déterminé d'une série d'octets.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool enroll_prepared_atom(const sized_binary_t *raw, GEngineBackend *backend, tracked_scan_atom_t *atom) +{ + bool result; /* Statut à retourner */ + const bin_t *data; /* Données à rechercher */ + + data = raw->static_bin_data + atom->pos; + + result = g_engine_backend_enroll_plain_pattern(backend, data, atom->len, atom->tmp_id); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : atom = informations de suivi constituées. [OUT] * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool build_atom_pattern_id(tracked_scan_atom_t *atom, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + + atom->pid = g_engine_backend_build_plain_pattern_id(backend, atom->tmp_id); + + result = (atom->pid != INVALID_PATTERN_ID); + + return result; + +} diff --git a/src/analysis/scan/patterns/tokens/atom.h b/src/analysis/scan/patterns/tokens/atom.h new file mode 100644 index 0000000..1ef8f40 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/atom.h @@ -0,0 +1,88 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * atom.h - prototypes pour la détermination d'atomes à partir de motifs + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_ATOM_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_ATOM_H + + +#include <stdbool.h> + + +#include "../backend.h" +#include "../../../../arch/vmpa.h" +#include "../../../../common/szstr.h" + + + +/* Suivi des motifs réellement recherchés */ +typedef struct _tracked_scan_atom_t +{ + phys_t pos; /* Début de sélection atomique */ + phys_t len; /* Taille de ladite sélection */ + phys_t rem; /* Reste après l'atome */ + + bool fast_check; /* Besoin de vérifications ? */ + + uint32_t tmp_id[2]; /* Couple d'identifiants temp. */ + + patid_t pid; /* Identifiant de la bribe */ + +} tracked_scan_atom_t; + +/* Note l'intêret de rechercher un octet particulier. */ +int rate_byte_quality(bin_t, uint8_t *, size_t *, size_t *); + +/* Annihile l'intêret de rechercher un octet particulier. */ +int unrate_byte_quality(bin_t, uint8_t *, size_t *, size_t *); + +/* Termine la notation d'un ensemble d'octets. */ +int finish_quality_rating(int, size_t, size_t); + +/* Détermine la portion idéale de recherche. */ +void find_best_atom(const sized_binary_t *, size_t , tracked_scan_atom_t *, size_t *); + +/* Etablit la liste des cas de figures ignorant la casse. */ +sized_binary_t *make_atoms_case_insensitive(const sized_binary_t *, const tracked_scan_atom_t *, size_t); + +/* Mémorisation d'un octet visé avec son masque */ +typedef struct _masked_byte_t +{ + bin_t value; /* Valeur de l'octet visé */ + bin_t mask; /* Masque à appliquer */ + +} masked_byte_t; + +#define MASK_MAX_LEN_FOR_ATOMS 2 + +/* Etablit la liste des cas de figures avec des octets partiels. */ +sized_binary_t *make_atoms_from_masked_bytes(const masked_byte_t *, size_t, size_t *); + +/* Amorce l'insertion de l'atome déterminé d'une série d'octets. */ +bool enroll_prepared_atom(const sized_binary_t *, GEngineBackend *, tracked_scan_atom_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +bool build_atom_pattern_id(tracked_scan_atom_t *, GEngineBackend *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_ATOM_H */ diff --git a/src/analysis/scan/patterns/tokens/hex-int.h b/src/analysis/scan/patterns/tokens/hex-int.h new file mode 100644 index 0000000..dca9848 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/hex-int.h @@ -0,0 +1,56 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hex-int.h - prototypes internes pour la recherche de morceaux de binaire + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_HEX_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_HEX_INT_H + + +#include "hex.h" + + +#include "atom.h" +#include "../token-int.h" + + + +/* Encadrement d'une recherche de morceaux de binaire (instance) */ +struct _GScanHexBytes +{ + GBytesToken parent; /* A laisser en premier */ + +}; + +/* Encadrement d'une recherche de morceaux de binaire (classe) */ +struct _GScanHexBytesClass +{ + GBytesTokenClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un gestionnaire de recherche de binaire. */ +bool g_scan_hex_bytes_create(GScanHexBytes *, GScanTokenNode *, bool); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_HEX_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/hex.c b/src/analysis/scan/patterns/tokens/hex.c new file mode 100644 index 0000000..89d7ca4 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/hex.c @@ -0,0 +1,259 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hex.c - recherche de morceaux de binaire + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "hex.h" + + +#include <malloc.h> +#include <string.h> + + +#include "hex-int.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des recherches de texte brut. */ +static void g_scan_hex_bytes_class_init(GScanHexBytesClass *klass); + +/* Initialise une instance de recherche de texte brut. */ +static void g_scan_hex_bytes_init(GScanHexBytes *); + +/* Supprime toutes les références externes. */ +static void g_scan_hex_bytes_dispose(GScanHexBytes *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_hex_bytes_finalize(GScanHexBytes *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Affiche un motif de recherche au format texte. */ +static void g_scan_hex_bytes_output_to_text(const GScanHexBytes *, GScanContext *, int); + +/* Affiche un motif de recherche au format JSON. */ +static void g_scan_hex_bytes_output_to_json(const GScanHexBytes *, GScanContext *, const sized_string_t *, unsigned int, int); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une suite d'octets à retrouver dans un binaire. */ +G_DEFINE_TYPE(GScanHexBytes, g_scan_hex_bytes, G_TYPE_BYTES_TOKEN); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des recherches de texte brut. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_bytes_class_init(GScanHexBytesClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GSearchPatternClass *pattern; /* Version de classe ancêtre */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_hex_bytes_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_hex_bytes_finalize; + + pattern = G_SEARCH_PATTERN_CLASS(klass); + + pattern->to_text = (output_pattern_to_text_fc)g_scan_hex_bytes_output_to_text; + pattern->to_json = (output_pattern_to_json_fc)g_scan_hex_bytes_output_to_json; + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = instance à initialiser. * +* * +* Description : Initialise une instance de recherche de texte brut. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_bytes_init(GScanHexBytes *bytes) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_bytes_dispose(GScanHexBytes *bytes) +{ + G_OBJECT_CLASS(g_scan_hex_bytes_parent_class)->dispose(G_OBJECT(bytes)); + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_bytes_finalize(GScanHexBytes *bytes) +{ + G_OBJECT_CLASS(g_scan_hex_bytes_parent_class)->finalize(G_OBJECT(bytes)); + +} + + +/****************************************************************************** +* * +* Paramètres : root = représentation du motif à recherche. * +* private = donne une vocation privée au motif de recherche. * +* * +* Description : Construit un gestionnaire de recherche de texte brut. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GSearchPattern *g_scan_hex_bytes_new(GScanTokenNode *root, bool private) +{ + GSearchPattern *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_HEX_BYTES, NULL); + + if (!g_scan_hex_bytes_create(G_SCAN_HEX_BYTES(result), root, private)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = encadrement de motif à initialiser pleinement. * +* root = représentation du motif à recherche. * +* private = donne une vocation privée au motif de recherche. * +* * +* Description : Met en place un gestionnaire de recherche de binaire. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_hex_bytes_create(GScanHexBytes *bytes, GScanTokenNode *root, bool private) +{ + bool result; /* Bilan à retourner */ + + result = g_bytes_token_create(G_BYTES_TOKEN(bytes), root, false, private); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_bytes_output_to_text(const GScanHexBytes *pattern, GScanContext *context, int fd) +{ + G_SEARCH_PATTERN_CLASS(g_scan_hex_bytes_parent_class)->to_text(G_SEARCH_PATTERN(pattern), context, fd); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_hex_bytes_output_to_json(const GScanHexBytes *pattern, GScanContext *context, const sized_string_t *padding, unsigned int level, int fd) +{ + G_SEARCH_PATTERN_CLASS(g_scan_hex_bytes_parent_class)->to_json(G_SEARCH_PATTERN(pattern), context, padding, level, fd); + + /* TODO */ + +} diff --git a/src/analysis/scan/patterns/tokens/hex.h b/src/analysis/scan/patterns/tokens/hex.h new file mode 100644 index 0000000..fe5268c --- /dev/null +++ b/src/analysis/scan/patterns/tokens/hex.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * hex.h - prototypes pour la recherche de morceaux de binaire + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_HEX_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_HEX_H + + +#include <glib-object.h> + + +#include "node.h" +#include "../../pattern.h" + + + +#define G_TYPE_SCAN_HEX_BYTES g_scan_hex_bytes_get_type() +#define G_SCAN_HEX_BYTES(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_HEX_BYTES, GScanHexBytes)) +#define G_IS_SCAN_HEX_BYTES(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_HEX_BYTES)) +#define G_SCAN_HEX_BYTES_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_HEX_BYTES, GScanHexBytesClass)) +#define G_IS_SCAN_HEX_BYTES_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_HEX_BYTES)) +#define G_SCAN_HEX_BYTES_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_HEX_BYTES, GScanHexBytesClass)) + + +/* Encadrement d'une recherche de morceaux de binaire (instance) */ +typedef struct _GScanHexBytes GScanHexBytes; + +/* Encadrement d'une recherche de morceaux de binaire (classe) */ +typedef struct _GScanHexBytesClass GScanHexBytesClass; + + +/* Indique le type défini pour une suite d'octets à retrouver dans un binaire. */ +GType g_scan_hex_bytes_get_type(void); + +/* Construit un gestionnaire de recherche de texte brut. */ +GSearchPattern *g_scan_hex_bytes_new(GScanTokenNode *, bool); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_HEX_H */ diff --git a/src/analysis/scan/patterns/tokens/node-int.h b/src/analysis/scan/patterns/tokens/node-int.h new file mode 100644 index 0000000..520e2a4 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/node-int.h @@ -0,0 +1,108 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * node-int.h - prototypes internes pour la décomposition d'un motif de recherche en atomes assemblés + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODE_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODE_INT_H + + +#include "node.h" + + + +/* Communique l'intérêt d'un noeud au sein d'une analyse. */ +typedef float (* compute_scan_token_node_weight_fc) (const GScanTokenNode *); + +/* Prend acte d'une nouvelle propriété pour le noeud. */ +typedef void (* apply_scan_token_node_flags_fc) (GScanTokenNode *, ScanTokenNodeFlags); + +/* Noeuds clefs de l'arborescence mise en place */ +typedef struct _scan_tree_points_t +{ + GScanTokenNode *first_plain; /* Premier noeud textuel */ + GScanTokenNode *best_masked; /* Noeud masqué le plus long */ + +} scan_tree_points_t; + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +typedef void (* visit_scan_token_node_fc) (GScanTokenNode *, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +typedef bool (* enroll_scan_token_node_fc) (GScanTokenNode *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +typedef bool (* build_scan_token_node_id_fc) (GScanTokenNode *, GEngineBackend *); + +typedef enum _TokenNodeCheckFlags +{ + TNCF_UPDATE_IN_PLACE = (1 << 0), /* Actualisation de l'entrée */ + TNCF_CREATE_NEW = (1 << 1), /* Allocation de positions */ + TNCF_KEEP_DISCARDED = (1 << 2), /* Inversion des résultats */ + +} TokenNodeCheckFlags; + +/* Transforme les correspondances locales en trouvailles. */ +typedef void (* check_scan_token_node_fc) (const GScanTokenNode *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + +/* Décomposition d'un motif de recherche en atomes (instance) */ +struct _GScanTokenNode +{ + GObject parent; /* A laisser en premier */ + + ScanTokenNodeFlags flags; /* Propriétés particulières */ + +}; + +/* Décomposition d'un motif de recherche en atomes (classe) */ +struct _GScanTokenNodeClass +{ + GObjectClass parent; /* A laisser en premier */ + + compute_scan_token_node_weight_fc compute_weight; /* Evaluation */ + visit_scan_token_node_fc visit; /* Phase de répérage initial */ + apply_scan_token_node_flags_fc apply; /* Prise en compte de fanions */ + + enroll_scan_token_node_fc enroll; /* Inscription d'un motif */ + build_scan_token_node_id_fc build_id; /* Récupération d'identifiant */ + + check_scan_token_node_fc check_forward; /* Conversion en trouvailles */ + check_scan_token_node_fc check_backward;/* Conversion en trouvailles */ + +}; + + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +void g_scan_token_node_visit(GScanTokenNode *, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +bool _g_scan_token_node_enroll(GScanTokenNode *, GEngineBackend *, size_t, size_t *); + +/* Transforme les correspondances locales en trouvailles. */ +void _g_scan_token_node_check_forward(const GScanTokenNode *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +void _g_scan_token_node_check_backward(const GScanTokenNode *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODE_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/node.c b/src/analysis/scan/patterns/tokens/node.c new file mode 100644 index 0000000..767cc6d --- /dev/null +++ b/src/analysis/scan/patterns/tokens/node.c @@ -0,0 +1,675 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * node.c - décomposition d'un motif de recherche en atomes assemblés + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "node.h" + + +#include <assert.h> + + +#include "node-int.h" +#include "nodes/any.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des éléments de décomposition. */ +static void g_scan_token_node_class_init(GScanTokenNodeClass *); + +/* Initialise une instance d'élément décomposant un motif. */ +static void g_scan_token_node_init(GScanTokenNode *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_dispose(GScanTokenNode *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_finalize(GScanTokenNode *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un élément décomposant un motif d'octets à rechercher. */ +G_DEFINE_TYPE(GScanTokenNode, g_scan_token_node, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des éléments de décomposition. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_class_init(GScanTokenNodeClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : node = instance à initialiser. * +* * +* Description : Initialise une instance d'élément décomposant un motif. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_init(GScanTokenNode *node) +{ + node->flags = STNF_NONE; + +} + + +/****************************************************************************** +* * +* Paramètres : node = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_dispose(GScanTokenNode *node) +{ + G_OBJECT_CLASS(g_scan_token_node_parent_class)->dispose(G_OBJECT(node)); + +} + + +/****************************************************************************** +* * +* Paramètres : node = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_finalize(GScanTokenNode *node) +{ + G_OBJECT_CLASS(g_scan_token_node_parent_class)->finalize(G_OBJECT(node)); + +} + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à consulter. * +* * +* Description : Communique l'intérêt d'un noeud au sein d'une analyse. * +* * +* Retour : Poids de l'importance pour un départ de scan. * +* * +* Remarques : - * +* * +******************************************************************************/ + +float g_scan_token_node_compute_weight_for_scan(const GScanTokenNode *node) +{ + float result; /* Valeur à retourner */ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + if (class->compute_weight != NULL) + result = class->compute_weight(node); + else + result = 0; + + return result; + +} + + + + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à consulter. * +* * +* Description : Indique les propriétés particulières d'un noeud d'analyse. * +* * +* Retour : Propriétés particulières associées au noeud. * +* * +* Remarques : - * +* * +******************************************************************************/ + +ScanTokenNodeFlags g_scan_token_node_get_flags(const GScanTokenNode *node) +{ + ScanTokenNodeFlags result; /* Statut à retourner */ + + result = node->flags; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à mettre à jour. * +* flags = propriétés particulières à associer au noeud. * +* * +* Description : Marque le noeud avec des propriétés particulières. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_set_flags(GScanTokenNode *node, ScanTokenNodeFlags flags) +{ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + node->flags |= flags; + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + if (class->apply != NULL) + class->apply(node, flags); + +} + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à effectuer. * +* points = points capitaux de l'arborescence. [OUT] * +* * +* Description : Parcourt une arborescence de noeuds et y relève des éléments.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_visit(GScanTokenNode *node, scan_tree_points_t *points) +{ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + if (class->visit != NULL) + class->visit(node, points); + +} + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à préparer. * +* * +* Description : Détermine et prépare les éléments clefs d'une arborescence. * +* * +* Retour : true si une analyse à rebourd complémentaire est requise. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_setup_tree(GScanTokenNode *node) +{ + bool result; /* Prévision à retourner */ + scan_tree_points_t points; /* Repérage de points capitaux */ + GScanTokenNode *main; /* Principal noeud d'opération */ + + /* Phase de localisation */ + + points.first_plain = NULL; + points.best_masked = NULL; + + g_scan_token_node_visit(node, &points); + + /* Phase d'application */ + + g_scan_token_node_set_flags(node, STNF_FIRST); + g_scan_token_node_set_flags(node, STNF_LAST); + + if (points.first_plain != NULL) + main = points.first_plain; + + else if (points.best_masked != NULL) + main = points.best_masked; + + else + main = node; + + g_scan_token_node_set_flags(main, STNF_MAIN); + + result = (main != node); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool _g_scan_token_node_enroll(GScanTokenNode *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + result = class->enroll(node, backend, maxsize, slow); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_enroll(GScanTokenNode *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + + assert(g_engine_backend_get_atom_max_size(backend) == maxsize); + + *slow = 0; + + result = _g_scan_token_node_enroll(node, backend, maxsize, slow); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_build_id(GScanTokenNode *node, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + if (class->build_id == NULL) + result = true; + else + result = class->build_id(node, backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void _g_scan_token_node_check_forward(const GScanTokenNode *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + if (node->flags & STNF_MAIN) + { + //assert(*skip); //REMME + *skip = false; + } + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + class->check_forward(node, params, cflags, skip); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_check_forward(const GScanTokenNode *node, scan_node_check_params_t *params) +{ + node_search_offset_t offset; /* Espace des correspondances */ + bool skip; /* Mise en attente des analyses*/ + size_t ocount; /* Quantité de bornes présentes*/ + node_offset_range_t * const *ranges_ptr;/* Bornes d'espace à parcourir */ + size_t pcount; /* Nombre de correspondances */ + match_area_t * const *pending_ptr; /* Correspondances actuelles */ + size_t p; /* Boucle de parcours #2 */ + match_area_t *pending; /* Correspondance à traiter */ + phys_t old_end; /* Ancien point d'arrivée */ + size_t o; /* Boucle de parcours #1 */ + const node_offset_range_t *range; /* Bornes d'espace à parcourir */ + phys_t new_end; /* Nouveau point d'arrivée */ + + init_node_search_offset(¶ms->offset); + + skip = true; + + _g_scan_token_node_check_forward(node, params, TNCF_UPDATE_IN_PLACE, &skip); + + +#if 0 // FIXME + + /** + * Si un décalage entre octets n'a pas été consommé, + * les résultats sont étendus à minima. + */ + + ranges_ptr = get_node_search_offset_ranges(&offset, &ocount); + + if (ocount > 0) + { + /** + * Dans le cas où un unique noeud ne renvoie que vers un espace (par + * exemple : "$a = { [0] }"), il n'y a pas de résultats, donc pas + * d'initialisation. + * + * La réinitialisation des décomptes va tiquer pour cet état. La + * phase d'extension des résultats inexistants est ainsi sautée. + */ + if (count_pending_matches(matches) == 0) + { + + + for (o = 0; o < ocount; o++) + { + range = (*ranges_ptr) + o; + + + printf("range: %u - %u\n", + (unsigned int)range->min, + (unsigned int)range->max); + + + /* + new_end = old_end + range->min; + + if (new_end > matches->content_end) + new_end = matches->content_end; + + add_pending_match(pending_matches_t *, phys_t, phys_t); + + extend_pending_match_ending(matches, p, new_end); + */ + + } + + + + + + + goto offset_done; + + } + + reset_pending_matches_ttl(matches); + + pending_ptr = get_all_pending_matches(matches, &pcount); + + for (p = 0; p < pcount; p++) + { + pending = (*pending_ptr) + p; + + old_end = pending->end; + + for (o = 0; o < ocount; o++) + { + range = (*ranges_ptr) + o; + + new_end = old_end + range->min; + + if (new_end > matches->content_end) + new_end = matches->content_end; + + extend_pending_match_ending(matches, p, new_end); + + } + + } + + /** + * Pas besoin de purge ici puisque tous les résultats ont été traités + * au moins une fois, sans condition. + */ + /* purge_pending_matches(matches); */ + + offset_done: + + disable_all_ranges_in_node_search_offset(&offset); + + } + + assert(offset.used == 0); + +#endif + + exit_node_search_offset(¶ms->offset); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void _g_scan_token_node_check_backward(const GScanTokenNode *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + GScanTokenNodeClass *class; /* Classe de l'instance */ + + class = G_SCAN_TOKEN_NODE_GET_CLASS(node); + + class->check_backward(node, params, cflags, skip); + + if (node->flags & STNF_MAIN) + { + //assert(*skip); //REMME + *skip = false; + } + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_check_backward(const GScanTokenNode *node, scan_node_check_params_t *params) +{ + node_search_offset_t offset; /* Espace des correspondances */ + bool skip; /* Mise en attente des analyses*/ + size_t ocount; /* Quantité de bornes présentes*/ + node_offset_range_t * const *ranges_ptr;/* Bornes d'espace à parcourir */ + size_t pcount; /* Nombre de correspondances */ + match_area_t * const *pending_ptr; /* Correspondances actuelles */ + size_t p; /* Boucle de parcours #2 */ + match_area_t *pending; /* Correspondance à traiter */ + phys_t old_start; /* Ancien point d'arrivée */ + size_t o; /* Boucle de parcours #1 */ + const node_offset_range_t *range; /* Bornes d'espace à parcourir */ + phys_t new_start; /* Nouveau point d'arrivée */ + + init_node_search_offset(¶ms->offset); + + skip = true; + + _g_scan_token_node_check_backward(node, params, TNCF_UPDATE_IN_PLACE, &skip); + +#if 0 // FIXME + + /** + * Si un décalage entre octets n'a pas été consommé, + * les résultats sont étendus à minima. + */ + + ranges_ptr = get_node_search_offset_ranges(&offset, &ocount); + + if (ocount > 0) + { + reset_pending_matches_ttl(matches); + + pending_ptr = get_all_pending_matches(matches, &pcount); + + for (p = 0; p < pcount; p++) + { + pending = (*pending_ptr) + p; + + old_start = pending->start; + + for (o = 0; o < ocount; o++) + { + range = (*ranges_ptr) + o; + + if (old_start < range->min) + new_start = 0; + else + new_start = old_start - range->min; + + if (new_start < matches->content_start) + new_start = matches->content_start; + + extend_pending_match_beginning(matches, p, new_start); + + } + + } + + /** + * Pas besoin de purge ici puisque tous les résultats ont été traités + * au moins une fois, sans condition. + */ + /* purge_pending_matches(matches); */ + + disable_all_ranges_in_node_search_offset(&offset); + + } + + assert(offset.used == 0); + +#endif + + exit_node_search_offset(¶ms->offset); + +} diff --git a/src/analysis/scan/patterns/tokens/node.h b/src/analysis/scan/patterns/tokens/node.h new file mode 100644 index 0000000..5b1a247 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/node.h @@ -0,0 +1,127 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * node.h - prototypes pour la décomposition d'un motif de recherche en atomes assemblés + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODE_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODE_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "offset.h" +#include "../backend.h" +#include "../../context.h" +#include "../../matches/bytes.h" +#include "../../../../glibext/umemslice.h" + + +#define G_TYPE_SCAN_TOKEN_NODE g_scan_token_node_get_type() +#define G_SCAN_TOKEN_NODE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE, GScanTokenNode)) +#define G_IS_SCAN_TOKEN_NODE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE)) +#define G_SCAN_TOKEN_NODE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE, GScanTokenNodeClass)) +#define G_IS_SCAN_TOKEN_NODE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE)) +#define G_SCAN_TOKEN_NODE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE, GScanTokenNodeClass)) + + +/* Décomposition d'un motif de recherche en atomes (instance) */ +typedef struct _GScanTokenNode GScanTokenNode; + +/* Décomposition d'un motif de recherche en atomes (classe) */ +typedef struct _GScanTokenNodeClass GScanTokenNodeClass; + + +/* Propriétés particulières pour noeud d'analyse */ +typedef enum _ScanTokenNodeFlags +{ + STNF_NONE = (0 << 0), /* Absence de singularité */ + STNF_FIRST = (1 << 0), /* Premier noeud de traitement */ + STNF_LAST = (1 << 1), /* Dernier noeud de traitement */ + STNF_MAIN = (1 << 2), /* Point de départ d'analyse */ + +} ScanTokenNodeFlags; + + +/* Indique le type défini pour un élément décomposant un motif d'octets à rechercher. */ +GType g_scan_token_node_get_type(void); + +/* Communique l'intérêt d'un noeud au sein d'une analyse. */ +float g_scan_token_node_compute_weight_for_scan(const GScanTokenNode *); + + + +/* Indique les propriétés particulières d'un noeud d'analyse. */ +ScanTokenNodeFlags g_scan_token_node_get_flags(const GScanTokenNode *); + +/* Marque le noeud avec des propriétés particulières. */ +void g_scan_token_node_set_flags(GScanTokenNode *, ScanTokenNodeFlags); + +/* Détermine et prépare les éléments clefs d'une arborescence. */ +bool g_scan_token_node_setup_tree(GScanTokenNode *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +bool g_scan_token_node_enroll(GScanTokenNode *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +bool g_scan_token_node_build_id(GScanTokenNode *, GEngineBackend *); + +/* Accès direct aux éléments utiles aux contrôles */ +typedef struct _scan_node_check_params_t +{ + GScanContext *context; /* Contexte de scan en cours */ + GBinContent *content; /* Contenu binaire associé */ + GUMemSlice *allocator; /* Allocateur pour zones */ + + phys_t content_start; /* Point de début du contenu */ + phys_t content_end; /* Point de fin du contenu */ + + node_search_offset_t offset; /* Décalages à respecter */ + + bool initialized; /* Etat du suivi */ + + /* TNCF_UPDATE_IN_PLACE */ + + match_area_t *main_areas; /* Zones principales à analyser*/ + size_t main_count; /* Taille de cette liste */ + + /* TNCF_CREATE_NEW */ + + match_area_t *created_areas; /* Zones principales à analyser*/ + size_t created_count; /* Taille de cette liste */ + + /* TNCF_KEEP_DISCARDED */ + + match_area_t *kept_areas; /* Zones principales à analyser*/ + size_t kept_count; /* Taille de cette liste */ + +} scan_node_check_params_t; + +/* Transforme les correspondances locales en trouvailles. */ +void g_scan_token_node_check_forward(const GScanTokenNode *, scan_node_check_params_t *); + +/* Transforme les correspondances locales en trouvailles. */ +void g_scan_token_node_check_backward(const GScanTokenNode *, scan_node_check_params_t *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODE_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/Makefile.am b/src/analysis/scan/patterns/tokens/nodes/Makefile.am new file mode 100644 index 0000000..b5da1ee --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/Makefile.am @@ -0,0 +1,24 @@ + +noinst_LTLIBRARIES = libanalysisscanpatternstokensnodes.la + + +libanalysisscanpatternstokensnodes_la_SOURCES = \ + any-int.h \ + any.h any.c \ + choice-int.h \ + choice.h choice.c \ + masked-int.h \ + masked.h masked.c \ + not-int.h \ + not.h not.c \ + plain-int.h \ + plain.h plain.c \ + sequence-int.h \ + sequence.h sequence.c + +libanalysisscanpatternstokensnodes_la_CFLAGS = $(LIBGOBJ_CFLAGS) + + +devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) + +dev_HEADERS = $(libanalysisscanpatternstokensnodes_la_SOURCES:%c=) diff --git a/src/analysis/scan/patterns/tokens/nodes/any-int.h b/src/analysis/scan/patterns/tokens/nodes/any-int.h new file mode 100644 index 0000000..dd2e2e7 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/any-int.h @@ -0,0 +1,60 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * any-int.h - prototypes internes pour une suite d'octets quelconques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_ANY_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_ANY_INT_H + + +#include "any.h" + + +#include "../atom.h" +#include "../node-int.h" + + + +/* Espace constitué d'un ou plusieurs octets quelconques (instance) */ +struct _GScanTokenNodeAny +{ + GScanTokenNode parent; /* A laisser en premier */ + + phys_t min; /* Quantité minimale */ + phys_t max; /* Quantité maximale */ + bool has_max; /* Quantité définie ? */ + +}; + +/* Espace constitué d'un ou plusieurs octets quelconques (classe) */ +struct _GScanTokenNodeAnyClass +{ + GScanTokenNodeClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un noeud pointant une série d'octets. */ +bool g_scan_token_node_any_create(GScanTokenNodeAny *, const phys_t *, const phys_t *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_ANY_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/any.c b/src/analysis/scan/patterns/tokens/nodes/any.c new file mode 100644 index 0000000..4334fff --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/any.c @@ -0,0 +1,765 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * any.c - suite d'octets quelconques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "any.h" + + +#include <assert.h> + + +#include "any-int.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des séries d'octets quelconques. */ +static void g_scan_token_node_any_class_init(GScanTokenNodeAnyClass *); + +/* Initialise une instance de série d'octets quelconques. */ +static void g_scan_token_node_any_init(GScanTokenNodeAny *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_any_dispose(GScanTokenNodeAny *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_any_finalize(GScanTokenNodeAny *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +static bool g_scan_token_node_any_enroll(GScanTokenNodeAny *, GEngineBackend *, size_t, size_t *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_any_check_forward(const GScanTokenNodeAny *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_any_check_backward(const GScanTokenNodeAny *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une série d'octets quelconque, vide ou non. */ +G_DEFINE_TYPE(GScanTokenNodeAny, g_scan_token_node_any, G_TYPE_SCAN_TOKEN_NODE); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des séries d'octets quelconques. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_any_class_init(GScanTokenNodeAnyClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenNodeClass *node; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_any_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_any_finalize; + + node = G_SCAN_TOKEN_NODE_CLASS(klass); + + node->apply = (apply_scan_token_node_flags_fc)NULL; + node->visit = (visit_scan_token_node_fc)NULL; + node->enroll = (enroll_scan_token_node_fc)g_scan_token_node_any_enroll; + node->check_forward = (check_scan_token_node_fc)g_scan_token_node_any_check_forward; + node->check_backward = (check_scan_token_node_fc)g_scan_token_node_any_check_backward; + +} + + +/****************************************************************************** +* * +* Paramètres : any = instance à initialiser. * +* * +* Description : Initialise une instance de série d'octets quelconques. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_any_init(GScanTokenNodeAny *any) +{ + any->min = 0; + any->has_max = false; + +} + + +/****************************************************************************** +* * +* Paramètres : any = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_any_dispose(GScanTokenNodeAny *any) +{ + G_OBJECT_CLASS(g_scan_token_node_any_parent_class)->dispose(G_OBJECT(any)); + +} + + +/****************************************************************************** +* * +* Paramètres : any = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_any_finalize(GScanTokenNodeAny *any) +{ + G_OBJECT_CLASS(g_scan_token_node_any_parent_class)->finalize(G_OBJECT(any)); + +} + + +/****************************************************************************** +* * +* Paramètres : min = éventuelle quantité minimale à retrouver. * +* max = éventuelle quantité maximale à retrouver. * +* * +* Description : Construit un noeud pointant une série d'octets quelconques. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_any_new(const phys_t *min, const phys_t *max) +{ + GScanTokenNode *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_NODE_ANY, NULL); + + if (!g_scan_token_node_any_create(G_SCAN_TOKEN_NODE_ANY(result), min, max)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : any = séquence d'octets quelconques à initialiser pleinement.* +* min = éventuelle quantité minimale à retrouver. * +* max = éventuelle quantité maximale à retrouver. * +* * +* Description : Met en place un noeud pointant une série d'octets. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_any_create(GScanTokenNodeAny *any, const phys_t *min, const phys_t *max) +{ + bool result; /* Bilan à retourner */ + + result = true; + + if (min != NULL) + any->min = *min; + else + any->min = 0; + + if (max != NULL) + { + any->max = *max; + + result = (any->min <= any->max); + + if (result && any->min == any->max) + result = (any->min > 0); + + } + + any->has_max = (max != NULL); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : any = séquence d'octets quelconques à étendre. * +* extra = étendue supplémentaire à intégrer. * +* * +* Description : Etend un noeud pointant une série d'octets. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_any_merge(GScanTokenNodeAny *any, GScanTokenNodeAny *extra) +{ + any->min += extra->min; + + if (any->has_max && extra->has_max) + any->max += extra->max; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_any_enroll(GScanTokenNodeAny *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + bool forced; /* Inclusion dans un scan ? */ + + result = true; + + forced = (g_scan_token_node_get_flags(G_SCAN_TOKEN_NODE(node)) & STNF_MAIN); + + if (forced) + *slow += (maxsize * 4); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_any_check_forward(const GScanTokenNodeAny *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + ScanTokenNodeFlags flags; /* Particularités du noeud */ + bool forced; /* Inclusion dans un scan ? */ + phys_t size; /* Quantité d'octets considérés*/ + phys_t match_size; /* Taille de correspondance */ + phys_t i; /* Boucle de parcours #1 */ + match_area_t *space; /* Nouvelle zone à intégrer */ + match_area_t *area; /* Correspondance à valider */ + match_area_t *next; /* Correspondance suivante */ + phys_t after; /* Espace disposible après */ + phys_t min_end; /* Fin la plus proche possible */ + phys_t max_end; /* Fin la plus éloignée trouvée*/ + bool updated; /* Existence de correspondance */ + size_t rcount; /* Quantité de bornes présentes*/ + const node_offset_range_t *ranges; /* Bornes d'espace à parcourir */ + size_t r; /* Boucle de parcours #2 */ + phys_t updated_edge; /* Nouvelle bordure de motif */ + match_area_t *new_area; /* Copie de correspondance */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + flags = g_scan_token_node_get_flags(G_SCAN_TOKEN_NODE(node)); + + forced = (flags & STNF_MAIN); + + assert((!params->initialized && forced) || (params->initialized & !forced)); + + /** + * La situation forcée correspond au cas particulier d'une définition + * complètement abstraite : ??, ?? ??, etc. + */ + if (forced) + { + size = params->content_end - params->content_start; + + if (node->has_max && 0 /* greedy ? */) + { + match_size = node->max; + + if (match_size > size) + match_size = node->min; + + } + else + match_size = node->min; + + /** + * Si le contenu binaire est trop petit pour contenir au moins un enregistrement, + * aucune correspondance n'est enregistrée. Comme le noeud est le principale, ie. + * seul et unique, l'analyse s'arrête ensuite d'elle même. + * + * Si le contenu binaire est suffisamment large, des espaces sont créés et l'analyse + * se termine ensuite. La conservation des espaces n'est donc pas utile, ni réalisée. + */ + + if (match_size <= size) + { + size -= (match_size - 1); + + assert(cflags & TNCF_UPDATE_IN_PLACE); + + for (i = 0; i < size; i++) + { + space = g_umem_slice_alloc(params->allocator); + + space->start = params->content_start + i; + space->end = space->start + match_size; + + add_tail_match_area(space, ¶ms->main_areas); + + } + + params->main_count += size; + + } + + } + + /** + * Situation usuelle : des espaces séparent deux noeuds. + */ + else + { + assert(params->initialized); + + /** + * Les espaces existants sont à compléter. La présence de tels espaces + * restant à traiter peut provenir d'un aiguillage imposé par un motif + * tel que : + * + * ( aa ?? ?? | bb cc dd ) [0-5] ee ee + * + * Deux espaces sont à considérer avant de rechercher des octets ee : + * [2-7] et [0-5]. + * + * Note : ces espaces peuvent être disjoints. + * + * Si aucun espace n'est en place, un est créé. + */ + + extend_node_search_offset(¶ms->offset, node->min, node->max, node->has_max); + + /** + * Si un décalage enregistré ne peut être consommé par un noeud, les + * résultats sont étendus ici à minima ou maxima. + */ + + if (flags & STNF_LAST) + { + assert(offsets_exist(¶ms->offset)); + + if (0x0) printf(" LIST : %p (sz = %zu)\n", params->main_areas, params->main_count); + + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + assert(area->end <= params->content_end); + + after = params->content_end - area->end; + + if (0x0) printf("---------- iter @ %u -> %u\n", (unsigned int)area->start, (unsigned int)area->end); + + min_end = params->content_end; + max_end = params->content_start; + + updated = false; + + ranges = get_node_search_offset_ranges_2(¶ms->offset, &rcount); + + for (r = 0; r < rcount; r++) + { + if (ranges[r].min > after) + continue; + + updated_edge = area->end + ranges[r].min; + + if (updated_edge < min_end) + min_end = updated_edge; + + if (ranges[r].has_max) + { + if (ranges[r].max > after) + updated_edge = params->content_end; + else + updated_edge = area->end + ranges[r].max; + + if (updated_edge > max_end) + max_end = updated_edge; + + } + + updated = true; + + } + + if (updated) + { + /** + * Si seuls les rejets sont d'intérêt, les correspondances établies + * ne se voient pas mises à jours ni retirées. + */ + + if ((cflags & TNCF_KEEP_DISCARDED) == 0) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + area->end = (1 /* greedy */ ? min_end : max_end); + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->end = (1 /* greedy */ ? min_end : max_end); + + add_tail_match_area(new_area, ¶ms->created_areas); + params->created_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + else + { + /** + * Si la liste principale doit être mise à jour... + */ + + if (cflags & TNCF_UPDATE_IN_PLACE) + { + del_match_area(area, ¶ms->main_areas); + assert(params->main_count > 0); + params->main_count--; + } + + /** + * Au cas où le rejet est d'intérêt, l'absence de correspondance + * est conservée dans une liste dédiée. + */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + { + add_tail_match_area(area, ¶ms->kept_areas); + params->kept_count++; + } + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->end = (1 /* greedy */ ? min_end : max_end); + + add_tail_match_area(new_area, ¶ms->kept_areas); + params->kept_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + } + + disable_all_ranges_in_node_search_offset(¶ms->offset); + + } + + } + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_any_check_backward(const GScanTokenNodeAny *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + ScanTokenNodeFlags flags; /* Particularités du noeud */ +#ifndef NDEBUG + bool forced; /* Inclusion dans un scan ? */ +#endif + match_area_t *area; /* Correspondance à valider */ + match_area_t *next; /* Correspondance suivante */ + phys_t before; /* Espace disposible avant */ + phys_t min_start; /* Début le plus proche trouvé */ + phys_t max_start; /* Début le plus distant trouvé*/ + bool updated; /* Existence de correspondance */ + size_t rcount; /* Quantité de bornes présentes*/ + const node_offset_range_t *ranges; /* Bornes d'espace à parcourir */ + size_t r; /* Boucle de parcours */ + phys_t updated_edge; /* Nouvelle bordure de motif */ + match_area_t *new_area; /* Copie de correspondance */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + /** + * En lecture à rebourd, au moins un noeud a été solicité pour analyse (lors + * du sens de lecture normal). Donc l'initialisation a déjà dû avoir lieu. + */ + + assert(params->initialized); + + flags = g_scan_token_node_get_flags(G_SCAN_TOKEN_NODE(node)); + + /** + * Si les recherches associées au noeud ont été forcées, alors les traitements + * liés ont déjà été effectués, et l'appel de cette fonction aurait dû être sauté. + */ +#ifndef NDEBUG + forced = (flags & STNF_MAIN); + assert(!forced); +#endif + + /** + * Les considérations pour l'extension des espaces en place sont identiques + * à celles formulées dans la fonction g_scan_token_node_any_check_forward(). + */ + + extend_node_search_offset(¶ms->offset, node->min, node->max, node->has_max); + + /** + * Si un décalage enregistré ne peut être consommé par un noeud, les + * résultats sont étendus ici à minima ou maxima. + */ + + if (flags & STNF_FIRST) + { + assert(offsets_exist(¶ms->offset)); + + if (0x0) printf(" LIST : %p (sz = %zu)\n", params->main_areas, params->main_count); + + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + assert(params->content_start <= area->start); + + before = area->start - params->content_start; + + if (0x0) printf("---------- iter @ %u -> %u\n", (unsigned int)area->start, (unsigned int)area->end); + + min_start = params->content_start; + max_start = params->content_end; + + updated = false; + + ranges = get_node_search_offset_ranges_2(¶ms->offset, &rcount); + + for (r = 0; r < rcount; r++) + { + if (ranges[r].min > before) + continue; + + updated_edge = area->start - ranges[r].min; + + if (updated_edge > min_start) + min_start = updated_edge; + + if (ranges[r].has_max) + { + if (ranges[r].max > before) + updated_edge = params->content_start; + else + updated_edge = area->start - ranges[r].max; + + if (updated_edge < max_start) + max_start = updated_edge; + + } + + updated = true; + + } + + if (updated) + { + /** + * Si seuls les rejets sont d'intérêt, les correspondances établies + * ne se voient pas mises à jours ni retirées. + */ + + if ((cflags & TNCF_KEEP_DISCARDED) == 0) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + area->start = (1 /* greedy */ ? min_start : max_start); + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->start = (1 /* greedy */ ? min_start : max_start); + + add_tail_match_area(new_area, ¶ms->created_areas); + params->created_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + else + { + /** + * Si la liste principale doit être mise à jour... + */ + + if (cflags & TNCF_UPDATE_IN_PLACE) + { + del_match_area(area, ¶ms->main_areas); + assert(params->main_count > 0); + params->main_count--; + } + + /** + * Au cas où le rejet est d'intérêt, l'absence de correspondance + * est conservée dans une liste dédiée. + */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + { + add_tail_match_area(area, ¶ms->kept_areas); + params->kept_count++; + } + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->start = (1 /* greedy */ ? min_start : max_start); + + add_tail_match_area(new_area, ¶ms->kept_areas); + params->kept_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + } + + disable_all_ranges_in_node_search_offset(¶ms->offset); + + } + +} diff --git a/src/analysis/scan/patterns/tokens/nodes/any.h b/src/analysis/scan/patterns/tokens/nodes/any.h new file mode 100644 index 0000000..9b2233f --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/any.h @@ -0,0 +1,61 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * any.h - prototypes pour une suite d'octets quelconques + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_ANY_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_ANY_H + + +#include <glib-object.h> + + +#include "../node.h" + + + +#define G_TYPE_SCAN_TOKEN_NODE_ANY g_scan_token_node_any_get_type() +#define G_SCAN_TOKEN_NODE_ANY(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE_ANY, GScanTokenNodeAny)) +#define G_IS_SCAN_TOKEN_NODE_ANY(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE_ANY)) +#define G_SCAN_TOKEN_NODE_ANY_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE_ANY, GScanTokenNodeAnyClass)) +#define G_IS_SCAN_TOKEN_NODE_ANY_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE_ANY)) +#define G_SCAN_TOKEN_NODE_ANY_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE_ANY, GScanTokenNodeAnyClass)) + + +/* Espace constitué d'un ou plusieurs octets quelconques (instance) */ +typedef struct _GScanTokenNodeAny GScanTokenNodeAny; + +/* Espace constitué d'un ou plusieurs octets quelconques (classe) */ +typedef struct _GScanTokenNodeAnyClass GScanTokenNodeAnyClass; + + +/* Indique le type défini pour une série d'octets quelconque, vide ou non. */ +GType g_scan_token_node_any_get_type(void); + +/* Construit un noeud pointant une série d'octets quelconques. */ +GScanTokenNode *g_scan_token_node_any_new(const phys_t *, const phys_t *); + +/* Etend un noeud pointant une série d'octets. */ +void g_scan_token_node_any_merge(GScanTokenNodeAny *, GScanTokenNodeAny *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_ANY_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/choice-int.h b/src/analysis/scan/patterns/tokens/nodes/choice-int.h new file mode 100644 index 0000000..77a4058 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/choice-int.h @@ -0,0 +1,54 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * choice-int.h - prototypes internes pour des décompositions alternatives de motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_CHOICE_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_CHOICE_INT_H + + +#include "choice.h" + + +#include "../node-int.h" + + + +/* Décompositions alternatives de motif de recherche (instance) */ +struct _GScanTokenNodeChoice +{ + GScanTokenNode parent; /* A laisser en premier */ + + GScanTokenNode **children; /* Sous-noeuds à représenter */ + size_t count; /* Taille de cette liste */ + +}; + +/* Décompositions alternatives de motif de recherche (classe) */ +struct _GScanTokenNodeChoiceClass +{ + GScanTokenNodeClass parent; /* A laisser en premier */ + +}; + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_CHOICE_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/choice.c b/src/analysis/scan/patterns/tokens/nodes/choice.c new file mode 100644 index 0000000..2a5e5f5 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/choice.c @@ -0,0 +1,646 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * choice.c - décompositions alternatives de motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "choice.h" + + +#include <assert.h> + + +#include "choice-int.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des décompositions alternatives. */ +static void g_scan_token_node_choice_class_init(GScanTokenNodeChoiceClass *); + +/* Initialise une instance de décompositions alternatives. */ +static void g_scan_token_node_choice_init(GScanTokenNodeChoice *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_choice_dispose(GScanTokenNodeChoice *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_choice_finalize(GScanTokenNodeChoice *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Communique l'intérêt d'un noeud au sein d'une analyse. */ +static float g_scan_token_node_choice_compute_weight_for_scan(const GScanTokenNodeChoice *); + +/* Prend acte d'une nouvelle propriété pour le noeud. */ +static void g_scan_token_node_choice_apply_flags(GScanTokenNodeChoice *, ScanTokenNodeFlags); + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +static void g_scan_token_node_choice_visit(GScanTokenNodeChoice *, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +static bool g_scan_token_node_choice_enroll(GScanTokenNodeChoice *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +static bool g_scan_token_node_choice_build_id(GScanTokenNodeChoice *, GEngineBackend *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_choice_check_forward(const GScanTokenNodeChoice *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_choice_check_backward(const GScanTokenNodeChoice *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour des décompositions alternatives de motif de recherche. */ +G_DEFINE_TYPE(GScanTokenNodeChoice, g_scan_token_node_choice, G_TYPE_SCAN_TOKEN_NODE); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des décompositions alternatives. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_class_init(GScanTokenNodeChoiceClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenNodeClass *node; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_choice_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_choice_finalize; + + node = G_SCAN_TOKEN_NODE_CLASS(klass); + + node->compute_weight = (compute_scan_token_node_weight_fc)g_scan_token_node_choice_compute_weight_for_scan; + node->apply = (apply_scan_token_node_flags_fc)g_scan_token_node_choice_apply_flags; + node->visit = (visit_scan_token_node_fc)g_scan_token_node_choice_visit; + node->enroll = (enroll_scan_token_node_fc)g_scan_token_node_choice_enroll; + node->build_id = (build_scan_token_node_id_fc)g_scan_token_node_choice_build_id; + node->check_forward = (check_scan_token_node_fc)g_scan_token_node_choice_check_forward; + node->check_backward = (check_scan_token_node_fc)g_scan_token_node_choice_check_backward; + +} + + +/****************************************************************************** +* * +* Paramètres : choice = instance à initialiser. * +* * +* Description : Initialise une instance de décompositions alternatives. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_init(GScanTokenNodeChoice *choice) +{ + choice->children = NULL; + choice->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : choice = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_dispose(GScanTokenNodeChoice *choice) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < choice->count; i++) + g_clear_object(&choice->children[i]); + + G_OBJECT_CLASS(g_scan_token_node_choice_parent_class)->dispose(G_OBJECT(choice)); + +} + + +/****************************************************************************** +* * +* Paramètres : choice = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_finalize(GScanTokenNodeChoice *choice) +{ + if (choice->children != NULL) + free(choice->children); + + G_OBJECT_CLASS(g_scan_token_node_choice_parent_class)->finalize(G_OBJECT(choice)); + +} + + +/****************************************************************************** +* * +* Paramètres : - * +* * +* Description : Construit une série de décompositions alternatives de motif. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_choice_new(void) +{ + GScanTokenNode *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_NODE_CHOICE, NULL); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : choice = ensemble de noeuds à compléter. * +* node = nouveau noeud à intégrer. * +* * +* Description : Ajoute un noeud à aux décompositions alternatives de motif. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_choice_add(GScanTokenNodeChoice *choice, GScanTokenNode *node) +{ + choice->children = realloc(choice->children, ++choice->count * sizeof(GScanTokenNode *)); + + choice->children[choice->count - 1] = node; + g_object_ref(G_OBJECT(node)); + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à consulter. * +* * +* Description : Communique l'intérêt d'un noeud au sein d'une analyse. * +* * +* Retour : Poids de l'importance pour un départ de scan. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static float g_scan_token_node_choice_compute_weight_for_scan(const GScanTokenNodeChoice *node) +{ + float result; /* Valeur à retourner */ + size_t weight_count; /* Nombre de comptabilisations */ + size_t i; /* Boucle de parcours */ + float weight; /* Nouveau poids à intégrer */ + + result = 0; + + weight_count = 0; + + for (i = 0; i < node->count; i++) + { + weight = g_scan_token_node_compute_weight_for_scan(node->children[i]); + + if (weight > 0) + { + result += weight; + weight_count++; + } + + } + + if (weight_count != node->count) + result = 0; + else + result /= weight_count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à mettre à jour. * +* flags = propriétés particulières à associer au noeud. * +* * +* Description : Prend acte d'une nouvelle propriété pour le noeud. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_apply_flags(GScanTokenNodeChoice *node, ScanTokenNodeFlags flags) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < node->count; i++) + g_scan_token_node_set_flags(node->children[i], flags); + +} + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à effectuer. * +* points = points capitaux de l'arborescence. [OUT] * +* * +* Description : Parcourt une arborescence de noeuds et y relève des éléments.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_visit(GScanTokenNodeChoice *node, scan_tree_points_t *points) +{ + size_t first_plain_count; /* Décompte de noeuds textuels */ + size_t i; /* Boucle de parcours */ + scan_tree_points_t tmp_points; /* Synthèse d'analyse locale */ + + if (points->first_plain != NULL) + return; + + first_plain_count = 0; + + for (i = 0; i < node->count; i++) + { + tmp_points.first_plain = NULL; + tmp_points.best_masked = NULL; + + g_scan_token_node_visit(node->children[i], &tmp_points); + + if (tmp_points.first_plain != NULL) + first_plain_count++; + + } + + if (first_plain_count == node->count) + points->first_plain = G_SCAN_TOKEN_NODE(node); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_choice_enroll(GScanTokenNodeChoice *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours */ + + result = true; + + for (i = 0; i < node->count && result; i++) + result = _g_scan_token_node_enroll(node->children[i], backend, maxsize, slow); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_choice_build_id(GScanTokenNodeChoice *node, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours #1 */ + + result = true; + + for (i = 0; i < node->count && result; i++) + result = g_scan_token_node_build_id(node->children[i], backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_check_forward(const GScanTokenNodeChoice *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + bool initialized; /* Initialisation du suivi ? */ + match_area_t *collected_areas; /* Zones mises en place ici */ + size_t collected_count; /* Quantité de ces zones */ + TokenNodeCheckFlags local_cflags; /* Particularités nouvelles */ + size_t i; /* Boucle de parcours */ + scan_node_check_params_t local_params; /* Rassemblement de paramètres */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + /* Lancement des sous-traitements */ + + initialized = false; + + collected_areas = NULL; + collected_count = 0; + + local_cflags = (cflags & ~TNCF_UPDATE_IN_PLACE) | TNCF_CREATE_NEW; + + for (i = 0; i < node->count; i++) + { + local_params = *params; + + local_params.created_areas = NULL; + local_params.created_count = 0; + + local_params.kept_areas = NULL; + local_params.kept_count = 0; + + if ((cflags & TNCF_CREATE_NEW) == 0 && (i + 1) == node->count) + local_cflags = cflags; + + _g_scan_token_node_check_forward(node->children[i], &local_params, local_cflags, skip); + + initialized |= local_params.initialized; + + if (local_cflags & TNCF_KEEP_DISCARDED) + { + merge_match_areas(&collected_areas, &local_params.kept_areas); + collected_count += local_params.kept_count; + } + + else if (local_cflags & TNCF_CREATE_NEW) + { + merge_match_areas(&collected_areas, &local_params.created_areas); + collected_count += local_params.created_count; + } + + else + { + assert(local_cflags & TNCF_UPDATE_IN_PLACE); + + merge_match_areas(&collected_areas, &local_params.main_areas); + collected_count += local_params.main_count; + + } + + } + + /* Enregistrement des résultats finaux */ + + if (collected_count > 1) + sort_match_areas_no_dup(&collected_areas, &collected_count, compare_match_area_as_dl_item, NULL); + + if (0x0) printf("[%s] collected: #%zu (bis)\n", __FUNCTION__, collected_count); + + params->initialized = initialized; + + if (cflags & TNCF_KEEP_DISCARDED) + { + params->kept_areas = collected_areas; + params->kept_count = collected_count; + } + + else if (cflags & TNCF_CREATE_NEW) + { + params->created_areas = collected_areas; + params->created_count = collected_count; + } + + else + { + assert(cflags & TNCF_UPDATE_IN_PLACE); + + params->main_areas = collected_areas; + params->main_count = collected_count; + + } + + + + + + /// TODO : gestion des offets en sortie : ajout (+ ajout d'un test en Python) + + + + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_choice_check_backward(const GScanTokenNodeChoice *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + match_area_t *collected_areas; /* Zones mises en place ici */ + size_t collected_count; /* Quantité de ces zones */ + TokenNodeCheckFlags local_cflags; /* Particularités nouvelles */ + size_t i; /* Boucle de parcours */ + scan_node_check_params_t local_params; /* Rassemblement de paramètres */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + /** + * En lecture à rebourd, au moins un noeud a été solicité pour analyse (lors + * du sens de lecture normal). Donc l'initialisation a déjà dû avoir lieu. + */ + + assert(params->initialized); + + /* Lancement des sous-traitements */ + + collected_areas = NULL; + collected_count = 0; + + local_cflags = (cflags & ~TNCF_UPDATE_IN_PLACE) | TNCF_CREATE_NEW; + + for (i = 0; i < node->count; i++) + { + local_params = *params; + + local_params.created_areas = NULL; + local_params.created_count = 0; + + local_params.kept_areas = NULL; + local_params.kept_count = 0; + + if ((cflags & TNCF_CREATE_NEW) == 0 && (i + 1) == node->count) + local_cflags = cflags; + + _g_scan_token_node_check_backward(node->children[i], &local_params, local_cflags, skip); + + if (local_cflags & TNCF_KEEP_DISCARDED) + { + merge_match_areas(&collected_areas, &local_params.kept_areas); + collected_count += local_params.kept_count; + } + + else if (local_cflags & TNCF_CREATE_NEW) + { + merge_match_areas(&collected_areas, &local_params.created_areas); + collected_count += local_params.created_count; + } + + else + { + assert(local_cflags & TNCF_UPDATE_IN_PLACE); + + merge_match_areas(&collected_areas, &local_params.main_areas); + collected_count += local_params.main_count; + + } + + } + + /* Enregistrement des résultats finaux */ + + if (collected_count > 1) + sort_match_areas_no_dup(&collected_areas, &collected_count, compare_match_area_as_dl_item, NULL); + + if (0x0) printf("[%s] collected: #%zu (bis)\n", __FUNCTION__, collected_count); + + if (cflags & TNCF_KEEP_DISCARDED) + { + params->kept_areas = collected_areas; + params->kept_count = collected_count; + } + + else if (cflags & TNCF_CREATE_NEW) + { + params->created_areas = collected_areas; + params->created_count = collected_count; + } + + else + { + assert(cflags & TNCF_UPDATE_IN_PLACE); + + params->main_areas = collected_areas; + params->main_count = collected_count; + + } + + + + + + /// TODO : gestion des offets en sortie : ajout (+ ajout d'un test en Python) + + + + + + +} diff --git a/src/analysis/scan/patterns/tokens/nodes/choice.h b/src/analysis/scan/patterns/tokens/nodes/choice.h new file mode 100644 index 0000000..e793b1e --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/choice.h @@ -0,0 +1,61 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * choice.h - prototypes pour des décompositions alternatives de motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_CHOICE_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_CHOICE_H + + +#include <glib-object.h> + + +#include "../node.h" + + + +#define G_TYPE_SCAN_TOKEN_NODE_CHOICE g_scan_token_node_choice_get_type() +#define G_SCAN_TOKEN_NODE_CHOICE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE_CHOICE, GScanTokenNodeChoice)) +#define G_IS_SCAN_TOKEN_NODE_CHOICE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE_CHOICE)) +#define G_SCAN_TOKEN_NODE_CHOICE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE_CHOICE, GScanTokenNodeChoiceClass)) +#define G_IS_SCAN_TOKEN_NODE_CHOICE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE_CHOICE)) +#define G_SCAN_TOKEN_NODE_CHOICE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE_CHOICE, GScanTokenNodeChoiceClass)) + + +/* Décompositions alternatives de motif de recherche (instance) */ +typedef struct _GScanTokenNodeChoice GScanTokenNodeChoice; + +/* Décompositions alternatives de motif de recherche (classe) */ +typedef struct _GScanTokenNodeChoiceClass GScanTokenNodeChoiceClass; + + +/* Indique le type défini pour des décompositions alternatives de motif de recherche. */ +GType g_scan_token_node_choice_get_type(void); + +/* Construit une série de décompositions alternatives de motif. */ +GScanTokenNode *g_scan_token_node_choice_new(void); + +/* Ajoute un noeud à aux décompositions alternatives de motif. */ +void g_scan_token_node_choice_add(GScanTokenNodeChoice *, GScanTokenNode *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_CHOICE_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/masked-int.h b/src/analysis/scan/patterns/tokens/nodes/masked-int.h new file mode 100644 index 0000000..5fcc330 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/masked-int.h @@ -0,0 +1,64 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * masked-int.h - prototypes internes pour la gestion d'une recherche de motif partielle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_MASKED_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_MASKED_INT_H + + +#include "masked.h" + + +#include "../node-int.h" + + + +/* Bribe de motif partielle pour recherches (instance) */ +struct _GScanTokenNodeMasked +{ + GScanTokenNode parent; /* A laisser en premier */ + + masked_byte_t *bytes; /* Série d'octets masqués */ + size_t len; /* Taille de cette série */ + + sized_binary_t *raw; /* Liste de motifs à couvrir */ + size_t raw_count; /* Taille de cette liste */ + + tracked_scan_atom_t *enrolled_atoms; /* Atomes correspondants */ + size_t enrolled_count; /* Quantité avec identifiant */ + +}; + +/* Bribe de motif partielle pour recherches (classe) */ +struct _GScanTokenNodeMaskedClass +{ + GScanTokenNodeClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une bribe de motif partielle. */ +bool g_scan_token_node_masked_create(GScanTokenNodeMasked *, const masked_byte_t *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_MASKED_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/masked.c b/src/analysis/scan/patterns/tokens/nodes/masked.c new file mode 100644 index 0000000..5194cb8 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/masked.c @@ -0,0 +1,1135 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * masked.c - gestion d'une recherche de motif partielle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "masked.h" + + +#include <assert.h> + + +#include "masked-int.h" +#include "../../backends/bitap.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des bribes de motif partielles. */ +static void g_scan_token_node_masked_class_init(GScanTokenNodeMaskedClass *); + +/* Initialise une instance de bribe de motif partielle. */ +static void g_scan_token_node_masked_init(GScanTokenNodeMasked *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_masked_dispose(GScanTokenNodeMasked *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_masked_finalize(GScanTokenNodeMasked *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +static void g_scan_token_node_masked_visit(GScanTokenNodeMasked *, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +static bool g_scan_token_node_masked_enroll(GScanTokenNodeMasked *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +static bool g_scan_token_node_masked_build_id(GScanTokenNodeMasked *, GEngineBackend *); + +/* Détermine si un contenu d'intérêt est présent à une position. */ +static bool check_scan_token_node_masked_content(const masked_byte_t *, size_t, phys_t, GBinContent *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_masked_check_forward(const GScanTokenNodeMasked *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_masked_check_backward(const GScanTokenNodeMasked *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un noeud représentant une bribe partielle à retrouver. */ +G_DEFINE_TYPE(GScanTokenNodeMasked, g_scan_token_node_masked, G_TYPE_SCAN_TOKEN_NODE); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des bribes de motif partielles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_class_init(GScanTokenNodeMaskedClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenNodeClass *node; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_masked_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_masked_finalize; + + node = G_SCAN_TOKEN_NODE_CLASS(klass); + + node->apply = (apply_scan_token_node_flags_fc)NULL; + node->visit = (visit_scan_token_node_fc)g_scan_token_node_masked_visit; + node->enroll = (enroll_scan_token_node_fc)g_scan_token_node_masked_enroll; + node->build_id = (build_scan_token_node_id_fc)g_scan_token_node_masked_build_id; + node->check_forward = (check_scan_token_node_fc)g_scan_token_node_masked_check_forward; + node->check_backward = (check_scan_token_node_fc)g_scan_token_node_masked_check_backward; + +} + + +/****************************************************************************** +* * +* Paramètres : masked = instance à initialiser. * +* * +* Description : Initialise une instance de bribe de motif partielle. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_init(GScanTokenNodeMasked *masked) +{ + masked->bytes = NULL; + masked->len = 0; + + masked->raw = NULL; + masked->raw_count = 0; + + masked->enrolled_atoms = NULL; + masked->enrolled_count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : masked = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_dispose(GScanTokenNodeMasked *masked) +{ + G_OBJECT_CLASS(g_scan_token_node_masked_parent_class)->dispose(G_OBJECT(masked)); + +} + + +/****************************************************************************** +* * +* Paramètres : masked = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_finalize(GScanTokenNodeMasked *masked) +{ + size_t i; /* Boucle de parcours */ + + if (masked->bytes != NULL) + free(masked->bytes); + + for (i = 0; i < masked->raw_count; i++) + exit_szstr(&masked->raw[i]); + + if (masked->raw != NULL) + free(masked->raw); + + if (masked->enrolled_atoms != NULL) + free(masked->enrolled_atoms); + + G_OBJECT_CLASS(g_scan_token_node_masked_parent_class)->finalize(G_OBJECT(masked)); + +} + + +/****************************************************************************** +* * +* Paramètres : byte = valeur masquée à intégrer. * +* * +* Description : Construit une bribe de motif partielle. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_masked_new(const masked_byte_t *byte) +{ + GScanTokenNode *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_NODE_MASKED, NULL); + + if (!g_scan_token_node_masked_create(G_SCAN_TOKEN_NODE_MASKED(result), byte)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : masked = bribe partielle à initialiser pleinement. * +* byte = valeur masquée à intégrer. * +* * +* Description : Met en place une bribe de motif partielle. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_masked_create(GScanTokenNodeMasked *masked, const masked_byte_t *byte) +{ + bool result; /* Bilan à retourner */ + + result = true; + + g_scan_token_node_masked_add(masked, byte); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : masked = ensemble de noeuds à compléter. * +* byte = valeur masquée à intégrer. * +* * +* Description : Enregistre la valeur d'octet à rechercher avec son masque. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_masked_add(GScanTokenNodeMasked *masked, const masked_byte_t *byte) +{ + assert((byte->value & 0x0f) == 0 || (byte->value & 0xf0) == 0); + + masked->bytes = realloc(masked->bytes, ++masked->len * sizeof(masked_byte_t)); + + masked->bytes[masked->len - 1] = *byte; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à effectuer. * +* points = points capitaux de l'arborescence. [OUT] * +* * +* Description : Parcourt une arborescence de noeuds et y relève des éléments.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_visit(GScanTokenNodeMasked *node, scan_tree_points_t *points) +{ + GScanTokenNodeMasked *other; /* Concurrence à mesurer */ + + if (points->best_masked == NULL) + points->best_masked = G_SCAN_TOKEN_NODE(node); + + else + { + other = G_SCAN_TOKEN_NODE_MASKED(points->best_masked); + + if (node->len > other->len) + points->best_masked = G_SCAN_TOKEN_NODE(node); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_masked_enroll(GScanTokenNodeMasked *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + bool forced; /* Inclusion dans un scan ? */ + //size_t len_to_enroll; /* Taille à considérer */ + size_t i; /* Boucle de parcours */ + + result = true; + + forced = (g_scan_token_node_get_flags(G_SCAN_TOKEN_NODE(node)) & STNF_MAIN); + + if (forced) + { + *slow += (maxsize * 2); + + node->raw = make_atoms_from_masked_bytes(node->bytes, node->len, &node->raw_count); + + /** + * Dans le cas bien précis de l'usage de l'algorithme Bitap pour les recherches + * dans le contenu binaire à analyser, on tire parti du coût nul des recherches + * multiples pour une même position. + */ + + if (G_IS_BITAP_BACKEND(backend)) + { + //len_to_enroll = (node->len < maxsize ? node->len : maxsize); + + /* TODO */ + assert(false); + + + node->enrolled_count = 1; + + } + + else + { + node->enrolled_atoms = malloc(node->raw_count * sizeof(tracked_scan_atom_t)); + node->enrolled_count = node->raw_count; + + for (i = 0; i < node->enrolled_count && result; i++) + { + find_best_atom(&node->raw[i], maxsize, &node->enrolled_atoms[i], NULL); + + /** + * Correction : si l'atome ne représente qu'une vue partielle, + * la validation rapide ne peut s'appliquer. + */ + if (node->enrolled_atoms[i].fast_check) + node->enrolled_atoms[i].fast_check = (node->enrolled_atoms[i].len == node->len); + + result = enroll_prepared_atom(&node->raw[i], backend, &node->enrolled_atoms[i]); + + } + + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_masked_build_id(GScanTokenNodeMasked *node, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours #1 */ + + result = true; + + for (i = 0; i < node->enrolled_count && result; i++) + result = build_atom_pattern_id(&node->enrolled_atoms[i], backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = octets partiels avec leur masque à interpréter. * +* len = quantité d'octets à interpréter. * +* start = point d'analyse à respecter. * +* content = accès au contenu brut pour vérifications (optim.) * +* * +* Description : Détermine si un contenu d'intérêt est présent à une position.* +* * +* Retour : Bilan de l'analyse : true pour une correspondance. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool check_scan_token_node_masked_content(const masked_byte_t *bytes, size_t len, phys_t start, GBinContent *content) +{ + bool result; /* Bilan à retourner */ + vmpa2t pos; /* Position dans les données */ + const bin_t *ptr; /* Accès aux données brutes */ + size_t i; /* Boucle de parcours */ + + result = false; + + init_vmpa(&pos, start, VMPA_NO_VIRTUAL); + + ptr = g_binary_content_get_raw_access(content, &pos, len); + + for (i = 0; i < len; i++) + { + if ((ptr[i] & bytes[i].mask) != bytes[i].value) + break; + } + + result = (i == len); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_check_forward(const GScanTokenNodeMasked *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ +#ifndef NDEBUG + bool forced; /* Inclusion dans un scan ? */ +#endif + match_area_t **areas; /* Liste de zones à constituer */ + size_t *count; /* Taille de cette liste */ + bool copy; /* Besoin d'une copie ? */ + bool inverted; /* Inversion des bilans ? */ + size_t i; /* Boucle de parcours #1 */ + const tracked_scan_atom_t *atom; /* Atome correspondant */ + match_area_t *atoms; /* Localisations des bribes */ + bool first_round; /* Premier tour de traitement */ + match_area_t *area; /* Correspondance à valider */ + match_area_t *next; /* Correspondance suivante */ + phys_t start; /* Début potentiel de motif */ + bool status; /* Bilan d'une correspondance */ + phys_t after; /* Espace disposible après */ + phys_t min_end; /* Fin la plus proche possible */ + phys_t max_end; /* Fin la plus éloignée trouvée*/ + bool updated; /* Existence de correspondance */ + size_t rcount; /* Quantité de bornes présentes*/ + const node_offset_range_t *ranges; /* Bornes d'espace à parcourir */ + size_t r; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t p; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t updated_edge; /* Nouvelle bordure de motif */ + match_area_t *new_area; /* Copie de correspondance */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + /** + * Si l'analyse arrive à un ou plusieurs octets masqués, soit il s'agit du + * premier noeud, et la génération d'atomes a été forcée pour obtenir des + * points de départ, soit des correspondances ont été établies au préalable, + * et il ne doit alors pas y avoir d'atome mis en place (si l'initialisation + * ne provient pas d'une mise en place artificielle par une inversion NOT). + */ +#ifndef NDEBUG + forced = (g_scan_token_node_get_flags(G_SCAN_TOKEN_NODE(node)) & STNF_MAIN); + assert((!params->initialized && forced) || (params->initialized && (!forced || cflags & TNCF_KEEP_DISCARDED))); +#endif + + if (!params->initialized) + { + /* Destinations établies une fois pour toutes */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + areas = ¶ms->kept_areas; + count = ¶ms->kept_count; + + copy = false; + inverted = true; + + } + + else if (cflags & TNCF_CREATE_NEW) + { + areas = ¶ms->created_areas; + count = ¶ms->created_count; + + copy = true; + inverted = false; + + } + + else + { + assert(cflags & TNCF_UPDATE_IN_PLACE); + + areas = ¶ms->main_areas; + count = ¶ms->main_count; + + copy = false; + inverted = false; + + } + + /* Parcours des combinaisons enregistrées */ + + for (i = 0; i < node->enrolled_count; i++) + { + atom = &node->enrolled_atoms[i]; + + atoms = g_scan_context_get_atom_matches(params->context, atom->pid); + + first_round = (*count == 0); + + if (atom->fast_check) + { + /** + * Toutes les correspondances sont validées d'office car le motif identifié + * correspondant au motif complet. + */ + + if (!inverted) + { + for_each_match_area(area, atoms) + { + /** + * La modification de la zone d'origine est possible dans tous les cas + * car cette zone a été allouée de façon dédiée à un type de correspondances + * et ne sera pas réutilisée comme autre source de correspondance ailleurs. + */ + + assert(area->end >= atom->len); + + area->start = area->end - atom->len; + + (*count)++; + + } + + } + + else + atoms = NULL; + + } + + else + { + for_each_match_area_safe(area, &atoms, next) + { + start = area->end - atom->len - atom->pos; + + status = check_scan_token_node_masked_content(node->bytes, node->len, + start, params->content); + + if (status) + { + /** + * La modification de la zone d'origine est possible dans tous les cas + * car cette zone a été allouée de façon dédiée à un type de correspondances + * et ne sera pas réutilisée comme autre source de correspondance ailleurs. + */ + + if (!inverted) + { + area->start = start; + area->end += atom->rem; + + (*count)++; + + } + else + del_match_area(area, &atoms); + + } + + else + { + /** + * Les principes de modifications restent valables, même inversés. + */ + if (inverted) + { + area->start = start; + area->end += atom->rem; + + (*count)++; + + } + else + del_match_area(area, &atoms); + + } + + } + + + } + + /* Mise à jour de la liste */ + + if (atoms != NULL) + { + if (first_round) + *areas = atoms; + + else + merge_match_areas(areas, &atoms); + + } + + } + + } + + /** + * Poursuite des traitements sur des correspondances déjà amorcées, impliquant + * des comparaisons entières de motifs. + */ + else + { + if (0x0) printf(" LIST : %p (sz = %zu)\n", params->main_areas, params->main_count); + + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + assert(area->end <= params->content_end); + + after = params->content_end - area->end; + + if (0x0) printf("---------- iter @ %u -> %u\n", (unsigned int)area->start, (unsigned int)area->end); + + /** + * S'il s'avère qu'il existe de multiples correspondances dans l'espace + * analysé, c'est la prise en compte d'une éventuelle avarice quant aux + * distances consommées qui va sélectionner la position d'une bribe de + * correspondance retenue. + * + * Par exemple, deux correspondances '?1 ?1 [1-3] ?2 ?2' peuvent être + * valides pour un même contenu : + * + * aa.bbb -> correspondance 'aa.bb' + * ^ + * + * aa.bbb -> correspondance 'aa..bb' + * ^ + */ + + min_end = params->content_end; + max_end = params->content_start; + + updated = false; + + /* Souplesse dans les positions ? */ + if (offsets_exist(¶ms->offset)) + { + ranges = get_node_search_offset_ranges_2(¶ms->offset, &rcount); + + for (r = 0; r < rcount; r++) + { + assert(ranges[r].has_max); + assert((ranges[r].max - ranges[r].min) <= MAX_RANGE_FOR_MANUAL_CHECK); + + for (p = ranges[r].min; p <= ranges[r].max; p++) + { + /** + * Si la fin d'une correspondance potentielle est trop près de + * la fin du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if ((p + node->len) > after) + break; + + status = check_scan_token_node_masked_content(node->bytes, node->len, + area->end + p, params->content); + + if (status) + { + updated_edge = area->end + p + node->len; + + if (updated_edge < min_end) + min_end = updated_edge; + + if (updated_edge > max_end) + max_end = updated_edge; + + updated = true; + + } + + } + + } + + } + + /* Position immédiatement attendue */ + else + { + /** + * Si la fin d'une correspondance potentielle est trop près de + * la fin du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if (node->len <= after) + { + status = check_scan_token_node_masked_content(node->bytes, node->len, + area->end, params->content); + + if (status) + { + updated_edge = area->end + node->len; + + min_end = updated_edge; + max_end = updated_edge; + + updated = true; + + } + + } + + } + + if (updated) + { + /** + * Si seuls les rejets sont d'intérêt, les correspondances établies + * ne se voient pas mises à jours ni retirées. + */ + + if ((cflags & TNCF_KEEP_DISCARDED) == 0) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + area->end = (1 /* greedy */ ? min_end : max_end); + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->end = (1 /* greedy */ ? min_end : max_end); + + add_tail_match_area(new_area, ¶ms->created_areas); + params->created_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + else + { + /** + * Si la liste principale doit être mise à jour... + */ + + if (cflags & TNCF_UPDATE_IN_PLACE) + { + del_match_area(area, ¶ms->main_areas); + assert(params->main_count > 0); + params->main_count--; + } + + /** + * Au cas où le rejet est d'intérêt, l'absence de correspondance + * est conservée dans une liste dédiée. + */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + { + add_tail_match_area(area, ¶ms->kept_areas); + params->kept_count++; + } + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->end = (1 /* greedy */ ? min_end : max_end); + + add_tail_match_area(new_area, ¶ms->kept_areas); + params->kept_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + } + + } + + params->initialized = true; + + disable_all_ranges_in_node_search_offset(¶ms->offset); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_masked_check_backward(const GScanTokenNodeMasked *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ +#ifndef NDEBUG + bool forced; /* Inclusion dans un scan ? */ +#endif + + + + bool status; /* Bilan d'une correspondance */ + + + match_area_t *area; /* Correspondance à valider */ + match_area_t *next; /* Correspondance suivante */ + phys_t before; /* Espace disposible avant */ + phys_t min_start; /* Début le plus proche trouvé */ + phys_t max_start; /* Début le plus distant trouvé*/ + bool updated; /* Existence de correspondance */ + size_t rcount; /* Quantité de bornes présentes*/ + const node_offset_range_t *ranges; /* Bornes d'espace à parcourir */ + size_t r; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t p; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t updated_edge; /* Nouvelle bordure de motif */ + match_area_t *new_area; /* Copie de correspondance */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + /** + * En lecture à rebourd, au moins un noeud a été solicité pour analyse (lors + * du sens de lecteur normal). Donc l'initialisation a déjà dû avoir lieu. + */ + assert(params->initialized); + + /** + * Si les recherches associées au noeud ont été forcées, alors les traitements + * liés ont déjà été effectués, et l'appel de cette fonction aurait dû être sauté. + */ +#ifndef NDEBUG + forced = (g_scan_token_node_get_flags(G_SCAN_TOKEN_NODE(node)) & STNF_MAIN); + assert(!forced); +#endif + + + + + /** + * ............. + */ + if (0) + { + + + ; + + + + } + + /** + * Poursuite des traitements sur des correspondances déjà amorcées, impliquant + * des comparaisons entières de motifs. + */ + else + { + if (0x0) printf(" LIST : %p (sz = %zu)\n", params->main_areas, params->main_count); + + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + assert(params->content_start <= area->start); + + before = area->start - params->content_start; + + if (0x0) printf("---------- iter @ %u -> %u\n", (unsigned int)area->start, (unsigned int)area->end); + + /** + * Il ne peut y avoir qu'une seule séquence d'octets à un même + * emplacement. En revanche, des modificateurs peuvent construire + * possédant une même base, mais offrant des suffixes différents + * (par exemple, un marqueur nul UTF-16 final en complément). + * + * L'ensemble des combinaisons produites doit ainsi être exploré. + */ + + min_start = params->content_start; + max_start = params->content_end; + + updated = false; + + /* Souplesse dans les positions ? */ + if (offsets_exist(¶ms->offset)) + { + ranges = get_node_search_offset_ranges_2(¶ms->offset, &rcount); + + for (r = 0; r < rcount; r++) + { + assert(ranges[r].has_max); + assert((ranges[r].max - ranges[r].min) <= MAX_RANGE_FOR_MANUAL_CHECK); + + for (p = ranges[r].min; p <= ranges[r].max; p++) + { + /** + * Si la fin d'une correspondance potentielle est trop près de + * la fin du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if ((p + node->len) > before) + break; + + status = check_scan_token_node_masked_content(node->bytes, node->len, + area->start - node->len - p, + params->content); + + if (status) + { + updated_edge = area->start - node->len - p; + + if (updated_edge > min_start) + min_start = updated_edge; + + if (updated_edge < max_start) + max_start = updated_edge; + + updated = true; + + } + + } + + } + + } + + /* Position immédiatement attendue */ + else + { + /** + * Si la fin d'une correspondance potentielle est trop près du + * début du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if (node->len <= before) + { + status = check_scan_token_node_masked_content(node->bytes, node->len, + area->start - node->len, + params->content); + + if (status) + { + updated_edge = area->start - node->len; + + if (updated_edge > min_start) + min_start = updated_edge; + + if (updated_edge < max_start) + max_start = updated_edge; + + updated = true; + + } + + } + + } + + if (updated) + { + /** + * Si seuls les rejets sont d'intérêt, les correspondances établies + * ne se voient pas mises à jours ni retirées. + */ + + if ((cflags & TNCF_KEEP_DISCARDED) == 0) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + area->start = (1 /* greedy */ ? min_start : max_start); + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->start = (1 /* greedy */ ? min_start : max_start); + + add_tail_match_area(new_area, ¶ms->created_areas); + params->created_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + else + { + /** + * Si la liste principale doit être mise à jour... + */ + + if (cflags & TNCF_UPDATE_IN_PLACE) + { + del_match_area(area, ¶ms->main_areas); + assert(params->main_count > 0); + params->main_count--; + } + + /** + * Au cas où le rejet est d'intérêt, l'absence de correspondance + * est conservée dans une liste dédiée. + */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + { + add_tail_match_area(area, ¶ms->kept_areas); + params->kept_count++; + } + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->start = (1 /* greedy */ ? min_start : max_start); + + add_tail_match_area(new_area, ¶ms->kept_areas); + params->kept_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + } + + } + + disable_all_ranges_in_node_search_offset(¶ms->offset); + +} diff --git a/src/analysis/scan/patterns/tokens/nodes/masked.h b/src/analysis/scan/patterns/tokens/nodes/masked.h new file mode 100644 index 0000000..04a05bc --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/masked.h @@ -0,0 +1,63 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * masked.h - prototypes pour la gestion d'une recherche de motif partielle + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_MASKED_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_MASKED_H + + +#include <glib-object.h> + + +#include "../atom.h" +#include "../node.h" +#include "../../../../../arch/archbase.h" + + + +#define G_TYPE_SCAN_TOKEN_NODE_MASKED g_scan_token_node_masked_get_type() +#define G_SCAN_TOKEN_NODE_MASKED(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE_MASKED, GScanTokenNodeMasked)) +#define G_IS_SCAN_TOKEN_NODE_MASKED(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE_MASKED)) +#define G_SCAN_TOKEN_NODE_MASKED_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE_MASKED, GScanTokenNodeMaskedClass)) +#define G_IS_SCAN_TOKEN_NODE_MASKED_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE_MASKED)) +#define G_SCAN_TOKEN_NODE_MASKED_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE_MASKED, GScanTokenNodeMaskedClass)) + + +/* Bribe de motif partielle pour recherches (instance) */ +typedef struct _GScanTokenNodeMasked GScanTokenNodeMasked; + +/* Bribe de motif partielle pour recherches (classe) */ +typedef struct _GScanTokenNodeMaskedClass GScanTokenNodeMaskedClass; + + +/* Indique le type défini pour un noeud représentant une bribe partielle à retrouver. */ +GType g_scan_token_node_masked_get_type(void); + +/* Construit une bribe de motif partielle. */ +GScanTokenNode *g_scan_token_node_masked_new(const masked_byte_t *); + +/* Enregistre la valeur d'octet à rechercher avec son masque. */ +void g_scan_token_node_masked_add(GScanTokenNodeMasked *, const masked_byte_t *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_MASKED_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/not-int.h b/src/analysis/scan/patterns/tokens/nodes/not-int.h new file mode 100644 index 0000000..5f92afd --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/not-int.h @@ -0,0 +1,57 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * not-int.h - prototypes internes pour l'inversion de résultats de correspondances établis + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_NOT_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_NOT_INT_H + + +#include "not.h" + + +#include "../node-int.h" + + + +/* Inversion de résultats de correspondances établis (instance) */ +struct _GScanTokenNodeNot +{ + GScanTokenNode parent; /* A laisser en premier */ + + GScanTokenNode *child; /* Sous-noeud à considérer */ + +}; + +/* Inversion de résultats de correspondances établis (classe) */ +struct _GScanTokenNodeNotClass +{ + GScanTokenNodeClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une inversion de résultats de correspondances. */ +bool g_scan_token_node_not_create(GScanTokenNodeNot *, GScanTokenNode *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_NOT_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/not.c b/src/analysis/scan/patterns/tokens/nodes/not.c new file mode 100644 index 0000000..81fce28 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/not.c @@ -0,0 +1,416 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * not.c - inversion de résultats de correspondances établis + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "not.h" + + +#include <assert.h> + + +#include "not-int.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des inversions de correspondances. */ +static void g_scan_token_node_not_class_init(GScanTokenNodeNotClass *); + +/* Initialise une instance d'inversion de correspondances. */ +static void g_scan_token_node_not_init(GScanTokenNodeNot *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_not_dispose(GScanTokenNodeNot *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_not_finalize(GScanTokenNodeNot *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Prend acte d'une nouvelle propriété pour le noeud. */ +static void g_scan_token_node_not_apply_flags(GScanTokenNodeNot *, ScanTokenNodeFlags); + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +static void g_scan_token_node_not_visit(GScanTokenNodeNot *, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +static bool g_scan_token_node_not_enroll(GScanTokenNodeNot *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +static bool g_scan_token_node_not_build_id(GScanTokenNodeNot *, GEngineBackend *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_not_check_forward(const GScanTokenNodeNot *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_not_check_backward(const GScanTokenNodeNot *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une inversion des résultats de correspondances. */ +G_DEFINE_TYPE(GScanTokenNodeNot, g_scan_token_node_not, G_TYPE_SCAN_TOKEN_NODE); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des inversions de correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_class_init(GScanTokenNodeNotClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenNodeClass *node; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_not_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_not_finalize; + + node = G_SCAN_TOKEN_NODE_CLASS(klass); + + node->apply = (apply_scan_token_node_flags_fc)g_scan_token_node_not_apply_flags; + node->visit = (visit_scan_token_node_fc)g_scan_token_node_not_visit; + node->enroll = (enroll_scan_token_node_fc)g_scan_token_node_not_enroll; + node->build_id = (build_scan_token_node_id_fc)g_scan_token_node_not_build_id; + node->check_forward = (check_scan_token_node_fc)g_scan_token_node_not_check_forward; + node->check_backward = (check_scan_token_node_fc)g_scan_token_node_not_check_backward; + +} + + +/****************************************************************************** +* * +* Paramètres : not = instance à initialiser. * +* * +* Description : Initialise une instance d'inversion de correspondances. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_init(GScanTokenNodeNot *not) +{ + not->child = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : not = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_dispose(GScanTokenNodeNot *not) +{ + g_clear_object(¬->child); + + G_OBJECT_CLASS(g_scan_token_node_not_parent_class)->dispose(G_OBJECT(not)); + +} + + +/****************************************************************************** +* * +* Paramètres : not = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_finalize(GScanTokenNodeNot *not) +{ + G_OBJECT_CLASS(g_scan_token_node_not_parent_class)->finalize(G_OBJECT(not)); + +} + + +/****************************************************************************** +* * +* Paramètres : child = noeud dont les résultats sont à écarter. * +* * +* Description : Construit une inversion de résultats de correspondances. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_not_new(GScanTokenNode *child) +{ + GScanTokenNode *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_NODE_NOT, NULL); + + if (!g_scan_token_node_not_create(G_SCAN_TOKEN_NODE_NOT(result), child)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : not = encadrement d'inversion à initialiser pleinement. * +* child = noeud dont les résultats sont à écarter. * +* * +* Description : Met en place une inversion de résultats de correspondances. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_not_create(GScanTokenNodeNot *not, GScanTokenNode *child) +{ + bool result; /* Bilan à retourner */ + + result = true; + + not->child = child; + g_object_ref(G_OBJECT(child)); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à mettre à jour. * +* flags = propriétés particulières à associer au noeud. * +* * +* Description : Prend acte d'une nouvelle propriété pour le noeud. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_apply_flags(GScanTokenNodeNot *node, ScanTokenNodeFlags flags) +{ + g_scan_token_node_set_flags(node->child, flags); + +} + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à effectuer. * +* points = points capitaux de l'arborescence. [OUT] * +* * +* Description : Parcourt une arborescence de noeuds et y relève des éléments.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_visit(GScanTokenNodeNot *node, scan_tree_points_t *points) +{ + g_scan_token_node_visit(node->child, points); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_not_enroll(GScanTokenNodeNot *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + + result = _g_scan_token_node_enroll(node->child, backend, maxsize, slow); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_not_build_id(GScanTokenNodeNot *node, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + + result = g_scan_token_node_build_id(node->child, backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_check_forward(const GScanTokenNodeNot *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + +#if 0 + + + bool initialized; /* Initialisation du suivi ? */ + phys_t i; /* Boucle de parcours */ + + + /* + + ????????????????????????? + + + if (*skip) + return; + */ + + + + initialized = are_pending_matches_initialized(matches); + + + //printf("TOTO......(init done? %d)\n", initialized); + + + + if (!initialized) + { + for (i = matches->content_start; i < matches->content_end; i++) + add_pending_match(matches, i, 0); + + set_pending_matches_initialized(matches); + + } + + _g_scan_token_node_check_forward(node->child, context, content, matches, offset, !not, skip); + + +#endif + + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_not_check_backward(const GScanTokenNodeNot *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + + + + if (*skip) + return; + + + + printf("TODO\n"); + assert(0); + + + +} diff --git a/src/analysis/scan/patterns/tokens/nodes/not.h b/src/analysis/scan/patterns/tokens/nodes/not.h new file mode 100644 index 0000000..58630e8 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/not.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * not.h - prototypes pour l'inversion de résultats de correspondances établis + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_NOT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_NOT_H + + +#include <glib-object.h> + + +#include "../node.h" +#include "../../../../../arch/archbase.h" + + + +#define G_TYPE_SCAN_TOKEN_NODE_NOT g_scan_token_node_not_get_type() +#define G_SCAN_TOKEN_NODE_NOT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE_NOT, GScanTokenNodeNot)) +#define G_IS_SCAN_TOKEN_NODE_NOT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE_NOT)) +#define G_SCAN_TOKEN_NODE_NOT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE_NOT, GScanTokenNodeNotClass)) +#define G_IS_SCAN_TOKEN_NODE_NOT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE_NOT)) +#define G_SCAN_TOKEN_NODE_NOT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE_NOT, GScanTokenNodeNotClass)) + + +/* Inversion de résultats de correspondances établis (instance) */ +typedef struct _GScanTokenNodeNot GScanTokenNodeNot; + +/* Inversion de résultats de correspondances établis (classe) */ +typedef struct _GScanTokenNodeNotClass GScanTokenNodeNotClass; + + +/* Indique le type défini pour une inversion des résultats de correspondances. */ +GType g_scan_token_node_not_get_type(void); + +/* Construit une inversion de résultats de correspondances. */ +GScanTokenNode *g_scan_token_node_not_new(GScanTokenNode *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_NOT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/plain-int.h b/src/analysis/scan/patterns/tokens/nodes/plain-int.h new file mode 100644 index 0000000..2077c6f --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/plain-int.h @@ -0,0 +1,64 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain-int.h - prototypes internes pour la gestion d'une recherche de motif textuel + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_PLAIN_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_PLAIN_INT_H + + +#include "plain.h" + + +#include "../atom.h" +#include "../node-int.h" + + + +/* Bribe de motif textuelle pour recherches (instance) */ +struct _GScanTokenNodePlain +{ + GScanTokenNode parent; /* A laisser en premier */ + + sized_binary_t orig; /* Motif d'origine avant modifs*/ + GScanTokenModifier *modifier; /* Transformateur pour le motif*/ + ScanPlainNodeFlags flags; /* Fanions associés au motif */ + + sized_binary_t *raw; /* Liste de motifs à couvrir */ + tracked_scan_atom_t *atoms; /* Atomes correspondants */ + size_t count; /* Taille de cette liste */ + +}; + +/* Bribe de motif textuelle pour recherches (instance) */ +struct _GScanTokenNodePlainClass +{ + GScanTokenNodeClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un noeud représentant un motif textuel. */ +bool g_scan_token_node_plain_create(GScanTokenNodePlain *, const sized_binary_t *, GScanTokenModifier *, ScanPlainNodeFlags); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_PLAIN_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/plain.c b/src/analysis/scan/patterns/tokens/nodes/plain.c new file mode 100644 index 0000000..5dd45df --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/plain.c @@ -0,0 +1,1377 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain.c - gestion d'une recherche de motif textuel + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "plain.h" + + +#include <assert.h> + + +#include "plain-int.h" +#include "../../../../../common/extstr.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des noeuds pour motif textuel. */ +static void g_scan_token_node_plain_class_init(GScanTokenNodePlainClass *); + +/* Initialise une instance de noeud pour motif textuel. */ +static void g_scan_token_node_plain_init(GScanTokenNodePlain *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_plain_dispose(GScanTokenNodePlain *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_plain_finalize(GScanTokenNodePlain *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Communique l'intérêt d'un noeud au sein d'une analyse. */ +static float g_scan_token_node_plain_compute_weight_for_scan(const GScanTokenNodePlain *); + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +static void g_scan_token_node_plain_visit(GScanTokenNodePlain *, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +static bool g_scan_token_node_plain_enroll(GScanTokenNodePlain *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +static bool g_scan_token_node_plain_build_id(GScanTokenNodePlain *, GEngineBackend *); + +/* Détermine si un contenu d'intérêt est présent à une position. */ +static bool check_scan_token_node_plain_content(const sized_binary_t *, const tracked_scan_atom_t *, bool, phys_t, GBinContent *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_plain_check_forward(const GScanTokenNodePlain *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_plain_check_backward(const GScanTokenNodePlain *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour un noeud représentant une bribe de texte à retrouver. */ +G_DEFINE_TYPE(GScanTokenNodePlain, g_scan_token_node_plain, G_TYPE_SCAN_TOKEN_NODE); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des noeuds pour motif textuel. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_class_init(GScanTokenNodePlainClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenNodeClass *node; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_plain_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_plain_finalize; + + node = G_SCAN_TOKEN_NODE_CLASS(klass); + + node->compute_weight = (compute_scan_token_node_weight_fc)g_scan_token_node_plain_compute_weight_for_scan; + node->apply = (apply_scan_token_node_flags_fc)NULL; + node->visit = (visit_scan_token_node_fc)g_scan_token_node_plain_visit; + node->enroll = (enroll_scan_token_node_fc)g_scan_token_node_plain_enroll; + node->build_id = (build_scan_token_node_id_fc)g_scan_token_node_plain_build_id; + node->check_forward = (check_scan_token_node_fc)g_scan_token_node_plain_check_forward; + node->check_backward = (check_scan_token_node_fc)g_scan_token_node_plain_check_backward; + +} + + +/****************************************************************************** +* * +* Paramètres : plain = instance à initialiser. * +* * +* Description : Initialise une instance de noeud pour motif textuel. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_init(GScanTokenNodePlain *plain) +{ + init_szstr(&plain->orig); + plain->modifier = NULL; + plain->flags = SPNF_NONE; + + plain->raw = NULL; + plain->atoms = NULL; + plain->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : plain = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_dispose(GScanTokenNodePlain *plain) +{ + g_clear_object(&plain->modifier); + + G_OBJECT_CLASS(g_scan_token_node_plain_parent_class)->dispose(G_OBJECT(plain)); + +} + + +/****************************************************************************** +* * +* Paramètres : plain = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_finalize(GScanTokenNodePlain *plain) +{ + size_t i; /* Boucle de parcours */ + + exit_szstr(&plain->orig); + + for (i = 0; i < plain->count; i++) + exit_szstr(&plain->raw[i]); + + if (plain->raw != NULL) + free(plain->raw); + + if (plain->atoms != NULL) + free(plain->atoms); + + G_OBJECT_CLASS(g_scan_token_node_plain_parent_class)->finalize(G_OBJECT(plain)); + +} + + +/****************************************************************************** +* * +* Paramètres : text = texte brut à rechercher. * +* modifier = transformateur éventuel à solliciter. * +* flags = particularités à prendre en considération. * +* * +* Description : Construit un noeud représentant un motif textuel. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_plain_new(const sized_binary_t *text, GScanTokenModifier *modifier, ScanPlainNodeFlags flags) +{ + GScanTokenNode *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_NODE_PLAIN, NULL); + + if (!g_scan_token_node_plain_create(G_SCAN_TOKEN_NODE_PLAIN(result), text, modifier, flags)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : plain = encadrement de motif à initialiser pleinement. * +* text = texte brut à rechercher. * +* modifier = transformateur éventuel à solliciter. * +* flags = particularités à prendre en considération. * +* * +* Description : Met en place un noeud représentant un motif textuel. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_plain_create(GScanTokenNodePlain *plain, const sized_binary_t *text, GScanTokenModifier *modifier, ScanPlainNodeFlags flags) +{ + bool result; /* Bilan à retourner */ + + result = true; + + szstrdup(&plain->orig, text); + + if (modifier != NULL) + { + plain->modifier = modifier; + g_object_ref(G_OBJECT(modifier)); + } + + plain->flags = flags; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : plain = noeud de motif textuel à consulter. * +* * +* Description : Indique les propriétés particulières d'un noeud de texte. * +* * +* Retour : Propriétés particulières associées au noeud. * +* * +* Remarques : - * +* * +******************************************************************************/ + +ScanPlainNodeFlags g_scan_token_node_plain_get_flags(const GScanTokenNodePlain *plain) +{ + ScanPlainNodeFlags result; /* Statut à retourner */ + + result = plain->flags; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à consulter. * +* index = indice de la combinaison de modificateurs ciblée. * +* * +* Description : Retrouve l'origine d'une correspondance à partir d'un indice.* +* * +* Retour : Version humainement lisible de la combinaison. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_token_node_plain_get_modifier_path(const GScanTokenNodePlain *node, size_t index) +{ + char *result; /* Combinaison à retourner */ + + if (node->modifier == NULL) + result = strdup("plain"); + + else + result = g_scan_token_modifier_get_path(node->modifier, (size_t []){ index }); + + return result; + + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à consulter. * +* * +* Description : Communique l'intérêt d'un noeud au sein d'une analyse. * +* * +* Retour : Poids de l'importance pour un départ de scan. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static float g_scan_token_node_plain_compute_weight_for_scan(const GScanTokenNodePlain *node) +{ + float result; /* Valeur à retourner */ + + result = node->orig.len; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à effectuer. * +* points = points capitaux de l'arborescence. [OUT] * +* * +* Description : Parcourt une arborescence de noeuds et y relève des éléments.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_visit(GScanTokenNodePlain *node, scan_tree_points_t *points) +{ + GScanTokenNode *candidate; /* Autre version du noeud */ + float node_weight; /* Poids du noeud courant */ + float other_weight; /* Poids de l'autre noeud */ + + if (points->first_plain == NULL) + points->first_plain = G_SCAN_TOKEN_NODE(node); + + else + { + candidate = G_SCAN_TOKEN_NODE(node); + + node_weight = g_scan_token_node_compute_weight_for_scan(candidate); + other_weight = g_scan_token_node_compute_weight_for_scan(points->first_plain); + + if (node_weight >= other_weight) + points->first_plain = candidate; + + } + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* context = contexte de l'analyse à mener. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_plain_enroll(GScanTokenNodePlain *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours #1 */ + tracked_scan_atom_t atom; /* Atome identifié */ + size_t letters; /* Nombre de lettres présentes */ + size_t k; /* Boucle de parcours #2 */ + size_t extra_count; /* Quantité pour l'exhaustivité*/ + sized_binary_t *extra; /* Couverture supplémntaire */ + size_t remaining; /* Quantité restant à traiter */ + + /* Génération d'une base de chaînes à couvrir */ + + if (node->modifier == NULL) + { + node->raw = malloc(sizeof(sized_binary_t)); + node->count = 1; + + szstrdup(&node->raw[0], &node->orig); + + result = true; + + } + else + result = g_scan_token_modifier_transform(node->modifier, &node->orig, 1, &node->raw, &node->count); + + if (!result) + goto exit; + + /* Préparation pour la mémorisation des atomes */ + + node->atoms = malloc(node->count * sizeof(tracked_scan_atom_t)); + + /* Validation du besoin effectif dans les cas extrèmes */ + + + + // TODO : if (orig.len < ...) + + + + /* Recherche des atomes */ + + for (i = 0; i < node->count; i++) + { + if (node->flags & SPNF_CASE_INSENSITIVE) + { + find_best_atom(&node->raw[i], maxsize, &atom, &letters); + + if (letters == 0) + node->atoms[i] = atom; + + /* Insertion des nouvelles combinaisons pour couvrir toutes les casses */ + else + { + /* extra_count = 2^letters */ + for (k = 1, extra_count = 2; k < letters; k++, extra_count *= 2) + ; + + extra = make_atoms_case_insensitive(&node->raw[i], &atom, extra_count); + + remaining = node->count - i - 1; + + node->count += (extra_count - 1); + + node->raw = realloc(node->raw, node->count * sizeof(sized_binary_t)); + + memmove(&node->raw[i + extra_count], &node->raw[i + 1], remaining * sizeof(sized_binary_t)); + + for (k = 0; k < extra_count; k++) + node->raw[i + k] = extra[k]; + + free(extra); + + node->atoms = realloc(node->atoms, node->count * sizeof(tracked_scan_atom_t)); + + for (k = 0; k < extra_count; k++) + node->atoms[i + k] = atom; + + i += extra_count - 1; + + } + + } + + else + find_best_atom(&node->raw[i], maxsize, &node->atoms[i], &letters); + + } + + /* Enregistrements en masse */ + + for (i = 0; i < node->count && result; i++) + result = enroll_prepared_atom(&node->raw[i], backend, &node->atoms[i]); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_plain_build_id(GScanTokenNodePlain *node, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours #1 */ + + result = true; + + for (i = 0; i < node->count && result; i++) + result = build_atom_pattern_id(&node->atoms[i], backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : raw = contneu brut à retrouver idéalement. * +* atom = contenu brut représentatif ciblé. * +* nocase = marque un éventuel désintérêt pour la casse. * +* start = point d'analyse à respecter. * +* content = accès au contenu brut pour vérifications (optim.) * +* * +* Description : Détermine si un contenu d'intérêt est présent à une position.* +* * +* Retour : Bilan de l'analyse : true pour une correspondance. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool check_scan_token_node_plain_content(const sized_binary_t *raw, const tracked_scan_atom_t *atom, bool nocase, phys_t start, GBinContent *content) +{ + bool result; /* Bilan à retourner */ + vmpa2t pos; /* Position dans les données */ + const bin_t *ptr; /* Accès aux données brutes */ + int ret; /* Bilan d'une comparaison */ + + result = false; + + init_vmpa(&pos, start, VMPA_NO_VIRTUAL); + + /* Validation du motif intégral */ + + if (atom == NULL) + { + ptr = g_binary_content_get_raw_access(content, &pos, raw->len); + + /** + * Si la partion atomique recherchée est trouvée en début de contenu, + * le reste du motif de recherche va déborder. L'accès correspondant + * est donc refusé, et cette situation est prise en compte ici. + */ + if (ptr == NULL) goto done; + + if (nocase) + ret = memcasecmp(raw->data, ptr, raw->len); + else + ret = memcmp(raw->data, ptr, raw->len); + + result = (ret == 0); + + } + + /* Validation des extrémités */ + + else + { + /* Validation du contenu avant l'atome */ + + if (atom->pos > 0) + { + ptr = g_binary_content_get_raw_access(content, &pos, atom->pos); + + /** + * Si la partion atomique recherchée est trouvée en début de contenu, + * le reste du motif de recherche va déborder. L'accès correspondant + * est donc refusé, et cette situation est prise en compte ici. + */ + if (ptr == NULL) goto done; + + if (nocase) + ret = memcasecmp(raw->data, ptr, atom->pos); + else + ret = memcmp(raw->data, ptr, atom->pos); + + if (ret != 0) goto done; + + } + + /* Validation du contenu après l'atome */ + + if (atom->rem > 0) + { + advance_vmpa(&pos, atom->len); + + ptr = g_binary_content_get_raw_access(content, &pos, atom->rem); + + /** + * Si la partion atomique recherchée est trouvée en fin de contenu, + * le reste du motif de recherche va déborder. L'accès correspondant + * est donc refusé, et cette situation est prise en compte ici. + */ + if (ptr == NULL) goto done; + + if (nocase) + ret = memcasecmp(raw->data + atom->pos + atom->len, ptr, atom->rem); + else + ret = memcmp(raw->data + atom->pos + atom->len, ptr, atom->rem); + + if (ret != 0) goto done; + + } + + result = true; + + } + + done: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_check_forward(const GScanTokenNodePlain *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + bool track_path; /* Conservation du chemin */ + bool nocase; /* Pas d'intérêt pour la casse */ + match_area_t **areas; /* Liste de zones à constituer */ + size_t *count; /* Taille de cette liste */ + bool copy; /* Besoin d'une copie ? */ + bool inverted; /* Inversion des bilans ? */ + size_t i; /* Boucle de parcours #1 */ + const tracked_scan_atom_t *atom; /* Atome correspondant */ + match_area_t *atoms; /* Localisations des bribes */ + bool first_round; /* Premier tour de traitement */ + match_area_t *area; /* Correspondance à valider */ + const sized_binary_t *raw; /* Données brutes d'origine */ + match_area_t *next; /* Correspondance suivante */ + phys_t start; /* Début potentiel de motif */ + bool status; /* Bilan d'une correspondance */ + phys_t after; /* Espace disposible après */ + phys_t min_end; /* Fin la plus proche possible */ + phys_t max_end; /* Fin la plus éloignée trouvée*/ + bool updated; /* Existence de correspondance */ + size_t rcount; /* Quantité de bornes présentes*/ + const node_offset_range_t *ranges; /* Bornes d'espace à parcourir */ + size_t r; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t p; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t updated_edge; /* Nouvelle bordure de motif */ + match_area_t *new_area; /* Copie de correspondance */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + track_path = (G_SCAN_TOKEN_NODE(node)->flags & STNF_MAIN); + + nocase = (node->flags & SPNF_CASE_INSENSITIVE); + + /** + * Création de premières marques de correspondances. + */ + if (!params->initialized) + { + /* Destinations établies une fois pour toutes */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + areas = ¶ms->kept_areas; + count = ¶ms->kept_count; + + copy = false; + inverted = true; + + } + + else if (cflags & TNCF_CREATE_NEW) + { + areas = ¶ms->created_areas; + count = ¶ms->created_count; + + copy = true; + inverted = false; + + } + + else + { + assert(cflags & TNCF_UPDATE_IN_PLACE); + + areas = ¶ms->main_areas; + count = ¶ms->main_count; + + copy = false; + inverted = false; + + } + + /* Parcours des combinaisons enregistrées */ + + for (i = 0; i < node->count; i++) + { + atom = &node->atoms[i]; + + atoms = g_scan_context_get_atom_matches(params->context, atom->pid); + + first_round = (*count == 0); + + if (atom->fast_check) + { + /** + * Toutes les correspondances sont validées d'office car le motif identifié + * correspondant au motif complet. + */ + + if (!inverted) + { + for_each_match_area(area, atoms) + { + /** + * La modification de la zone d'origine est possible dans tous les cas + * car cette zone a été allouée de façon dédiée à un type de correspondances + * et ne sera pas réutilisée comme autre source de correspondance ailleurs. + */ + + assert(area->end >= atom->len); + + area->start = area->end - atom->len; + + (*count)++; + + } + + } + + else + atoms = NULL; + + } + + else + { + raw = &node->raw[i]; + + for_each_match_area_safe(area, &atoms, next) + { + start = area->end - atom->len - atom->pos; + + status = check_scan_token_node_plain_content(raw, atom, nocase, start, params->content); + + if (status) + { + /** + * La modification de la zone d'origine est possible dans tous les cas + * car cette zone a été allouée de façon dédiée à un type de correspondances + * et ne sera pas réutilisée comme autre source de correspondance ailleurs. + */ + + if (!inverted) + { + area->start = start; + area->end += atom->rem; + + (*count)++; + + } + else + del_match_area(area, &atoms); + + } + + else + { + /** + * Les principes de modifications restent valables, même inversés. + */ + if (inverted) + { + area->start = start; + area->end += atom->rem; + + (*count)++; + + } + else + del_match_area(area, &atoms); + + } + + } + + + } + + /* Mise à jour de la liste */ + + if (atoms != NULL) + { + if (first_round) + *areas = atoms; + + else + merge_match_areas(areas, &atoms); + + } + + } + + } + + /** + * Poursuite des traitements sur des correspondances déjà amorcées, impliquant + * des comparaisons entières de motifs. + */ + else + { + if (0x0) printf(" LIST : %p (sz = %zu)\n", params->main_areas, params->main_count); + + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + assert(area->end <= params->content_end); + + after = params->content_end - area->end; + + if (0x0) printf("---------- iter @ %u -> %u\n", (unsigned int)area->start, (unsigned int)area->end); + + /** + * Il ne peut y avoir qu'une seule séquence d'octets à un même + * emplacement. En revanche, des modificateurs peuvent construire + * possédant une même base, mais offrant des suffixes différents + * (par exemple, un marqueur nul UTF-16 final en complément). + * + * L'ensemble des combinaisons produites doit ainsi être exploré. + */ + + /** + * Par ailleurs, même si une base de couples uniques est assurée, + * la constitution d'un ensemble de noeuds peut amener une redondance + * dans les emplacements de correspondances ; ces doublons éventuels + * sont alors filtrés par un appel à sort_match_areas_no_dup(). + * + * Par exemple, pour la séquence d'octets analysés suivante : + * + * aaa....bbb + * + * La définition { (61 61 | 61 61 61) [4-5] 62 62 62 } peut établir + * les correspondances suivantes : + * + * aa.....bbb -> couple pending[x] (0;2) puis (0;10) + * ^ + * aa....bbb -> couple pending[y] (1;3) puis (1;10) + * ^ + * aaa....bbb -> couple pending[z] (0;3) puis (0;10) + * ^ + * + * Par ailleurs, une même base de départ peut conduire à plusieurs + * zones de correspondances. + * + * Par exemple, pour la séquence d'octets analysés suivante : + * + * aa..bb..bb + * + * La définition { 61 61 [2-6] 62 62 } peut établir + * les correspondances suivantes : + * + * aa..bb..bb -> couple pending[x] (0;2) puis (0;6) + * ^ + * aa..bb..bb -> couple pending[x] (0;2) puis (0;10) + * ^ + */ + + /** + * Dans la première situation, c'est la bribe 62 62 62 qui fait l'objet + * d'une recherche de motifs. Les autres bribes sont recherchées + * manuellement ici, car l'espace de séparation est léger (inférieur à + * MAX_RANGE_FOR_MANUAL_CHECK). + * + * La seconde situation bénéficie de recherches automatisées pour + * l'ensemble des motifs, du fait d'une valeur de séparation plus + * importante. + * + * Dans les deux cas, l'espace de séparation est entièrement considéré. + * La sélection de la correspondance à retour s'établit selon un + * paramètre de configuation : doit-on être avare sur les distances + * consommées ou non ? + */ + + min_end = params->content_end; + max_end = params->content_start; + + updated = false; + + for (i = 0; i < node->count; i++) + { + raw = &node->raw[i]; + + /* Souplesse dans les positions ? */ + if (offsets_exist(¶ms->offset)) + { + ranges = get_node_search_offset_ranges_2(¶ms->offset, &rcount); + + for (r = 0; r < rcount; r++) + { + assert(ranges[r].has_max); + assert((ranges[r].max - ranges[r].min) <= MAX_RANGE_FOR_MANUAL_CHECK); + + for (p = ranges[r].min; p <= ranges[r].max; p++) + { + /** + * Si la fin d'une correspondance potentielle est trop près de + * la fin du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if ((p + raw->len) > after) + break; + + status = check_scan_token_node_plain_content(raw, NULL, nocase, + area->end + p, params->content); + + if (status) + { + updated_edge = area->end + p + raw->len; + + if (updated_edge < min_end) + min_end = updated_edge; + + if (updated_edge > max_end) + max_end = updated_edge; + + updated = true; + + } + + } + + } + + } + + /* Position immédiatement attendue */ + else + { + /** + * Si la fin d'une correspondance potentielle est trop près de + * la fin du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if (raw->len > after) + continue; + + status = check_scan_token_node_plain_content(raw, NULL, nocase, area->end, params->content); + + if (status) + { + updated_edge = area->end + raw->len; + + if (updated_edge < min_end) + min_end = updated_edge; + + if (updated_edge > max_end) + max_end = updated_edge; + + updated = true; + + } + + } + + } + + if (updated) + { + /** + * Si seuls les rejets sont d'intérêt, les correspondances établies + * ne se voient pas mises à jours ni retirées. + */ + + if ((cflags & TNCF_KEEP_DISCARDED) == 0) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + area->end = (1 /* greedy */ ? min_end : max_end); + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->end = (1 /* greedy */ ? min_end : max_end); + + add_tail_match_area(new_area, ¶ms->created_areas); + params->created_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + else + { + /** + * Si la liste principale doit être mise à jour... + */ + + if (cflags & TNCF_UPDATE_IN_PLACE) + { + del_match_area(area, ¶ms->main_areas); + assert(params->main_count > 0); + params->main_count--; + } + + /** + * Au cas où le rejet est d'intérêt, l'absence de correspondance + * est conservée dans une liste dédiée. + */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + { + add_tail_match_area(area, ¶ms->kept_areas); + params->kept_count++; + } + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->end = (1 /* greedy */ ? min_end : max_end); + + add_tail_match_area(new_area, ¶ms->kept_areas); + params->kept_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + } + + } + + params->initialized = true; + + disable_all_ranges_in_node_search_offset(¶ms->offset); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_plain_check_backward(const GScanTokenNodePlain *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + + + + + + bool track_path; /* Conservation du chemin */ + bool nocase; /* Pas d'intérêt pour la casse */ + + + + + size_t i; /* Boucle de parcours #1 */ + + + const sized_binary_t *raw; /* Données brutes d'origine */ + + + bool status; /* Bilan d'une correspondance */ + + + + + + match_area_t *area; /* Correspondance à valider */ + match_area_t *next; /* Correspondance suivante */ + phys_t before; /* Espace disposible avant */ + phys_t min_start; /* Début le plus proche trouvé */ + phys_t max_start; /* Début le plus distant trouvé*/ + bool updated; /* Existence de correspondance */ + size_t rcount; /* Quantité de bornes présentes*/ + const node_offset_range_t *ranges; /* Bornes d'espace à parcourir */ + size_t r; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t p; /* Boucle de parcours #xxxxxxxxxxxx*/ + phys_t updated_edge; /* Nouvelle bordure de motif */ + match_area_t *new_area; /* Copie de correspondance */ + + if (0x0) printf("=================== CHECK :: %s (skip? %d)\n", __FUNCTION__, *skip); + + if (*skip) + return; + + /** + * En lecture à rebourd, au moins un noeud a été solicité pour analyse (lors + * du sens de lecture normal). Donc l'initialisation a déjà dû avoir lieu. + */ + + assert(params->initialized); + + track_path = (G_SCAN_TOKEN_NODE(node)->flags & STNF_MAIN); + + nocase = (node->flags & SPNF_CASE_INSENSITIVE); + + + + /** + * ............. + */ + if (0) + { + + + ; + + + + } + + /** + * Poursuite des traitements sur des correspondances déjà amorcées, impliquant + * des comparaisons entières de motifs. + */ + else + { + if (0x0) printf(" LIST : %p (sz = %zu)\n", params->main_areas, params->main_count); + + for_each_match_area_safe(area, ¶ms->main_areas, next) + { + assert(params->content_start <= area->start); + + before = area->start - params->content_start; + + if (0x0) printf("---------- iter @ %u -> %u\n", (unsigned int)area->start, (unsigned int)area->end); + + /** + * Il ne peut y avoir qu'une seule séquence d'octets à un même + * emplacement. En revanche, des modificateurs peuvent construire + * possédant une même base, mais offrant des suffixes différents + * (par exemple, un marqueur nul UTF-16 final en complément). + * + * L'ensemble des combinaisons produites doit ainsi être exploré. + */ + + min_start = params->content_start; + max_start = params->content_end; + + updated = false; + + for (i = 0; i < node->count; i++) + { + raw = &node->raw[i]; + + /* Souplesse dans les positions ? */ + if (offsets_exist(¶ms->offset)) + { + ranges = get_node_search_offset_ranges_2(¶ms->offset, &rcount); + + for (r = 0; r < rcount; r++) + { + assert(ranges[r].has_max); + assert((ranges[r].max - ranges[r].min) <= MAX_RANGE_FOR_MANUAL_CHECK); + + for (p = ranges[r].min; p <= ranges[r].max; p++) + { + /** + * Si la fin d'une correspondance potentielle est trop près de + * la fin du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if ((p + raw->len) > before) + break; + + status = check_scan_token_node_plain_content(raw, NULL, nocase, + area->start - raw->len - p, + params->content); + + if (status) + { + updated_edge = area->start - raw->len - p; + + if (updated_edge > min_start) + min_start = updated_edge; + + if (updated_edge < max_start) + max_start = updated_edge; + + updated = true; + + } + + } + + } + + } + + /* Position immédiatement attendue */ + else + { + /** + * Si la fin d'une correspondance potentielle est trop près du + * début du contenu binaire et ne peut contenir le motif + * représenté, alors la corresponance est écartée sans appel. + */ + if (raw->len > before) + continue; + + status = check_scan_token_node_plain_content(raw, NULL, nocase, + area->start - raw->len, + params->content); + + if (status) + { + updated_edge = area->start - raw->len; + + if (updated_edge > min_start) + min_start = updated_edge; + + if (updated_edge < max_start) + max_start = updated_edge; + + updated = true; + + } + + } + + } + + if (updated) + { + /** + * Si seuls les rejets sont d'intérêt, les correspondances établies + * ne se voient pas mises à jours ni retirées. + */ + + if ((cflags & TNCF_KEEP_DISCARDED) == 0) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + area->start = (1 /* greedy */ ? min_start : max_start); + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->start = (1 /* greedy */ ? min_start : max_start); + + add_tail_match_area(new_area, ¶ms->created_areas); + params->created_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + else + { + /** + * Si la liste principale doit être mise à jour... + */ + + if (cflags & TNCF_UPDATE_IN_PLACE) + { + del_match_area(area, ¶ms->main_areas); + assert(params->main_count > 0); + params->main_count--; + } + + /** + * Au cas où le rejet est d'intérêt, l'absence de correspondance + * est conservée dans une liste dédiée. + */ + + if (cflags & TNCF_KEEP_DISCARDED) + { + if (cflags & TNCF_UPDATE_IN_PLACE) + { + add_tail_match_area(area, ¶ms->kept_areas); + params->kept_count++; + } + + else if (cflags & TNCF_CREATE_NEW) + { + new_area = g_umem_slice_alloc(params->allocator); + + *new_area = *area; + + new_area->start = (1 /* greedy */ ? min_start : max_start); + + add_tail_match_area(new_area, ¶ms->kept_areas); + params->kept_count++; + + } + +#ifndef NDEBUG + else + assert(false); +#endif + + } + + } + + } + + } + + disable_all_ranges_in_node_search_offset(¶ms->offset); + +} diff --git a/src/analysis/scan/patterns/tokens/nodes/plain.h b/src/analysis/scan/patterns/tokens/nodes/plain.h new file mode 100644 index 0000000..abf71de --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/plain.h @@ -0,0 +1,83 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain.h - prototypes pour la gestion d'une recherche de motif textuel + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_PLAIN_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_PLAIN_H + + +#include <glib-object.h> + + +#include "../node.h" +#include "../../modifier.h" +#include "../../../../../common/szstr.h" + + + +#define G_TYPE_SCAN_TOKEN_NODE_PLAIN g_scan_token_node_plain_get_type() +#define G_SCAN_TOKEN_NODE_PLAIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE_PLAIN, GScanTokenNodePlain)) +#define G_IS_SCAN_TOKEN_NODE_PLAIN(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE_PLAIN)) +#define G_SCAN_TOKEN_NODE_PLAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE_PLAIN, GScanTokenNodePlainClass)) +#define G_IS_SCAN_TOKEN_NODE_PLAIN_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE_PLAIN)) +#define G_SCAN_TOKEN_NODE_PLAIN_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE_PLAIN, GScanTokenNodePlainClass)) + + +/* Bribe de motif textuelle pour recherches (instance) */ +typedef struct _GScanTokenNodePlain GScanTokenNodePlain; + +/* Bribe de motif textuelle pour recherches (classe) */ +typedef struct _GScanTokenNodePlainClass GScanTokenNodePlainClass; + + +/* Propriétés d'un élément textuel à rechercher */ +typedef enum _ScanPlainNodeFlags +{ + SPNF_NONE = (0 << 0), /* Aucune particularité */ + SPNF_CASE_INSENSITIVE = (1 << 0), /* Ignorance de la casse */ + + /** + * Les deux propriétés suivantes sont récupérées et traitées + * au niveau du Token propriétaire. + */ + + SPNF_FULLWORD = (1 << 1), /* Recherche de mot entier */ + SPNF_PRIVATE = (1 << 2), /* Marque privative */ + +} ScanPlainNodeFlags; + + +/* Indique le type défini pour un noeud représentant une bribe de texte à retrouver. */ +GType g_scan_token_node_plain_get_type(void); + +/* Construit un noeud représentant un motif textuel. */ +GScanTokenNode *g_scan_token_node_plain_new(const sized_binary_t *, GScanTokenModifier *, ScanPlainNodeFlags); + +/* Indique les propriétés particulières d'un noeud de texte. */ +ScanPlainNodeFlags g_scan_token_node_plain_get_flags(const GScanTokenNodePlain *); + +/* Retrouve l'origine d'une correspondance à partir d'un indice. */ +char *g_scan_token_node_plain_get_modifier_path(const GScanTokenNodePlain *, size_t); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_PLAIN_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/sequence-int.h b/src/analysis/scan/patterns/tokens/nodes/sequence-int.h new file mode 100644 index 0000000..f0ea6ae --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/sequence-int.h @@ -0,0 +1,58 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * sequence-int.h - prototypes internes pour des décompositions séquentielles de motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_SEQUENCE_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_SEQUENCE_INT_H + + +#include "sequence.h" + + +#include "../node-int.h" + + + +/* Décompositions séquentielles de motif de recherche (instance) */ +struct _GScanTokenNodeSequence +{ + GScanTokenNode parent; /* A laisser en premier */ + + GScanTokenNode **children; /* Sous-noeuds à représenter */ + size_t count; /* Taille de cette liste */ + +}; + +/* Décompositions séquentielles de motif de recherche (classe) */ +struct _GScanTokenNodeSequenceClass +{ + GScanTokenNodeClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une série de décompositions séquentielles. */ +bool g_scan_token_node_sequence_create(GScanTokenNodeSequence *, GScanTokenNode *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_SEQUENCE_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/nodes/sequence.c b/src/analysis/scan/patterns/tokens/nodes/sequence.c new file mode 100644 index 0000000..394c877 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/sequence.c @@ -0,0 +1,504 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * sequence.c - décompositions séquentielles de motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "sequence.h" + + +#include <assert.h> + + +#include "any.h" +#include "sequence-int.h" + + + +/* ------------------------ DECOMPOSITION DE MOTIF RECHERCHE ------------------------ */ + + +/* Initialise la classe des décompositions séquentielles. */ +static void g_scan_token_node_sequence_class_init(GScanTokenNodeSequenceClass *); + +/* Initialise une instance de décompositions séquentielles. */ +static void g_scan_token_node_sequence_init(GScanTokenNodeSequence *); + +/* Supprime toutes les références externes. */ +static void g_scan_token_node_sequence_dispose(GScanTokenNodeSequence *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_token_node_sequence_finalize(GScanTokenNodeSequence *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Prend acte d'une nouvelle propriété pour le noeud. */ +static void g_scan_token_node_sequence_apply_flags(GScanTokenNodeSequence *, ScanTokenNodeFlags); + +/* Parcourt une arborescence de noeuds et y relève des éléments. */ +static void g_scan_token_node_sequence_visit(GScanTokenNodeSequence *node, scan_tree_points_t *); + +/* Inscrit la définition d'un motif dans un moteur de recherche. */ +static bool g_scan_token_node_sequence_enroll(GScanTokenNodeSequence *, GEngineBackend *, size_t, size_t *); + +/* Récupère un identifiant final pour un atome d'octets. */ +static bool g_scan_token_node_sequence_build_id(GScanTokenNodeSequence *, GEngineBackend *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_sequence_check_forward(const GScanTokenNodeSequence *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + +/* Transforme les correspondances locales en trouvailles. */ +static void g_scan_token_node_sequence_check_backward(const GScanTokenNodeSequence *, scan_node_check_params_t *, TokenNodeCheckFlags, bool *); + + + +/* ---------------------------------------------------------------------------------- */ +/* DECOMPOSITION DE MOTIF RECHERCHE */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour des décompositions séquentielles de motif de recherche. */ +G_DEFINE_TYPE(GScanTokenNodeSequence, g_scan_token_node_sequence, G_TYPE_SCAN_TOKEN_NODE); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des décompositions séquentielles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_class_init(GScanTokenNodeSequenceClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanTokenNodeClass *node; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_token_node_sequence_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_token_node_sequence_finalize; + + node = G_SCAN_TOKEN_NODE_CLASS(klass); + + node->apply = (apply_scan_token_node_flags_fc)g_scan_token_node_sequence_apply_flags; + node->visit = (visit_scan_token_node_fc)g_scan_token_node_sequence_visit; + node->enroll = (enroll_scan_token_node_fc)g_scan_token_node_sequence_enroll; + node->build_id = (build_scan_token_node_id_fc)g_scan_token_node_sequence_build_id; + node->check_forward = (check_scan_token_node_fc)g_scan_token_node_sequence_check_forward; + node->check_backward = (check_scan_token_node_fc)g_scan_token_node_sequence_check_backward; + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = instance à initialiser. * +* * +* Description : Initialise une instance de décompositions séquentielles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_init(GScanTokenNodeSequence *sequence) +{ + sequence->children = NULL; + sequence->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_dispose(GScanTokenNodeSequence *sequence) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < sequence->count; i++) + g_clear_object(&sequence->children[i]); + + G_OBJECT_CLASS(g_scan_token_node_sequence_parent_class)->dispose(G_OBJECT(sequence)); + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_finalize(GScanTokenNodeSequence *sequence) +{ + if (sequence->children != NULL) + free(sequence->children); + + G_OBJECT_CLASS(g_scan_token_node_sequence_parent_class)->finalize(G_OBJECT(sequence)); + +} + + +/****************************************************************************** +* * +* Paramètres : child = noeud dont les résultats sont à écarter. * +* * +* Description : Construit une série de décompositions séquentielles de motif.* +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_sequence_new(GScanTokenNode *child) +{ + GScanTokenNode *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_TOKEN_NODE_SEQUENCE, NULL); + + if (!g_scan_token_node_sequence_create(G_SCAN_TOKEN_NODE_SEQUENCE(result), child)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = décompositions à initialiser pleinement. * +* child = noeud dont les résultats sont à écarter. * +* * +* Description : Met en place une série de décompositions séquentielles. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_token_node_sequence_create(GScanTokenNodeSequence *sequence, GScanTokenNode *child) +{ + bool result; /* Bilan à retourner */ + + result = true; + + g_scan_token_node_sequence_add(sequence, child); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = ensemble de noeuds à compléter. * +* child = nouveau noeud à intégrer. * +* * +* Description : Ajoute un noeud à aux décompositions séquentielles de motif. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_token_node_sequence_add(GScanTokenNodeSequence *sequence, GScanTokenNode *child) +{ + bool processed; /* Intégration traitée ? */ + GScanTokenNode *last; /* Dernier noeud inscrit */ + + processed = false; + + if (sequence->count > 0) + { + last = sequence->children[sequence->count - 1]; + + if (G_IS_SCAN_TOKEN_NODE_ANY(last) && G_IS_SCAN_TOKEN_NODE_ANY(child)) + { + g_scan_token_node_any_merge(G_SCAN_TOKEN_NODE_ANY(last), G_SCAN_TOKEN_NODE_ANY(child)); + processed = true; + } + + } + + if (!processed) + { + sequence->children = realloc(sequence->children, ++sequence->count * sizeof(GScanTokenNode *)); + + sequence->children[sequence->count - 1] = child; + g_object_ref(G_OBJECT(child)); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = ensemble de noeuds à consulter. * +* * +* Description : Indique le nombre de noeuds intégrés dans la séquence. * +* * +* Retour : Nombre de noeuds représentés. * +* * +* Remarques : - * +* * +******************************************************************************/ + +size_t g_scan_token_node_sequence_count(const GScanTokenNodeSequence *sequence) +{ + size_t result; /* Quantité à retourner */ + + result = sequence->count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : sequence = ensemble de noeuds à consulter. * +* index = indice du noeud à retourner. * +* * +* Description : Fournit un noeud donné d'une décomposition séquentielle. * +* * +* Retour : Noeud inclus dans l'ensemble ou NULL si mauvais indice. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanTokenNode *g_scan_token_node_sequence_get(const GScanTokenNodeSequence *sequence, size_t index) +{ + GScanTokenNode *result; /* Instance à retourner */ + + assert(index < sequence->count); + + if (index < sequence->count) + { + result = sequence->children[index]; + g_object_ref(G_OBJECT(result)); + } + + else + result = NULL; + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : node = noeud de motif à mettre à jour. * +* flags = propriétés particulières à associer au noeud. * +* * +* Description : Prend acte d'une nouvelle propriété pour le noeud. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_apply_flags(GScanTokenNodeSequence *node, ScanTokenNodeFlags flags) +{ + size_t i; /* Boucle de parcours */ + + if (node->count == 1) + g_scan_token_node_set_flags(node->children[0], flags); + + else if (node->count > 1) + { + g_scan_token_node_set_flags(node->children[0], flags & ~STNF_LAST); + + for (i = 1; i < (node->count - 1); i++) + g_scan_token_node_set_flags(node->children[i], flags & ~(STNF_FIRST | STNF_LAST)); + + g_scan_token_node_set_flags(node->children[node->count - 1], flags & ~STNF_FIRST); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : node = point de départ du parcours à effectuer. * +* points = points capitaux de l'arborescence. [OUT] * +* * +* Description : Parcourt une arborescence de noeuds et y relève des éléments.* +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_visit(GScanTokenNodeSequence *node, scan_tree_points_t *points) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < node->count; i++) + g_scan_token_node_visit(node->children[i], points); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à enregistrer. * +* backend = moteur de recherche à préchauffer. * +* maxsize = taille max. des atomes (mise en commun optimisée). * +* slow = niveau de ralentissement induit (0 = idéal). [OUT] * +* * +* Description : Inscrit la définition d'un motif dans un moteur de recherche.* +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_sequence_enroll(GScanTokenNodeSequence *node, GEngineBackend *backend, size_t maxsize, size_t *slow) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours */ + + result = true; + + for (i = 0; i < node->count && result; i++) + result = _g_scan_token_node_enroll(node->children[i], backend, maxsize, slow); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à peaufiner. * +* backend = moteur de recherche à préchauffer. * +* * +* Description : Récupère un identifiant final pour un atome d'octets. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_token_node_sequence_build_id(GScanTokenNodeSequence *node, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours #1 */ + + result = true; + + for (i = 0; i < node->count && result; i++) + result = g_scan_token_node_build_id(node->children[i], backend); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_check_forward(const GScanTokenNodeSequence *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < node->count; i++) + _g_scan_token_node_check_forward(node->children[i], params, cflags, skip); + +} + + +/****************************************************************************** +* * +* Paramètres : node = définition de la bribe à manipuler. * +* params = accès direct aux éléments utiles aux validations. * +* cflags = altérations de traitement à respecter. * +* skip = détermine si l'analyse est différée. [OUT] * +* * +* Description : Transforme les correspondances locales en trouvailles. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_token_node_sequence_check_backward(const GScanTokenNodeSequence *node, scan_node_check_params_t *params, TokenNodeCheckFlags cflags, bool *skip) +{ + size_t i; /* Boucle de parcours */ + + for (i = node->count; i > 0 ; i--) + _g_scan_token_node_check_backward(node->children[i - 1], params, cflags, skip); + +} diff --git a/src/analysis/scan/patterns/tokens/nodes/sequence.h b/src/analysis/scan/patterns/tokens/nodes/sequence.h new file mode 100644 index 0000000..12df9d1 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/nodes/sequence.h @@ -0,0 +1,67 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * sequence.h - prototypes pour des décompositions séquentielles de motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_SEQUENCE_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_SEQUENCE_H + + +#include <glib-object.h> + + +#include "../node.h" + + + +#define G_TYPE_SCAN_TOKEN_NODE_SEQUENCE g_scan_token_node_sequence_get_type() +#define G_SCAN_TOKEN_NODE_SEQUENCE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_TOKEN_NODE_SEQUENCE, GScanTokenNodeSequence)) +#define G_IS_SCAN_TOKEN_NODE_SEQUENCE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_TOKEN_NODE_SEQUENCE)) +#define G_SCAN_TOKEN_NODE_SEQUENCE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_TOKEN_NODE_SEQUENCE, GScanTokenNodeSequenceClass)) +#define G_IS_SCAN_TOKEN_NODE_SEQUENCE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_TOKEN_NODE_SEQUENCE)) +#define G_SCAN_TOKEN_NODE_SEQUENCE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_TOKEN_NODE_SEQUENCE, GScanTokenNodeSequenceClass)) + + +/* Décompositions séquentielles de motif de recherche (instance) */ +typedef struct _GScanTokenNodeSequence GScanTokenNodeSequence; + +/* Décompositions séquentielles de motif de recherche (classe) */ +typedef struct _GScanTokenNodeSequenceClass GScanTokenNodeSequenceClass; + + +/* Indique le type défini pour des décompositions séquentielles de motif de recherche. */ +GType g_scan_token_node_sequence_get_type(void); + +/* Construit une série de décompositions séquentielles de motif. */ +GScanTokenNode *g_scan_token_node_sequence_new(GScanTokenNode *); + +/* Ajoute un noeud à aux décompositions séquentielles de motif. */ +void g_scan_token_node_sequence_add(GScanTokenNodeSequence *, GScanTokenNode *); + +/* Indique le nombre de noeuds intégrés dans la séquence. */ +size_t g_scan_token_node_sequence_count(const GScanTokenNodeSequence *); + +/* Fournit un noeud donné d'une décomposition séquentielle. */ +GScanTokenNode *g_scan_token_node_sequence_get(const GScanTokenNodeSequence *, size_t); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_NODES_SEQUENCE_H */ diff --git a/src/analysis/scan/patterns/tokens/offset.c b/src/analysis/scan/patterns/tokens/offset.c new file mode 100644 index 0000000..0a4fd91 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/offset.c @@ -0,0 +1,438 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * offset.c - décomposition d'un motif de recherche en atomes assemblés + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "offset.h" + + +#include <assert.h> + + + + + + +/****************************************************************************** +* * +* Paramètres : range = bornes décrivant un espace quelconque. * +* available = espace restant disponible. * +* min = point de départ pour parcourir une zone. [OUT] * +* max = point d'arrivée pour parcourir une zone. [OUT] * +* * +* Description : Fournit les bornes d'une zone à analyser. * +* * +* Retour : true si assez d'espace est disponible, false sinon. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool get_node_offset_range(const node_offset_range_t *range, phys_t len, phys_t available, phys_t *min, phys_t *max) +{ + bool result; /* Bilan à retourner */ + + if ((len + range->min) > available) + result = false; + + else + { + result = true; + + *min = range->min; + *max = range->max; + + if ((len + *max) > available) + { + *max = available - len; + assert(*max >= *min); + } + + } + + return result; + +} + + + + + + + + + + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à initialiser. * +* * +* Description : Initialise une mémorisation d'intervales de tolérance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void init_node_search_offset(node_search_offset_t *offset) +{ + offset->ranges = NULL; + offset->allocated = 0; + + offset->gen_ptr = NULL; + + offset->used = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = suivi de tolérances bornées à initialiser. [OUT] * +* src = suivi de tolérances bornées à copier. * +* * +* Description : Copie une mémorisation d'intervales entre positions. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void copy_node_search_offset(node_search_offset_t *dest, const node_search_offset_t *src) +{ + init_node_search_offset(dest); + + switch (src->used) + { + case 0: + dest->gen_ptr = NULL; + break; + + case 1: + dest->range = src->range; + dest->gen_ptr = &dest->range; + break; + + default: + dest->ranges = malloc(src->used * sizeof(node_offset_range_t)); + memcpy(dest->ranges, src->ranges, src->used * sizeof(node_offset_range_t)); + dest->gen_ptr = dest->ranges;; + break; + + } + + dest->used = src->used; + +} + + +/****************************************************************************** +* * +* Paramètres : dest = suivi de tolérances bornées à initialiser. [OUT] * +* src = suivi de tolérances bornées à copier. * +* * +* Description : Fusionne une mémorisation d'intervales entre positions. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void merge_node_search_offset(node_search_offset_t *dest, const node_search_offset_t *src) +{ + node_offset_range_t * const *list; /* Liste d'intervales à copier */ + size_t i; /* Boucle de parcours */ + + if ((dest->used + src->used) > 1 && (dest->used + src->used) > dest->allocated) + { + dest->allocated += src->used; + + dest->ranges = realloc(dest->ranges, dest->allocated * sizeof(node_offset_range_t)); + + } + + list = get_node_search_offset_ranges(src, (size_t []){ 0 }); + + for (i = 0; i < src->used; i++) + add_range_to_node_search_offset(dest, (*list)[i].min, (*list)[i].max, NULL); + +} + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à terminer. * +* * +* Description : Met fin à une mémorisation d'intervales de tolérance. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void exit_node_search_offset(node_search_offset_t *offset) +{ + if (offset->ranges != NULL) + free(offset->ranges); + +} + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à consulter. * +* count = nombre de bornes enregistrées. [OUT] * +* * +* Description : Fournit la liste des tolérances bornées établies à présent. * +* * +* Retour : Liste d'intervales en lecture seule. * +* * +* Remarques : - * +* * +******************************************************************************/ + +node_offset_range_t * const *get_node_search_offset_ranges(const node_search_offset_t *offset, size_t *count) +{ + node_offset_range_t * const *result; /* Série à renvoyer */ + + result = &offset->gen_ptr; + + *count = offset->used; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à consulter. * +* count = nombre de bornes enregistrées. [OUT] * +* * +* Description : Fournit la liste des tolérances bornées établies à présent. * +* * +* Retour : Liste d'intervales en lecture seule. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const node_offset_range_t * const get_node_search_offset_ranges_2(const node_search_offset_t *offset, size_t *count) +{ + node_offset_range_t *result; /* Série à renvoyer */ + + result = offset->gen_ptr; + + *count = offset->used; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à consulter. * +* min = point de départ pour parcourir une zone. * +* max = point d'arrivée pour parcourir une zone. * +* datasize = taille maximale pour définir une inversion NOT. * +* * +* Description : Ajoute un nouvel espace borné aux décalages tolérés. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void add_range_to_node_search_offset(node_search_offset_t *offset, phys_t min, phys_t max, const phys_t *datasize) +{ + bool not; /* Traduction de la taille */ + size_t needed; /* Nombre d'emplacements requis*/ + + not = (datasize != NULL); + + /* Si le réceptacle unique peut être employé... */ + if (offset->used == 0 && !not) + { + offset->range.min = min; + offset->range.max = max; + + offset->used = 1; + + offset->gen_ptr = &offset->range; + + } + + /* Sinon le groupe dynamique est sollicité */ + else + { + needed = offset->used + (not ? 2 : 1); + + if (needed > offset->allocated) + { + offset->ranges = realloc(offset->ranges, needed * sizeof(node_offset_range_t)); + offset->allocated = needed; + } + + /* Bascule d'un éventuel intervale courant */ + if (offset->used == 1) + { + offset->ranges[0].min = offset->range.min; + offset->ranges[0].max = offset->range.max; + } + + if (not) + { + if (min > 0) + { + offset->ranges[offset->used].min = 0; + offset->ranges[offset->used].max = min - 1; + + offset->used++; + + } + + if ((max + 1) < *datasize) + { + offset->ranges[offset->used].min = max + 1; + offset->ranges[offset->used].max = *datasize - (max + 1); + + offset->used++; + + } + + } + else + { + offset->ranges[offset->used].min = min; + offset->ranges[offset->used].max = max; + + offset->used++; + + } + + offset->gen_ptr = offset->ranges; + + } + +} + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à consulter. * +* min = point de départ pour parcourir une zone. * +* max = point d'arrivée pour parcourir une zone. * +* has_max = validité de la valeur maximale transmise. * +* * +* Description : Etend les décalages tolérés avec un nouvel espace. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void extend_node_search_offset(node_search_offset_t *offset, phys_t min, phys_t max, bool has_max) +{ + size_t i; /* Boucle de parcours */ + + switch (offset->used) + { + /* Si le réceptacle unique peut être employé... */ + case 0: + + offset->range.min = min; + offset->range.max = max; + offset->range.has_max = has_max; + + offset->used = 1; + + offset->gen_ptr = &offset->range; + + break; + + /* Si un espace unique est enregistré */ + case 1: + + offset->range.min += min; + offset->range.max += max; + offset->range.has_max &= has_max; + + break; + + /* Sinon le groupe dynamique est sollicité */ + default: + + for (i = 0; i < offset->used; i++) + { + offset->ranges[i].min += min; + offset->ranges[i].max += max; + offset->ranges[i].has_max &= has_max; + } + + break; + + } + +} + + +/****************************************************************************** +* * +* Paramètres : offset = suivi de tolérances bornées à consulter. * +* last = dernière position validée. * +* pos = nouvelle position potentielle. * +* * +* Description : Indique si une position est comprise dans un intervale. * +* * +* Retour : Bilan de la détermination. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool does_node_search_offset_include_pos_forward(const node_search_offset_t *offset, phys_t last, phys_t pos) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + const node_offset_range_t *range; /* Accès rapide aux infos. */ + + result = false; + + for (i = 0; i < offset->used; i++) + { + range = &offset->gen_ptr[i]; + + result = ((last + range->min) <= pos && pos <= (last + range->max)); + if (result) break; + + } + + return result; + +} diff --git a/src/analysis/scan/patterns/tokens/offset.h b/src/analysis/scan/patterns/tokens/offset.h new file mode 100644 index 0000000..130aaea --- /dev/null +++ b/src/analysis/scan/patterns/tokens/offset.h @@ -0,0 +1,111 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * offset.h - prototypes pour la prise en compte des espaces entre octets dans un motif de recherche + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_OFFSET_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_OFFSET_H + + +#include <stdbool.h> + +#include "../../../../arch/vmpa.h" + + + +/* Mémorisation d'une souplesse dans les positions visées */ +typedef struct _node_offset_range_t +{ + /** + * Les deux champs ci-après font bien référence à des positions absolues, + * et non à des bornes d'espace, lorsque les résultats de correspondances + * sont encore non initialisés. + * + * Ensuite ces bornes représentent bien un espace séparant les résultats + * issus de deux noeuds. + */ + phys_t min; /* Position minimale */ + phys_t max; /* Position maximale */ + bool has_max; /* Quantité définie ? */ + +} node_offset_range_t; + + +/* Fournit les bornes d'une zone à analyser. */ +bool get_node_offset_range(const node_offset_range_t *, phys_t, phys_t, phys_t *, phys_t *); + + + +#define MAX_RANGE_FOR_MANUAL_CHECK 5 + + + +/* Mémorisation d'une souplesse dans les positions visées */ +typedef struct _node_search_offset_t +{ + node_offset_range_t range; /* Bornes de décalage uniques */ + + node_offset_range_t *ranges; /* Bornes de décalage multiples*/ + size_t allocated; /* Nombre d'allocations */ + + node_offset_range_t *gen_ptr; /* Accès générique à la liste */ + + size_t used; /* Nombre de bornes présentes */ + +} node_search_offset_t; + + +/* Initialise une mémorisation d'intervales de tolérance. */ +void init_node_search_offset(node_search_offset_t *); + +/* Copie une mémorisation d'intervales entre positions. */ +void copy_node_search_offset(node_search_offset_t *, const node_search_offset_t *); + +/* Fusionne une mémorisation d'intervales entre positions. */ +void merge_node_search_offset(node_search_offset_t *, const node_search_offset_t *); + +/* Met fin à une mémorisation d'intervales de tolérance. */ +void exit_node_search_offset(node_search_offset_t *); + +#define offsets_exist(off) \ + ((off)->used > 0) + + +/* Fournit la liste des tolérances bornées établies à présent. */ +/* TODO : supprimer un niveau d'indirection */ +node_offset_range_t * const *get_node_search_offset_ranges(const node_search_offset_t *, size_t *); +const node_offset_range_t * const get_node_search_offset_ranges_2(const node_search_offset_t *, size_t *); + +/* Ajoute un nouvel espace borné aux décalages tolérés. */ +void add_range_to_node_search_offset(node_search_offset_t *, phys_t, phys_t, const phys_t *); + +/* Etend les décalages tolérés avec un nouvel espace. */ +void extend_node_search_offset(node_search_offset_t *, phys_t, phys_t, bool); + +#define disable_all_ranges_in_node_search_offset(off) \ + (off)->used = 0 + +/* Indique si une position est comprise dans un intervale. */ +bool does_node_search_offset_include_pos_forward(const node_search_offset_t *, phys_t, phys_t); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_OFFSET_H */ diff --git a/src/analysis/scan/patterns/tokens/plain-int.h b/src/analysis/scan/patterns/tokens/plain-int.h new file mode 100644 index 0000000..b0ef106 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/plain-int.h @@ -0,0 +1,56 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain-int.h - prototypes internes pour la recherche d'une chaîne de caractères brute + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_PLAIN_INT_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_PLAIN_INT_H + + +#include "plain.h" + + +#include "atom.h" +#include "../token-int.h" + + + +/* Encadrement d'une recherche de texte brut (instance) */ +struct _GScanPlainBytes +{ + GBytesToken parent; /* A laisser en premier */ + +}; + +/* Encadrement d'une recherche de texte brut (classe) */ +struct _GScanPlainBytesClass +{ + GBytesTokenClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un gestionnaire de recherche de texte brut. */ +bool g_scan_plain_bytes_create(GScanPlainBytes *, GScanTokenNode *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_PLAIN_INT_H */ diff --git a/src/analysis/scan/patterns/tokens/plain.c b/src/analysis/scan/patterns/tokens/plain.c new file mode 100644 index 0000000..3d6c39d --- /dev/null +++ b/src/analysis/scan/patterns/tokens/plain.c @@ -0,0 +1,266 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain.c - recherche d'une chaîne de caractères brute + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "plain.h" + + +#include <malloc.h> +#include <string.h> + + +#include "plain-int.h" +#include "nodes/plain.h" + + + +/* ----------------------- RECHERCHE D'UN MOTIF DE TEXTE BRUT ----------------------- */ + + +/* Initialise la classe des recherches de texte brut. */ +static void g_scan_plain_bytes_class_init(GScanPlainBytesClass *klass); + +/* Initialise une instance de recherche de texte brut. */ +static void g_scan_plain_bytes_init(GScanPlainBytes *); + +/* Supprime toutes les références externes. */ +static void g_scan_plain_bytes_dispose(GScanPlainBytes *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_plain_bytes_finalize(GScanPlainBytes *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Affiche un motif de recherche au format texte. */ +static void g_scan_plain_bytes_output_to_text(const GScanPlainBytes *, GScanContext *, int); + +/* Affiche un motif de recherche au format JSON. */ +static void g_scan_plain_bytes_output_to_json(const GScanPlainBytes *, GScanContext *, const sized_string_t *, unsigned int, int); + + + +/* ---------------------------------------------------------------------------------- */ +/* RECHERCHE D'UN MOTIF DE TEXTE BRUT */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une suite d'octets à retrouver dans un binaire. */ +G_DEFINE_TYPE(GScanPlainBytes, g_scan_plain_bytes, G_TYPE_BYTES_TOKEN); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des recherches de texte brut. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_bytes_class_init(GScanPlainBytesClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GSearchPatternClass *pattern; /* Version de classe ancêtre */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_plain_bytes_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_plain_bytes_finalize; + + pattern = G_SEARCH_PATTERN_CLASS(klass); + + pattern->to_text = (output_pattern_to_text_fc)g_scan_plain_bytes_output_to_text; + pattern->to_json = (output_pattern_to_json_fc)g_scan_plain_bytes_output_to_json; + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = instance à initialiser. * +* * +* Description : Initialise une instance de recherche de texte brut. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_bytes_init(GScanPlainBytes *bytes) +{ + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_bytes_dispose(GScanPlainBytes *bytes) +{ + G_OBJECT_CLASS(g_scan_plain_bytes_parent_class)->dispose(G_OBJECT(bytes)); + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_bytes_finalize(GScanPlainBytes *bytes) +{ + G_OBJECT_CLASS(g_scan_plain_bytes_parent_class)->finalize(G_OBJECT(bytes)); + +} + + +/****************************************************************************** +* * +* Paramètres : root = représentation du motif à recherche. * +* * +* Description : Construit un gestionnaire de recherche de texte brut. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GSearchPattern *g_scan_plain_bytes_new(GScanTokenNode *root) +{ + GSearchPattern *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_PLAIN_BYTES, NULL); + + if (!g_scan_plain_bytes_create(G_SCAN_PLAIN_BYTES(result), root)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : bytes = encadrement de motif à initialiser pleinement. * +* root = représentation du motif à recherche. * +* * +* Description : Met en place un gestionnaire de recherche de texte brut. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_plain_bytes_create(GScanPlainBytes *bytes, GScanTokenNode *root) +{ + bool result; /* Bilan à retourner */ + ScanPlainNodeFlags flags; /* Propriétés à interpréter */ + bool fullword; /* Cible de mots entiers ? */ + bool private; /* Vocation privée ? */ + + flags = g_scan_token_node_plain_get_flags(G_SCAN_TOKEN_NODE_PLAIN(root)); + + fullword = (flags & SPNF_FULLWORD); + private = (flags & SPNF_PRIVATE); + + result = g_bytes_token_create(G_BYTES_TOKEN(bytes), root, fullword, private); + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_bytes_output_to_text(const GScanPlainBytes *pattern, GScanContext *context, int fd) +{ + G_SEARCH_PATTERN_CLASS(g_scan_plain_bytes_parent_class)->to_text(G_SEARCH_PATTERN(pattern), context, fd); + +} + + +/****************************************************************************** +* * +* Paramètres : pattern = définition de motif à considérer. * +* context = contexte de l'analyse à mener. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* * +* Description : Affiche un motif de recherche au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_plain_bytes_output_to_json(const GScanPlainBytes *pattern, GScanContext *context, const sized_string_t *padding, unsigned int level, int fd) +{ + G_SEARCH_PATTERN_CLASS(g_scan_plain_bytes_parent_class)->to_json(G_SEARCH_PATTERN(pattern), context, padding, level, fd); + + /* TODO */ + +} diff --git a/src/analysis/scan/patterns/tokens/plain.h b/src/analysis/scan/patterns/tokens/plain.h new file mode 100644 index 0000000..6ff48d7 --- /dev/null +++ b/src/analysis/scan/patterns/tokens/plain.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * plain.h - prototypes pour la recherche d'une chaîne de caractères brute + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_PATTERNS_TOKENS_PLAIN_H +#define _ANALYSIS_SCAN_PATTERNS_TOKENS_PLAIN_H + + +#include <glib-object.h> + + +#include "node.h" +#include "../../pattern.h" + + + +#define G_TYPE_SCAN_PLAIN_BYTES g_scan_plain_bytes_get_type() +#define G_SCAN_PLAIN_BYTES(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_PLAIN_BYTES, GScanPlainBytes)) +#define G_IS_SCAN_PLAIN_BYTES(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_PLAIN_BYTES)) +#define G_SCAN_PLAIN_BYTES_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_PLAIN_BYTES, GScanPlainBytesClass)) +#define G_IS_SCAN_PLAIN_BYTES_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_PLAIN_BYTES)) +#define G_SCAN_PLAIN_BYTES_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_PLAIN_BYTES, GScanPlainBytesClass)) + + +/* Représentation d'une suite d'octets à retrouver (instance) */ +typedef struct _GScanPlainBytes GScanPlainBytes; + +/* Représentation d'une suite d'octets à retrouver (classe) */ +typedef struct _GScanPlainBytesClass GScanPlainBytesClass; + + +/* Indique le type défini pour une suite d'octets à retrouver dans un binaire. */ +GType g_scan_plain_bytes_get_type(void); + +/* Construit un gestionnaire de recherche de texte brut. */ +GSearchPattern *g_scan_plain_bytes_new(GScanTokenNode *); + + + +#endif /* _ANALYSIS_SCAN_PATTERNS_TOKENS_PLAIN_H */ diff --git a/src/analysis/scan/rule-int.h b/src/analysis/scan/rule-int.h new file mode 100644 index 0000000..17d4dc2 --- /dev/null +++ b/src/analysis/scan/rule-int.h @@ -0,0 +1,69 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * rule-int.h - prototypes internes pour la gestion d'une règle de détection par motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_RULE_INT_H +#define _ANALYSIS_SCAN_RULE_INT_H + + +#include "rule.h" + + + +#define PATTERN_ALLOC_SIZE 20 + + +/* Représentation d'une règle de détection statique (instance) */ +struct _GScanRule +{ + GObject parent; /* A laisser en premier */ + + ScanRuleFlags flags; /* Propriétés de la règle */ + + char *name; /* Désignation de la règle */ + fnv64_t name_hash; /* Empreinte de la désignation */ + + char **tags; /* Etiquettes associées */ + char tags_count; /* Quantité de ces étiquettes */ + + GSearchPattern **bytes_locals; /* Variables de données */ + size_t bytes_allocated; /* Taille allouée du tableau */ + size_t bytes_used; /* Nombre d'éléments présents */ + + GScanExpression *condition; /* Condition de correspondance */ + +}; + +/* Représentation d'une règle de détection statique (classe) */ +struct _GScanRuleClass +{ + GObjectClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une règle de détection statique avec motifs. */ +bool g_scan_rule_create(GScanRule *, ScanRuleFlags, const char *); + + + +#endif /* _ANALYSIS_SCAN_RULE_INT_H */ diff --git a/src/analysis/scan/rule.c b/src/analysis/scan/rule.c new file mode 100644 index 0000000..d3acbc2 --- /dev/null +++ b/src/analysis/scan/rule.c @@ -0,0 +1,1084 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * rule.c - parcours de contenus à la recherche de motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "rule.h" + + +#include <assert.h> +#include <regex.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <sys/mman.h> +#include <sys/stat.h> + + +#include "rule-int.h" +#include "matches/bytes.h" +#include "patterns/token.h" +#include "../../common/extstr.h" +#include "../../core/logs.h" + + + +/* Initialise la classe des règles de détection statique. */ +static void g_scan_rule_class_init(GScanRuleClass *); + +/* Initialise une instance de règle de détection statique. */ +static void g_scan_rule_init(GScanRule *); + +/* Supprime toutes les références externes. */ +static void g_scan_rule_dispose(GScanRule *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_rule_finalize(GScanRule *); + + + +/* Indique le type défini pour une règle de détection par motifs. */ +G_DEFINE_TYPE(GScanRule, g_scan_rule, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des règles de détection statique. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_rule_class_init(GScanRuleClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_rule_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_rule_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = instance à initialiser. * +* * +* Description : Initialise une instance de règle de détection statique. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_rule_init(GScanRule *rule) +{ + rule->flags = SRF_NONE; + + rule->name = NULL; + rule->name_hash = 0; + + rule->tags = NULL; + rule->tags_count = 0; + + rule->bytes_locals = NULL; + rule->bytes_allocated = 0; + rule->bytes_used = 0; + + rule->condition = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_rule_dispose(GScanRule *rule) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < rule->bytes_used; i++) + g_clear_object(&rule->bytes_locals[i]); + + g_clear_object(&rule->condition); + + G_OBJECT_CLASS(g_scan_rule_parent_class)->dispose(G_OBJECT(rule)); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_rule_finalize(GScanRule *rule) +{ + size_t i; /* Boucle de parcours */ + + if (rule->name != NULL) + free(rule->name); + + for (i = 0; i < rule->tags_count; i++) + free(rule->tags[i]); + + if (rule->tags != NULL) + free(rule->tags); + + if (rule->bytes_locals != NULL) + free(rule->bytes_locals); + + G_OBJECT_CLASS(g_scan_rule_parent_class)->finalize(G_OBJECT(rule)); + +} + + +/****************************************************************************** +* * +* Paramètres : flags = propriétés particulières à conférer à la règle. * +* name = désignation à associer à la future règle. * +* * +* Description : Crée une règle de détection statique à l'aide de motifs. * +* * +* Retour : Règle de détection mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanRule *g_scan_rule_new(ScanRuleFlags flags, const char *name) +{ + GScanRule *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_RULE, NULL); + + result->flags = flags; + + result->name = strdup(name); + result->name_hash = fnv_64a_hash(name); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à initialiser pleinement. * +* flags = propriétés particulières à conférer à la règle. * +* name = désignation à associer à la future règle. * +* * +* Description : Met en place une règle de détection statique avec motifs. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_rule_create(GScanRule *rule, ScanRuleFlags flags, const char *name) +{ + GScanRule *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_RULE, NULL); + + result->flags = flags; + + result->name = strdup(name); + result->name_hash = fnv_64a_hash(name); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à consulter. * +* * +* Description : Indique les particularités liées à une règle de détection. * +* * +* Retour : Propriétés particulières attachées à la règle. * +* * +* Remarques : - * +* * +******************************************************************************/ + +ScanRuleFlags g_scan_rule_get_flags(const GScanRule *rule) +{ + ScanRuleFlags result; /* Fanions à retourner */ + + result = rule->flags; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à consulter. * +* hash = empreinte précalculée associée au nom. [OUT] * +* * +* Description : Indique le nom associé à une règle de détection. * +* * +* Retour : Désignation humaine associée à la règle. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char *g_scan_rule_get_name(const GScanRule *rule, fnv64_t *hash) +{ + const char *result; /* Désignation à retourner */ + + result = rule->name; + + if (hash != NULL) + *hash = rule->name_hash; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à compléter. * +* tag = étiquette à associer à la règle. * +* * +* Description : Lie une règle à une nouvelle étiquette. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_rule_add_tag(GScanRule *rule, const char *tag) +{ + rule->tags = realloc(rule->tags, ++rule->tags_count * sizeof(char *)); + + rule->tags[rule->tags_count - 1] = strdup(tag); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à consulter. * +* count = quantité d'éléments retournés. [OUT] * +* * +* Description : Indique les éventuelles étiquettes associées à une règle. * +* * +* Retour : Liste d'étiquettes associées à la règle consultée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char * const *g_scan_rule_list_tags(const GScanRule *rule, size_t *count) +{ + const char * const *result; /* Liste à retourner */ + + result = rule->tags; + + *count = rule->tags_count; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à compléter. * +* pattern = nouveau motif de détection. * +* * +* Description : Intègre une nouvelle variable locale à une règle. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_rule_add_local_variable(GScanRule *rule, GSearchPattern *pattern) +{ + if (G_IS_BYTES_TOKEN(pattern)) + { + if (rule->bytes_used == rule->bytes_allocated) + { + rule->bytes_allocated += PATTERN_ALLOC_SIZE; + rule->bytes_locals = realloc(rule->bytes_locals, rule->bytes_allocated * sizeof(GSearchPattern *)); + } + + rule->bytes_locals[rule->bytes_used++] = pattern; + g_object_ref(G_OBJECT(pattern)); + + } + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à consulter. * +* target = nom d'une variable locale à retrouver. * +* * +* Description : Fournit une variable locale à une règle selon un nom. * +* * +* Retour : Motif de détection retrouvé ou NULL en cas d'échec. * +* * +* Remarques : La propriétée de l'instance renvoyée est partagée ! * +* * +******************************************************************************/ + +const GSearchPattern *g_scan_rule_get_local_variable(GScanRule *rule, const char *target) +{ + const GSearchPattern *result; /* Variable à retourner */ + size_t i; /* Boucle de parcours */ + const char *name; /* Désignation d'un motif */ + + result = NULL; + + for (i = 0; i < rule->bytes_used; i++) + { + name = g_search_pattern_get_name(rule->bytes_locals[i]); + + if (strcmp(name, target) == 0) + { + result = rule->bytes_locals[i]; + break; + } + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à consulter. * +* target = nom d'une variable locale à retrouver. * +* count = quantité de motifs renvoyés. [OUT] * +* * +* Description : Fournit une liste de variables locales à partir d'un nom. * +* * +* Retour : Motifs de détection retrouvés ou NULL en cas d'échec. * +* * +* Remarques : La propriétée des instances renvoyées est partagée ! * +* * +******************************************************************************/ + +const GSearchPattern **g_scan_rule_get_local_variables(GScanRule *rule, const char *target, size_t *count) +{ + const GSearchPattern **result; /* Variables à retourner */ + size_t target_len; /* Nbre de caractères à évaluer*/ + size_t len_without_star; /* Taille sans masque */ + bool need_regex; /* Traitement complexe requis */ + size_t i; /* Boucle de parcours */ + char *regex; /* Définition complète */ + regex_t preg; /* Expression compilée */ + int ret; /* Bilan d'un appel */ + const char *name; /* Désignation d'un motif */ + + result = NULL; + + *count = 0; + + /* Premier cas de figure : la liste complète est attendue */ + + if (target == NULL) + { + need_all_of_them: + + *count = rule->bytes_used; + result = malloc(*count * sizeof(GSearchPattern *)); + + memcpy(result, rule->bytes_locals, *count); + + } + + /* Second cas de figure : identification au cas par cas */ + + else + { + target_len = strlen(target); + + len_without_star = 0; + + need_regex = false; + + for (i = 0; i < target_len; i++) + if (target[i] == '*') + break; + else + len_without_star++; + + for (i++; i < target_len; i++) + if (target[i] != '*') + { + need_regex = true; + goto try_harder; + } + + if (len_without_star == 0) + goto need_all_of_them; + + result = malloc(rule->bytes_used * sizeof(GSearchPattern *)); + + for (i = 0; i < rule->bytes_used; i++) + { + name = g_search_pattern_get_name(rule->bytes_locals[i]); + + if (strncmp(name, target, len_without_star) == 0) + { + result[*count] = rule->bytes_locals[i]; + (*count)++; + } + + } + + if (*count == 0) + { + free(result); + result = NULL; + } + + } + + try_harder: + + /* Dernier cas de figure : une expression régulière est vraisemblablement de mise */ + + if (need_regex) + { + regex = strdup(target); + + regex = strrpl(regex, "*", ".*"); + regex = strprep(regex, "^"); + regex = stradd(regex, "$"); + + ret = regcomp(&preg, regex, REG_NOSUB); + + if (ret != 0) + { + LOG_ERROR_REGCOMP(&preg, ret); + goto done; + } + + result = malloc(rule->bytes_used * sizeof(GSearchPattern *)); + + for (i = 0; i < rule->bytes_used; i++) + { + name = g_search_pattern_get_name(rule->bytes_locals[i]); + + ret = regexec(&preg, name, 0, NULL, 0); + + if (ret != REG_NOMATCH) + { + result[*count] = rule->bytes_locals[i]; + (*count)++; + } + + } + + if (*count == 0) + { + free(result); + result = NULL; + } + + regfree(&preg); + + done: + + free(regex); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à compléter. * +* expr = expression de condition à satisfaire. * +* * +* Description : Définit l'expression d'une correspondance recherchée. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_rule_set_match_condition(GScanRule *rule, GScanExpression *expr) +{ + rule->condition = expr; + + g_object_ref(G_OBJECT(expr)); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* backend = moteur d'analyse pour données brutes. * +* context = contexte de l'analyse à mener. * +* * +* Description : Prépare le suivi de recherche de motifs pour une règle. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_rule_setup_backend(GScanRule *rule, GEngineBackend *backend, GScanContext *context) +{ + bool result; /* Statut à retourner */ + size_t maxsize; /* Taille maximale des atomes */ + GSearchPattern *pattern; /* Motif à intégrer */ + size_t i; /* Boucle de parcours */ + + /* Suivi des conditions de correspondance */ + + result = g_scan_context_set_rule_condition(context, rule->name, rule->condition); + if (!result) goto exit; + + /* Programmation des motifs recherchés */ + + maxsize = g_engine_backend_get_atom_max_size(backend); + + for (i = 0; i < rule->bytes_used && result; i++) + { + pattern = rule->bytes_locals[i]; + result = g_bytes_token_enroll(G_BYTES_TOKEN(pattern), backend, maxsize); + } + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* backend = moteur d'analyse pour données brutes. * +* * +* Description : Récupère les identifiants finaux pour les motifs recherchés. * +* * +* Retour : Bilan de l'opération à renvoyer. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_rule_define_pattern_ids(GScanRule *rule, GEngineBackend *backend) +{ + bool result; /* Statut à retourner */ + size_t i; /* Boucle de parcours */ + GSearchPattern *pattern; /* Motif à intégrer */ + + result = true; + + for (i = 0; i < rule->bytes_used && result; i++) + { + pattern = rule->bytes_locals[i]; + result = g_bytes_token_build_id(G_BYTES_TOKEN(pattern), backend); + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* backend = moteur d'analyse pour données brutes. * +* context = contexte de l'analyse à mener. * +* * +* Description : Lance une analyse d'un contenu binaire selon une règle. * +* * +* Retour : Contexte de suivi pour l'analyse menée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_rule_check(GScanRule *rule, GEngineBackend *backend, GScanContext *context) +{ + scan_node_check_params_t params; /* Rassemblement de paramètres */ + vmpa2t start; /* Point de début du contenu */ + vmpa2t end; /* Point de fin du contenu */ + size_t i; /* Boucle de parcours */ + GSearchPattern *pattern; /* Motif à intégrer */ + GScanMatches *matches; /* Correspondances établies */ + + /* Définition d'un contexte */ + + params.context = context; + params.content = g_scan_context_get_content(context); + params.allocator = g_umem_slice_new(sizeof(match_area_t)); + + g_binary_content_compute_start_pos(params.content, &start); + g_binary_content_compute_end_pos(params.content, &end); + + params.content_start = start.physical; + params.content_end = end.physical; + + /* Vérifications */ + + for (i = 0; i < rule->bytes_used; i++) + { + pattern = rule->bytes_locals[i]; + + matches = g_scan_bytes_matches_new(); + + g_bytes_token_check(G_BYTES_TOKEN(pattern), G_SCAN_BYTES_MATCHES(matches), ¶ms); + + g_scan_context_register_full_matches(context, pattern, matches); + + g_object_unref(G_OBJECT(matches)); + + } + + g_object_unref(G_OBJECT(params.content)); + //g_object_unref(G_OBJECT(params.allocator)); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* context = contexte de l'analyse à mener. * +* full = force un affichage complet des résultats. * +* fd = canal d'écriture. * +* * +* Description : Affiche une règle au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_rule_output_to_text(const GScanRule *rule, GScanContext *context, bool full, int fd) +{ + GScanOptions *options; /* Options de l'utilisateur */ + bool selected; /* Affichage attendu ? */ + size_t i; /* Boucle de parcours */ + GBinContent *content; /* Contenu binaire scanné */ + char *desc; /* Description de ce contenu */ + + /** + * Si la règle n'a pas fait mouche, rien n'est imprimé. + */ + if (!g_scan_context_has_match_for_rule(context, rule->name)) + return; + + options = g_scan_context_get_options(context); + + selected = g_scan_options_has_tag_as_selected(options, NULL); + + /** + * Si la règle comporte des étiquettes et que l'utilisateur en a spécifié + * également. + */ + if (rule->tags_count > 0 && !selected) + { + for (i = 0; i < rule->tags_count && !selected; i++) + selected = g_scan_options_has_tag_as_selected(options, rule->tags[i]); + } + + if (selected) + { + write(fd, rule->name, strlen(rule->name)); + + if (g_scan_options_get_print_tags(options)) + { + write(fd, " [", 2); + + for (i = 0; i < rule->tags_count; i++) + { + if (i > 0) + write(fd, ",", 1); + + write(fd, rule->tags[i], strlen(rule->tags[i])); + + } + + write(fd, "]", 1); + + } + + write(fd, " ", 1); + + content = g_scan_context_get_content(context); + + desc = g_binary_content_describe(content, true); + + write(fd, desc, strlen(desc)); + write(fd, "\n", 1); + + free(desc); + + g_object_unref(G_OBJECT(content)); + + if (full) + for (i = 0; i < rule->bytes_used; i++) + g_search_pattern_output_to_text(rule->bytes_locals[i], context, fd); + + } + + g_object_unref(G_OBJECT(options)); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* context = contexte de l'analyse à mener. * +* * +* Description : Convertit une règle en texte. * +* * +* Retour : Données textuelles ou NULL en cas d'erreur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_rule_convert_as_text(const GScanRule *rule, GScanContext *context) +{ + char *result; /* Données à retourner */ + char *name; /* Nom "unique" pour le canal */ + int ret; /* Bilan de création de nom */ + int fd; /* Canal d'écriture */ + struct stat info; /* Infos. incluant une taille */ + ssize_t got; /* Données effectivement relues*/ + + static unsigned long long counter = 0; + + result = NULL; + + ret = asprintf(&name, "rost-rule2text-%llu", counter++); + if (ret == -1) goto exit; + + fd = memfd_create(name, MFD_CLOEXEC); + if (fd == -1) + { + LOG_ERROR_N("memfd_create"); + goto exit_with_name; + } + + g_scan_rule_output_to_text(rule, context, true, fd); + + ret = fstat(fd, &info); + if (ret != 0) + { + LOG_ERROR_N("fstat"); + goto exit_with_name_and_fd; + } + + result = malloc((info.st_size + 1) * sizeof(char)); + + lseek(fd, SEEK_SET, 0); + + got = read(fd, result, info.st_size); + if (got != info.st_size) + { + LOG_ERROR_N("read"); + free(result); + goto exit_with_name_and_fd; + } + + result[info.st_size] = '\0'; + + exit_with_name_and_fd: + + close(fd); + + exit_with_name: + + free(name); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* context = contexte de l'analyse à mener. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* tail = décline la pose d'une virgule finale ? * +* * +* Description : Affiche une règle au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_scan_rule_output_to_json(const GScanRule *rule, GScanContext *context, const sized_string_t *padding, unsigned int level, int fd, bool tail) +{ + size_t i; /* Boucle de parcours #1 */ + bool sub_tail; /* Saut de la virgule finale ? */ + size_t k; /* Boucle de parcours #2 */ + GBinContent *content; /* Contenu binaire scanné */ + char *desc; /* Description de ce contenu */ + + /* Introduction */ + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + write(fd, "{\n", 2); + + /* Désignation de la règle */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"name\": \"", 9); + + write(fd, rule->name, strlen(rule->name)); + + write(fd, "\",\n", 3); + + /* Etiquettes ? */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"tags\": [", 9); + + if (rule->tags_count > 0) + { + write(fd, "\n", 1); + + for (k = 0; k < rule->tags_count; k++) + { + for (i = 0; i < (level + 2); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"", 1); + + write(fd, rule->tags[k], strlen(rule->tags[k])); + + write(fd, "\"", 1); + + if ((k + 1) < rule->tags_count) + write(fd, ",", 1); + + write(fd, "\n", 1); + + } + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + } + + write(fd, "],\n", 3); + + /* Cible du scan */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"target\": \"", 11); + + content = g_scan_context_get_content(context); + + desc = g_binary_content_describe(content, true); + + write(fd, desc, strlen(desc)); + + free(desc); + + g_object_unref(G_OBJECT(content)); + + write(fd, "\",\n", 3); + + /* Affichage des correspondances d'octets */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"bytes_patterns\": [\n", 20); + + for (i = 0; i < rule->bytes_used; i++) + { + sub_tail = ((i + 1) == rule->bytes_used); + + g_search_pattern_output_to_json(rule->bytes_locals[i], context, padding, level + 2, fd, sub_tail); + + } + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "],\n", 3); + + /* Bilan du filtrage */ + + for (i = 0; i < (level + 1); i++) + write(fd, padding->data, padding->len); + + write(fd, "\"matched\": ", 11); + + if (g_scan_context_has_match_for_rule(context, rule->name)) + write(fd, "true", 4); + else + write(fd, "false", 5); + + write(fd, "\n", 1); + + /* Conclusion */ + + for (i = 0; i < level; i++) + write(fd, padding->data, padding->len); + + if (tail) + write(fd, "}\n", 2); + else + write(fd, "},\n", 3); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = règle de détection à considérer. * +* context = contexte de l'analyse à mener. * +* * +* Description : Convertit une règle en JSON. * +* * +* Retour : Données textuelles au format JSON ou NULL en cas d'erreur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_scan_rule_convert_as_json(const GScanRule *rule, GScanContext *context) +{ + char *result; /* Données à retourner */ + char *name; /* Nom "unique" pour le canal */ + int ret; /* Bilan de création de nom */ + int fd; /* Canal d'écriture */ + sized_string_t padding; /* Bourrage pour le JSON */ + struct stat info; /* Infos. incluant une taille */ + ssize_t got; /* Données effectivement relues*/ + + static unsigned long long counter = 0; + + result = NULL; + + ret = asprintf(&name, "rost-rule2json-%llu", counter++); + if (ret == -1) goto exit; + + fd = memfd_create(name, MFD_CLOEXEC); + if (fd == -1) + { + LOG_ERROR_N("memfd_create"); + goto exit_with_name; + } + + padding.data = " "; + padding.len = 3; + + g_scan_rule_output_to_json(rule, context, &padding, 0, fd, false); + + ret = fstat(fd, &info); + if (ret != 0) + { + LOG_ERROR_N("fstat"); + goto exit_with_name_and_fd; + } + + result = malloc((info.st_size + 1) * sizeof(char)); + + lseek(fd, SEEK_SET, 0); + + got = read(fd, result, info.st_size); + if (got != info.st_size) + { + LOG_ERROR_N("read"); + free(result); + goto exit_with_name_and_fd; + } + + result[info.st_size] = '\0'; + + exit_with_name_and_fd: + + close(fd); + + exit_with_name: + + free(name); + + exit: + + return result; + +} diff --git a/src/analysis/scan/rule.h b/src/analysis/scan/rule.h new file mode 100644 index 0000000..c2c58dc --- /dev/null +++ b/src/analysis/scan/rule.h @@ -0,0 +1,119 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scanner.h - prototypes pour le parcours de contenus à la recherche de motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_RULE_H +#define _ANALYSIS_SCAN_RULE_H + + +#include <glib-object.h> + + +#include "cond.h" +#include "context.h" +#include "pattern.h" +#include "expr.h" +#include "patterns/backend.h" +#include "../../common/fnv1a.h" +#include "../../common/szstr.h" + + + +#define G_TYPE_SCAN_RULE g_scan_rule_get_type() +#define G_SCAN_RULE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_RULE, GScanRule)) +#define G_IS_SCAN_RULE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_RULE)) +#define G_SCAN_RULE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_RULE, GScanRuleClass)) +#define G_IS_SCAN_RULE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_RULE)) +#define G_SCAN_RULE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_RULE, GScanRuleClass)) + + +/* Représentation d'une règle de détection statique (instance) */ +typedef struct _GScanRule GScanRule; + +/* Représentation d'une règle de détection statique (classe) */ +typedef struct _GScanRuleClass GScanRuleClass; + + +/* Particularités de règle à faire valoir */ +typedef enum _ScanRuleFlags +{ + SRF_NONE = (0 << 0), /* Absence de particularité */ + SRF_PRIVATE = (1 << 0), /* Règle silencieuse */ + SRF_GLOBAL = (1 << 1) /* Règle de base implicite */ + +} ScanRuleFlags; + + +/* Indique le type défini pour une règle de détection par motifs. */ +GType g_scan_rule_get_type(void); + +/* Crée une règle de détection statique à l'aide de motifs. */ +GScanRule *g_scan_rule_new(ScanRuleFlags, const char *); + +/* Indique les particularités liées à une règle de détection. */ +ScanRuleFlags g_scan_rule_get_flags(const GScanRule *); + +/* Indique le nom associé à une règle de détection. */ +const char *g_scan_rule_get_name(const GScanRule *, fnv64_t *); + +/* Lie une règle à une nouvelle étiquette. */ +void g_scan_rule_add_tag(GScanRule *, const char *); + +/* Indique les éventuelles étiquettes associées à une règle. */ +const char * const *g_scan_rule_list_tags(const GScanRule *, size_t *); + +/* Intègre une nouvelle variable locale à une règle. */ +void g_scan_rule_add_local_variable(GScanRule *, GSearchPattern *); + +/* Fournit une variable locale à une règle selon un nom. */ +const GSearchPattern *g_scan_rule_get_local_variable(GScanRule *, const char *); + +/* Fournit une liste de variables locales à partir d'un nom. */ +const GSearchPattern **g_scan_rule_get_local_variables(GScanRule *, const char *, size_t *); + +/* Définit l'expression d'une correspondance recherchée. */ +void g_scan_rule_set_match_condition(GScanRule *, GScanExpression *); + +/* Prépare le suivi de recherche de motifs pour une règle. */ +bool g_scan_rule_setup_backend(GScanRule *, GEngineBackend *, GScanContext *); + +/* Récupère les identifiants finaux pour les motifs recherchés. */ +bool g_scan_rule_define_pattern_ids(GScanRule *, GEngineBackend *); + +/* Lance une analyse d'un contenu binaire selon une règle. */ +void g_scan_rule_check(GScanRule *, GEngineBackend *, GScanContext *); + +/* Affiche une règle au format texte. */ +void g_scan_rule_output_to_text(const GScanRule *, GScanContext *, bool, int); + +/* Convertit une règle en texte. */ +char *g_scan_rule_convert_as_text(const GScanRule *, GScanContext *); + +/* Affiche une règle au format JSON. */ +void g_scan_rule_output_to_json(const GScanRule *, GScanContext *, const sized_string_t *, unsigned int, int, bool); + +/* Convertit une règle en JSON. */ +char *g_scan_rule_convert_as_json(const GScanRule *, GScanContext *); + + + +#endif /* _ANALYSIS_SCAN_RULE_H */ diff --git a/src/analysis/scan/scanner-int.h b/src/analysis/scan/scanner-int.h new file mode 100644 index 0000000..02fd6b3 --- /dev/null +++ b/src/analysis/scan/scanner-int.h @@ -0,0 +1,65 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scanner-int.h - prototypes internes pour le parcours de contenus à la recherche de motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_SCANNER_INT_H +#define _ANALYSIS_SCAN_SCANNER_INT_H + + +#include "scanner.h" + + +#include "patterns/backend.h" + + + +/* Encadrement d'une recherche au sein de contenus binaires (instance) */ +struct _GContentScanner +{ + GObject parent; /* A laisser en premier */ + + char *filename; /* Eventuel fichier d'origine */ + + GScanRule **rules; /* Règles de détection */ + size_t rule_count; /* Nombre de ces règles */ + + GEngineBackend *data_backend; /* Moteur pour les données */ + +}; + +/* Encadrement d'une recherche au sein de contenus binaires (classe) */ +struct _GContentScannerClass +{ + GObjectClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un scanner de contenus binaires. */ +bool g_content_scanner_create_from_text(GContentScanner *, const char *, size_t); + +/* Met en place un scanner de contenus binaires. */ +bool g_content_scanner_create_from_file(GContentScanner *, const char *); + + + +#endif /* _ANALYSIS_SCAN_SCANNER_INT_H */ diff --git a/src/analysis/scan/scanner.c b/src/analysis/scan/scanner.c new file mode 100644 index 0000000..02a93fa --- /dev/null +++ b/src/analysis/scan/scanner.c @@ -0,0 +1,808 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scanner.c - parcours de contenus à la recherche de motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "scanner.h" + + +#include <assert.h> +#include <libgen.h> +#include <malloc.h> +#include <stdio.h> +#include <unistd.h> +#include <sys/mman.h> +#include <sys/stat.h> + + +#include "decl.h" +#include "scanner-int.h" +#include "../contents/file.h" +#include "../../common/extstr.h" +#include "../../core/logs.h" + + + +/* Initialise la classe des recherches dans du binaire. */ +static void g_content_scanner_class_init(GContentScannerClass *); + +/* Initialise une instance de recherche dans du binaire. */ +static void g_content_scanner_init(GContentScanner *); + +/* Supprime toutes les références externes. */ +static void g_content_scanner_dispose(GContentScanner *); + +/* Procède à la libération totale de la mémoire. */ +static void g_content_scanner_finalize(GContentScanner *); + +/* Intègre une nouvelle règle de détection. */ +static bool _g_content_scanner_add_rule(GContentScanner *, GScanRule *); + + + +/* Indique le type défini pour une recherche dans du binaire. */ +G_DEFINE_TYPE(GContentScanner, g_content_scanner, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des recherches dans du binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_content_scanner_class_init(GContentScannerClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_content_scanner_dispose; + object->finalize = (GObjectFinalizeFunc)g_content_scanner_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = instance à initialiser. * +* * +* Description : Initialise une instance de recherche dans du binaire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_content_scanner_init(GContentScanner *scanner) +{ + scanner->filename = NULL; + + scanner->rules = NULL; + scanner->rule_count = 0; + + scanner->data_backend = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_content_scanner_dispose(GContentScanner *scanner) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < scanner->rule_count; i++) + g_clear_object(&scanner->rules[i]); + + g_clear_object(&scanner->data_backend); + + G_OBJECT_CLASS(g_content_scanner_parent_class)->dispose(G_OBJECT(scanner)); + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_content_scanner_finalize(GContentScanner *scanner) +{ + if (scanner->filename != NULL) + free(scanner->filename); + + if (scanner->rules != NULL) + free(scanner->rules); + + G_OBJECT_CLASS(g_content_scanner_parent_class)->finalize(G_OBJECT(scanner)); + +} + + +/****************************************************************************** +* * +* Paramètres : text = définitions textuelles de règles de recherche. * +* length = taille de la définition. * +* * +* Description : Prépare une recherche de motifs dans du contenu binaire. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GContentScanner *g_content_scanner_new_from_text(const char *text, size_t length) +{ + GContentScanner *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_CONTENT_SCANNER, NULL); + + if (!g_content_scanner_create_from_text(result, text, length)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = scanner de contenus à initialiser pleinement. * +* text = définitions textuelles de règles de recherche. * +* length = taille de la définition. * +* * +* Description : Met en place un scanner de contenus binaires. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_content_scanner_create_from_text(GContentScanner *scanner, const char *text, size_t length) +{ + bool result; /* Bilan à retourner */ + + result = process_rules_definitions(scanner, text, length); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : filename = chemin vers des définitions de règles. * +* * +* Description : Prépare une recherche de motifs dans du contenu binaire. * +* * +* Retour : Mécanismes mis en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GContentScanner *g_content_scanner_new_from_file(const char *filename) +{ + GContentScanner *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_CONTENT_SCANNER, NULL); + + if (!g_content_scanner_create_from_file(result, filename)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = scanner de contenus à initialiser pleinement. * +* filename = chemin vers des définitions de règles. * +* * +* Description : Met en place un scanner de contenus binaires. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_content_scanner_create_from_file(GContentScanner *scanner, const char *filename) +{ + bool result; /* Bilan à retourner */ + GBinContent *content; /* Fichier à parcourir */ + phys_t size; /* Taille du contenu associé */ + vmpa2t start; /* Tête de lecture */ + const bin_t *data; /* Données à consulter */ + + result = false; + + content = g_file_content_new(filename); + if (content == NULL) goto no_content; + + scanner->filename = strdup(filename); + + size = g_binary_content_compute_size(content); + + g_binary_content_compute_start_pos(content, &start); + data = g_binary_content_get_raw_access(content, &start, size); + + result = process_rules_definitions(scanner, (char *)data, size); + + g_object_unref(G_OBJECT(content)); + + no_content: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = scanner de contenus à consulter. * +* * +* Description : Indique le chemin d'un éventuel fichier de source. * +* * +* Retour : Chemin d'un éventuel fichier de définitions ou NULL. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char *g_content_scanner_get_filename(const GContentScanner *scanner) +{ + const char *result; /* Chemin à retourner */ + + result = scanner->filename; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à compléter. * +* path = chemin vers une définition de règles à intégrer. * +* * +* Description : Inclut les définitions d'un fichier de règles externe. * +* * +* Retour : Bilan de l'inclusion à retourner. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_content_scanner_include_resource(GContentScanner *scanner, const char *path) +{ + bool result; /* Bilan à retourner */ + GContentScanner *included; /* Définition à inclure */ + char *tmp; /* Copie de travail */ + char *filename; /* Chemin d'accès reconstruit */ + size_t i; /* Boucle de parcours */ + const char *inc_name; /* Nom de la nouvelle règle */ + + /* Cas le plus simple : un chemin absolu */ + if (path[0] == '/') + included = g_content_scanner_new_from_file(path); + + /* Chemin relatif à l'emplacement de la définition courante ? */ + else if (scanner->filename != NULL) + { + tmp = strdup(scanner->filename); + + filename = strdup(dirname(tmp)); + filename = stradd(filename, G_DIR_SEPARATOR_S); + filename = stradd(filename, path); + + included = g_content_scanner_new_from_file(filename); + + free(filename); + free(tmp); + + } + + else + included = NULL; + + /* Inclusion des règles chargées */ + + result = (included != NULL); + + if (result) + { + for (i = 0; i < included->rule_count && result; i++) + { + result = _g_content_scanner_add_rule(scanner, included->rules[i]); + + if (!result) + { + inc_name = g_scan_rule_get_name(included->rules[i], NULL); + + log_variadic_message(LMT_ERROR, "Can not import from '%s': rule '%s' already exists!", + path, inc_name); + + } + + } + + g_object_unref(G_OBJECT(included)); + + } + + return result; + + + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à compléter. * +* rule = règle de détection à intégrer. * +* * +* Description : Intègre une nouvelle règle de détection. * +* * +* Retour : Bilan de l'ajout à retourner. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool _g_content_scanner_add_rule(GContentScanner *scanner, GScanRule *rule) +{ + bool result; /* Bilan à retourner */ + const char *inc_name; /* Nom de la nouvelle règle */ + fnv64_t inc_hash; /* Empreinte de ce nom */ + size_t i; /* Boucle de parcours */ + const char *cur_name; /* Nom d'une règle en place */ + fnv64_t cur_hash; /* Empreinte de ce nom */ + + result = false; + + inc_name = g_scan_rule_get_name(rule, &inc_hash); + + for (i = 0; i < scanner->rule_count; i++) + { + cur_name = g_scan_rule_get_name(scanner->rules[i], &cur_hash); + + if (inc_hash != cur_hash) + continue; + + if (strcmp(inc_name, cur_name) == 0) + goto exit_add; + + } + + result = true; + + scanner->rules = realloc(scanner->rules, ++scanner->rule_count * sizeof(GScanRule *)); + + scanner->rules[scanner->rule_count - 1] = rule; + + g_object_ref(G_OBJECT(rule)); + + exit_add: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à compléter. * +* rule = règle de détection à intégrer. * +* * +* Description : Intègre une nouvelle règle de détection. * +* * +* Retour : Bilan de l'ajout à retourner. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_content_scanner_add_rule(GContentScanner *scanner, GScanRule *rule) +{ + bool result; /* Bilan à retourner */ + const char *inc_name; /* Nom de la nouvelle règle */ + + result = _g_content_scanner_add_rule(scanner, rule); + + if (!result) + { + inc_name = g_scan_rule_get_name(rule, NULL); + + log_variadic_message(LMT_ERROR, "Can not add rule: '%s' already exists!", inc_name); + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à compléter. * +* options = ensemble des options d'analyses à respecter. * +* content = contenu à parcourir et analyser. * +* * +* Description : Lance une analyse d'un contenu binaire. * +* * +* Retour : Contexte de suivi pour l'analyse menée. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanContext *g_content_scanner_analyze(GContentScanner *scanner, GScanOptions *options, GBinContent *content) +{ + GScanContext *result; /* Bilan global à retourner */ + bool status; /* Bilan d'opération locale */ + size_t i; /* Boucle de parcours */ + size_t ids_count; /* Quantité de motifs prévus */ + bool global; /* Bilan des règles globales */ + GScanRule *rule; /* Règle à consulter */ + const char *name; /* Désignation de la règle */ + + /* Préparations... */ + + result = g_scan_context_new(options); + + if (scanner->data_backend == NULL) + { + scanner->data_backend = g_object_new(g_scan_options_get_backend_for_data(options), NULL); + assert(scanner->data_backend != NULL); + + status = (scanner->data_backend != NULL); + + for (i = 0; i < scanner->rule_count && status; i++) + status = g_scan_rule_setup_backend(scanner->rules[i], scanner->data_backend, result); + + if (status) + status = g_engine_backend_warm_up(scanner->data_backend); + + for (i = 0; i < scanner->rule_count && status; i++) + status = g_scan_rule_define_pattern_ids(scanner->rules[i], scanner->data_backend); + + if (!status) + { + g_clear_object(&result); + goto exit; + } + + /* Affichage éventuel de statistiques */ + + if (g_scan_options_get_print_stats(options)) + g_engine_backend_output_stats(scanner->data_backend); + + } + + /* Phase d'analyse */ + + ids_count = g_engine_backend_count_plain_pattern_ids(scanner->data_backend); + + g_scan_context_set_content(result, content, ids_count); + + g_engine_backend_run_scan(scanner->data_backend, result); + + g_scan_context_mark_scan_as_done(result); + + for (i = 0; i < scanner->rule_count; i++) + g_scan_rule_check(scanner->rules[i], scanner->data_backend, result); + + /* Etablissement d'un bilan global */ + + global = true; + + for (i = 0; i < scanner->rule_count && global; i++) + { + rule = scanner->rules[i]; + + if ((g_scan_rule_get_flags(rule) & SRF_GLOBAL) == 0) + continue; + + name = g_scan_rule_get_name(rule, NULL); + + global = g_scan_context_has_match_for_rule(result, name); + + } + + g_scan_context_set_global_match(result, global); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à consulter. * +* context = contexte de l'analyse à mener. * +* full = force un affichage complet des résultats. * +* fd = canal d'écriture. * +* * +* Description : Affiche un gestionnaire de recherches au format texte. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_content_scanner_output_to_text(const GContentScanner *scanner, GScanContext *context, bool full, int fd) +{ + size_t i; /* Boucle de parcours */ + + /* Sous-traitance aux règles */ + + for (i = 0; i < scanner->rule_count; i++) + g_scan_rule_output_to_text(scanner->rules[i], context, full, fd); + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à consulter. * +* context = contexte de l'analyse à mener. * +* * +* Description : Convertit un gestionnaire de recherches en texte. * +* * +* Retour : Données textuelles ou NULL en cas d'erreur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_content_scanner_convert_to_text(const GContentScanner *scanner, GScanContext *context) +{ + char *result; /* Données à retourner */ + char *name; /* Nom "unique" pour le canal */ + int ret; /* Bilan de création de nom */ + int fd; /* Canal d'écriture */ + struct stat info; /* Infos. incluant une taille */ + ssize_t got; /* Données effectivement relues*/ + + static unsigned long long counter = 0; + + result = NULL; + + ret = asprintf(&name, "rost-scanner2text-%llu", counter++); + if (ret == -1) goto exit; + + fd = memfd_create(name, MFD_CLOEXEC); + if (fd == -1) + { + LOG_ERROR_N("memfd_create"); + goto exit_with_name; + } + + g_content_scanner_output_to_text(scanner, context, true, fd); + + ret = fstat(fd, &info); + if (ret != 0) + { + LOG_ERROR_N("fstat"); + goto exit_with_name_and_fd; + } + + result = malloc((info.st_size + 1) * sizeof(char)); + + lseek(fd, SEEK_SET, 0); + + got = read(fd, result, info.st_size); + if (got != info.st_size) + { + LOG_ERROR_N("read"); + free(result); + goto exit_with_name_and_fd; + } + + result[info.st_size] = '\0'; + + exit_with_name_and_fd: + + close(fd); + + exit_with_name: + + free(name); + + exit: + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à consulter. * +* context = contexte de l'analyse à mener. * +* padding = éventuel bourrage initial à placer ou NULL. * +* level = profondeur actuelle. * +* fd = canal d'écriture. * +* * +* Description : Affiche un gestionnaire de recherches au format JSON. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +void g_content_scanner_output_to_json(const GContentScanner *scanner, GScanContext *context, const sized_string_t *padding, unsigned int level, int fd) +{ + size_t k; /* Boucle de parcours #1 */ + size_t i; /* Boucle de parcours #2 */ + size_t last_displayed; /* Dernier indice affiché */ + bool tail; /* Saut de la virgule finale ? */ + + /* Introduction */ + + for (k = 0; k < level; k++) + write(fd, padding->data, padding->len); + + write(fd, "[\n", 2); + + /* Sous-traitance aux règles */ + + for (i = scanner->rule_count; i > 0; i--) + if ((g_scan_rule_get_flags(scanner->rules[i - 1]) & SRF_PRIVATE) == 0) + break; + + if (i == 0) + goto nothing_to_display; + else + last_displayed = i - 1; + + for (i = 0; i < scanner->rule_count; i++) + { + if ((g_scan_rule_get_flags(scanner->rules[i]) & SRF_PRIVATE) == SRF_PRIVATE) + continue; + + tail = (i == last_displayed); + + g_scan_rule_output_to_json(scanner->rules[i], context, padding, level + 1, fd, tail); + + } + + /* Conclusion */ + + nothing_to_display: + + for (k = 0; k < level; k++) + write(fd, padding->data, padding->len); + + write(fd, "]\n", 2); + +} + + +/****************************************************************************** +* * +* Paramètres : scanner = gestionnaire de recherche à consulter. * +* context = contexte de l'analyse à mener. * +* * +* Description : Convertit un gestionnaire de recherches en JSON. * +* * +* Retour : Données textuelles au format JSON ou NULL en cas d'erreur. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char *g_content_scanner_convert_to_json(const GContentScanner *scanner, GScanContext *context) +{ + char *result; /* Données à retourner */ + char *name; /* Nom "unique" pour le canal */ + int ret; /* Bilan de création de nom */ + int fd; /* Canal d'écriture */ + sized_string_t padding; /* Bourrage pour le JSON */ + struct stat info; /* Infos. incluant une taille */ + ssize_t got; /* Données effectivement relues*/ + + static unsigned long long counter = 0; + + result = NULL; + + ret = asprintf(&name, "rost-scanner2json-%llu", counter++); + if (ret == -1) goto exit; + + fd = memfd_create(name, MFD_CLOEXEC); + if (fd == -1) + { + LOG_ERROR_N("memfd_create"); + goto exit_with_name; + } + + padding.data = " "; + padding.len = 3; + + g_content_scanner_output_to_json(scanner, context, &padding, 0, fd); + + ret = fstat(fd, &info); + if (ret != 0) + { + LOG_ERROR_N("fstat"); + goto exit_with_name_and_fd; + } + + result = malloc((info.st_size + 1) * sizeof(char)); + + lseek(fd, SEEK_SET, 0); + + got = read(fd, result, info.st_size); + if (got != info.st_size) + { + LOG_ERROR_N("read"); + free(result); + goto exit_with_name_and_fd; + } + + result[info.st_size] = '\0'; + + exit_with_name_and_fd: + + close(fd); + + exit_with_name: + + free(name); + + exit: + + return result; + +} diff --git a/src/analysis/scan/scanner.h b/src/analysis/scan/scanner.h new file mode 100644 index 0000000..7926ba1 --- /dev/null +++ b/src/analysis/scan/scanner.h @@ -0,0 +1,89 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scanner.h - prototypes pour le parcours de contenus à la recherche de motifs + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_SCANNER_H +#define _ANALYSIS_SCAN_SCANNER_H + + +#include <glib-object.h> + + +#include "context.h" +#include "expr.h" +#include "options.h" +#include "rule.h" +#include "../../common/szstr.h" + + + +#define G_TYPE_CONTENT_SCANNER g_content_scanner_get_type() +#define G_CONTENT_SCANNER(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_CONTENT_SCANNER, GContentScanner)) +#define G_IS_CONTENT_SCANNER(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_CONTENT_SCANNER)) +#define G_CONTENT_SCANNER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_CONTENT_SCANNER, GContentScannerClass)) +#define G_IS_CONTENT_SCANNER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_CONTENT_SCANNER)) +#define G_CONTENT_SCANNER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_CONTENT_SCANNER, GContentScannerClass)) + + +/* Encadrement d'une recherche au sein de contenus binaires (instance) */ +typedef struct _GContentScanner GContentScanner; + +/* Encadrement d'une recherche au sein de contenus binaires (classe) */ +typedef struct _GContentScannerClass GContentScannerClass; + + +/* Indique le type défini pour une recherche dans du binaire. */ +GType g_content_scanner_get_type(void); + +/* Prépare une recherche de motifs dans du contenu binaire. */ +GContentScanner *g_content_scanner_new_from_text(const char *, size_t); + +/* Prépare une recherche de motifs dans du contenu binaire. */ +GContentScanner *g_content_scanner_new_from_file(const char *); + +/* Indique le chemin d'un éventuel fichier de source. */ +const char *g_content_scanner_get_filename(const GContentScanner *); + +/* Inclut les définitions d'un fichier de règles externe. */ +bool g_content_scanner_include_resource(GContentScanner *, const char *); + +/* Intègre une nouvelle règle de détection. */ +bool g_content_scanner_add_rule(GContentScanner *, GScanRule *); + +/* Définit l'expression d'une correspondance recherchée. */ +GScanContext *g_content_scanner_analyze(GContentScanner *, GScanOptions *, GBinContent *); + +/* Affiche un gestionnaire de recherches au format texte. */ +void g_content_scanner_output_to_text(const GContentScanner *, GScanContext *, bool, int); + +/* Convertit un gestionnaire de recherches en texte. */ +char *g_content_scanner_convert_to_text(const GContentScanner *, GScanContext *); + +/* Affiche un gestionnaire de recherches au format JSON. */ +void g_content_scanner_output_to_json(const GContentScanner *, GScanContext *, const sized_string_t *, unsigned int, int); + +/* Convertit un gestionnaire de recherches en JSON. */ +char *g_content_scanner_convert_to_json(const GContentScanner *, GScanContext *); + + + +#endif /* _ANALYSIS_SCAN_SCANNER_H */ diff --git a/src/analysis/scan/scope-int.h b/src/analysis/scan/scope-int.h new file mode 100644 index 0000000..2d70532 --- /dev/null +++ b/src/analysis/scan/scope-int.h @@ -0,0 +1,54 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scope-int.h - prototypes internes pour la définition d'une portée locale de variables + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_SCOPE_INT_H +#define _ANALYSIS_SCAN_SCOPE_INT_H + + +#include "scope.h" + + + +/* Portée locale de variables et règle d'appartenance (instance) */ +struct _GScanScope +{ + GObject parent; /* A laisser en premier */ + + char *rule; /* Règle d'appartenance */ + +}; + +/* Portée locale de variables et règle d'appartenance (classe) */ +struct _GScanScopeClass +{ + GObjectClass parent; /* A laisser en premier */ + +}; + + +/* Met en place une définition de portée pour variables. */ +bool g_scan_scope_create(GScanScope *, const char *); + + + +#endif /* _ANALYSIS_SCAN_SCOPE_INT_H */ diff --git a/src/analysis/scan/scope.c b/src/analysis/scan/scope.c new file mode 100644 index 0000000..852b1d3 --- /dev/null +++ b/src/analysis/scan/scope.c @@ -0,0 +1,209 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scope.c - définition d'une portée locale de variables + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "scope.h" + + +#include <malloc.h> +#include <string.h> + + +#include "scope-int.h" + + + +/* Initialise la classe des définitions de portée locale. */ +static void g_scan_scope_class_init(GScanScopeClass *); + +/* Initialise une instance de définition de portée locale. */ +static void g_scan_scope_init(GScanScope *); + +/* Supprime toutes les références externes. */ +static void g_scan_scope_dispose(GScanScope *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_scope_finalize(GScanScope *); + + + +/* Indique le type défini pour la définition de portée de variables. */ +G_DEFINE_TYPE(GScanScope, g_scan_scope, G_TYPE_OBJECT); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des définitions de portée locale. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_scope_class_init(GScanScopeClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_scope_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_scope_finalize; + +} + + +/****************************************************************************** +* * +* Paramètres : scope = instance à initialiser. * +* * +* Description : Initialise une instance de définition de portée locale. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_scope_init(GScanScope *scope) +{ + scope->rule = NULL; + +} + + +/****************************************************************************** +* * +* Paramètres : scope = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_scope_dispose(GScanScope *scope) +{ + G_OBJECT_CLASS(g_scan_scope_parent_class)->dispose(G_OBJECT(scope)); + +} + + +/****************************************************************************** +* * +* Paramètres : scope = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_scope_finalize(GScanScope *scope) +{ + if (scope->rule != NULL) + free(scope->rule); + + G_OBJECT_CLASS(g_scan_scope_parent_class)->finalize(G_OBJECT(scope)); + +} + + +/****************************************************************************** +* * +* Paramètres : rule = désignation de la règle courante dans l'analyse. * +* * +* Description : Prépare une définition de portée pour variables. * +* * +* Retour : Définition mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanScope *g_scan_scope_new(const char *rule) +{ + GScanScope *result; /* Structure à retourner */ + + result = g_object_new(G_TYPE_SCAN_SCOPE, NULL); + + if (!g_scan_scope_create(result, rule)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scope = définition de portée à à initialiser pleinement. * +* rule = désignation de la règle courante dans l'analyse. * +* * +* Description : Met en place une définition de portée pour variables. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_scope_create(GScanScope *scope, const char *rule) +{ + bool result; /* Bilan à retourner */ + + result = true; + + scope->rule = strdup(rule); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : scope = définition de portée à consulter. * +* * +* Description : Fournit le nom de la règle d'appartenance. * +* * +* Retour : Nom de la règle courante pour une analyse. * +* * +* Remarques : - * +* * +******************************************************************************/ + +const char *g_scan_scope_get_rule_name(const GScanScope *scope) +{ + const char *result; /* Chemin à retourner */ + + result = scope->rule; + + return result; + +} diff --git a/src/analysis/scan/scope.h b/src/analysis/scan/scope.h new file mode 100644 index 0000000..26b8757 --- /dev/null +++ b/src/analysis/scan/scope.h @@ -0,0 +1,59 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * scope.h - prototypes pour la définition d'une portée locale de variables + * + * Copyright (C) 2023 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Chrysalide. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_SCOPE_H +#define _ANALYSIS_SCAN_SCOPE_H + + +#include <glib-object.h> +#include <stdbool.h> + + + +#define G_TYPE_SCAN_SCOPE g_scan_scope_get_type() +#define G_SCAN_SCOPE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_SCOPE, GScanScope)) +#define G_IS_SCAN_SCOPE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_SCOPE)) +#define G_SCAN_SCOPE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_SCOPE, GScanScopeClass)) +#define G_IS_SCAN_SCOPE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_SCOPE)) +#define G_SCAN_SCOPE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_SCOPE, GScanScopeClass)) + + +/* Portée locale de variables et règle d'appartenance (instance) */ +typedef struct _GScanScope GScanScope; + +/* Portée locale de variables et règle d'appartenance (classe) */ +typedef struct _GScanScopeClass GScanScopeClass; + + +/* Indique le type défini pour la définition de portée de variables. */ +GType g_scan_scope_get_type(void); + +/* Prépare une définition de portée pour variables. */ +GScanScope *g_scan_scope_new(const char *); + +/* Fournit le nom de la règle d'appartenance. */ +const char *g_scan_scope_get_rule_name(const GScanScope *); + + + +#endif /* _ANALYSIS_SCAN_SCOPE_H */ diff --git a/src/analysis/scan/space-int.h b/src/analysis/scan/space-int.h new file mode 100644 index 0000000..34c481c --- /dev/null +++ b/src/analysis/scan/space-int.h @@ -0,0 +1,61 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * space-int.h - prototypes internes pour la définition d'un espace de noms pour les fonctions de scan + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_SPACE_INT_H +#define _ANALYSIS_SCAN_SPACE_INT_H + + +#include "space.h" + + +#include "item-int.h" + + + +/* Espace de noms pour un groupe de fonctions (instance) */ +struct _GScanNamespace +{ + GScanRegisteredItem parent; /* A laisser en premier */ + + char *name; /* Désignation de l'espace */ + + GScanRegisteredItem **children; /* Sous-éléments inscrits */ + char **names; /* Désignations correspondantes*/ + size_t count; /* Quantité de sous-éléments */ + +}; + +/* Espace de noms pour un groupe de fonctions (classe) */ +struct _GScanNamespaceClass +{ + GScanRegisteredItemClass parent; /* A laisser en premier */ + +}; + + +/* Met en place un nouvel espace de noms pour scan. */ +bool g_scan_namespace_create(GScanNamespace *, const char *); + + + +#endif /* _ANALYSIS_SCAN_SPACE_INT_H */ diff --git a/src/analysis/scan/space.c b/src/analysis/scan/space.c new file mode 100644 index 0000000..38556a3 --- /dev/null +++ b/src/analysis/scan/space.c @@ -0,0 +1,451 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * space.c - définition d'un espace de noms pour les fonctions de scan + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#include "space.h" + + +#include <stdio.h> +#include <string.h> + + +#include "space-int.h" +#include "../../core/logs.h" + + + +/* ------------------------- SOCLE POUR LES ESPACES DE NOMS ------------------------- */ + + +/* Initialise la classe des espaces de noms pour scan. */ +static void g_scan_namespace_class_init(GScanNamespaceClass *); + +/* Initialise une instance d'espace de noms pour scan. */ +static void g_scan_namespace_init(GScanNamespace *); + +/* Supprime toutes les références externes. */ +static void g_scan_namespace_dispose(GScanNamespace *); + +/* Procède à la libération totale de la mémoire. */ +static void g_scan_namespace_finalize(GScanNamespace *); + + + +/* --------------------- IMPLEMENTATION DES FONCTIONS DE CLASSE --------------------- */ + + +/* Indique le nom associé à une expression d'évaluation. */ +static char *g_scan_namespace_get_name(const GScanNamespace *); + +/* Lance une résolution d'élément à solliciter. */ +static bool g_scan_namespace_resolve(GScanNamespace *, const char *, GScanContext *, GScanScope *, GScanRegisteredItem **); + + + +/* ---------------------------------------------------------------------------------- */ +/* SOCLE POUR LES ESPACES DE NOMS */ +/* ---------------------------------------------------------------------------------- */ + + +/* Indique le type défini pour une définition d'espace de noms. */ +G_DEFINE_TYPE(GScanNamespace, g_scan_namespace, G_TYPE_SCAN_REGISTERED_ITEM); + + +/****************************************************************************** +* * +* Paramètres : klass = classe à initialiser. * +* * +* Description : Initialise la classe des espaces de noms pour scan. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_namespace_class_init(GScanNamespaceClass *klass) +{ + GObjectClass *object; /* Autre version de la classe */ + GScanRegisteredItemClass *registered; /* Version de classe parente */ + + object = G_OBJECT_CLASS(klass); + + object->dispose = (GObjectFinalizeFunc/* ! */)g_scan_namespace_dispose; + object->finalize = (GObjectFinalizeFunc)g_scan_namespace_finalize; + + registered = G_SCAN_REGISTERED_ITEM_CLASS(klass); + + registered->get_name = (get_registered_item_name_fc)g_scan_namespace_get_name; + registered->resolve = (resolve_registered_item_fc)g_scan_namespace_resolve; + +} + + +/****************************************************************************** +* * +* Paramètres : space = instance à initialiser. * +* * +* Description : Initialise une instance d'espace de noms pour scan. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_namespace_init(GScanNamespace *space) +{ + space->name = NULL; + + space->children = NULL; + space->names = NULL; + space->count = 0; + +} + + +/****************************************************************************** +* * +* Paramètres : space = instance d'objet GLib à traiter. * +* * +* Description : Supprime toutes les références externes. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_namespace_dispose(GScanNamespace *space) +{ + size_t i; /* Boucle de parcours */ + + for (i = 0; i < space->count; i++) + g_clear_object(&space->children[i]); + + G_OBJECT_CLASS(g_scan_namespace_parent_class)->dispose(G_OBJECT(space)); + +} + + +/****************************************************************************** +* * +* Paramètres : space = instance d'objet GLib à traiter. * +* * +* Description : Procède à la libération totale de la mémoire. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void g_scan_namespace_finalize(GScanNamespace *space) +{ + size_t i; /* Boucle de parcours */ + + if (space->name != NULL) + free(space->name); + + if (space->children != NULL) + free(space->children); + + for (i = 0; i < space->count; i++) + free(space->names[i]); + + if (space->names != NULL) + free(space->names); + + G_OBJECT_CLASS(g_scan_namespace_parent_class)->finalize(G_OBJECT(space)); + +} + + +/****************************************************************************** +* * +* Paramètres : name = désignation du futur espace de noms. * +* * +* Description : Construit un nouvel espace de noms pour scan. * +* * +* Retour : Adresse de la structure mise en place. * +* * +* Remarques : - * +* * +******************************************************************************/ + +GScanNamespace *g_scan_namespace_new(const char *name) +{ + GScanNamespace *result; /* Instance à retourner */ + + result = g_object_new(G_TYPE_SCAN_NAMESPACE, NULL); + + if (!g_scan_namespace_create(result, name)) + g_clear_object(&result); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : space = instance d'espace de noms à initialiser. * +* name = désignation du futur espace de noms. * +* * +* Description : Met en place un nouvel espace de noms pour scan. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_namespace_create(GScanNamespace *space, const char *name) +{ + bool result; /* Bilan à retourner */ + + result = true; + + if (name != NULL) + space->name = strdup(name); + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : space = espace de noms à compléter. * +* child = élément d'évaluation à intégrer. * +* * +* Description : Intègre un nouvel élément dans l'espace de noms. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_scan_namespace_register_item(GScanNamespace *space, GScanRegisteredItem *child) +{ + bool result; /* Bilan à retourner */ + char *name; /* Nom de l'élément à ajouter */ + size_t i; /* Boucle de parcours */ + + name = g_scan_registered_item_get_name(child); + + /* Validation de l'unicité du nom */ + + for (i = 0; i < space->count; i++) + if (strcmp(name, space->names[i]) == 0) + break; + + result = (i == space->count); + + /* Inscription de l'élément ? */ + + if (!result) + free(name); + + else + { + space->count++; + + space->children = realloc(space->children, space->count * sizeof(GScanRegisteredItem *)); + space->children[space->count - 1] = child; + g_object_ref(G_OBJECT(child)); + + space->names = realloc(space->names, space->count * sizeof(char *)); + space->names[space->count - 1] = name; + + } + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : space = espace de noms à compléter. * +* count = nombre d'éléments exportés. [OUT] * +* * +* Description : Réalise l'inventaire d'un espace de noms. * +* * +* Retour : Liste d'éléments enregistrés. * +* * +* Remarques : - * +* * +******************************************************************************/ + +char **g_scan_namespace_explore(const GScanNamespace *space, size_t *count) +{ + char **result; /* Liste à retourner */ + size_t i; /* Boucle de parcours #1 */ + GScanRegisteredItem *child; /* Elément à considérer */ + char **sub_result; /* Sous-éléments obtenus */ + size_t sub_count; /* Quantité de ces éléments */ + size_t k; /* Boucle de parcours #2 */ + int ret; /* Bilan d'une construction */ + + result = NULL; + *count = 0; + + for (i = 0; i < space->count; i++) + { + child = space->children[i]; + + if (G_IS_SCAN_NAMESPACE(child)) + { + sub_result = g_scan_namespace_explore(G_SCAN_NAMESPACE(child), &sub_count); + + result = realloc(result, (*count + sub_count) * sizeof(char *)); + + for (k = 0; k < sub_count; k++) + { + if (space->name == NULL) + result[(*count)++] = sub_result[k]; + + else + { + ret = asprintf(&result[*count], "%s.%s", space->name, sub_result[k]); + + if (ret == -1) + { + LOG_ERROR_N("asprintf"); + result[*count] = sub_result[k]; + } + + else + free(sub_result[k]); + + (*count)++; + + } + + } + + if (sub_result != NULL) + free(sub_result); + + } + + else + { + result = realloc(result, (*count + 1) * sizeof(char *)); + + if (space->name == NULL) + result[(*count)++] = strdup(space->names[i]); + + else + { + ret = asprintf(&result[*count], "%s.%s", space->name, space->names[i]); + + if (ret == -1) + { + LOG_ERROR_N("asprintf"); + result[*count] = strdup(space->names[i]); + } + + (*count)++; + + } + + } + + } + + return result; + +} + + + +/* ---------------------------------------------------------------------------------- */ +/* IMPLEMENTATION DES FONCTIONS DE CLASSE */ +/* ---------------------------------------------------------------------------------- */ + + +/****************************************************************************** +* * +* Paramètres : space = élément d'appel à consulter. * +* * +* Description : Indique le nom associé à une expression d'évaluation. * +* * +* Retour : Désignation humaine de l'expression d'évaluation. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static char *g_scan_namespace_get_name(const GScanNamespace *space) +{ + char *result; /* Désignation à retourner */ + + if (space->name != NULL) + result = strdup(space->name); + + else + result = NULL; + + return result; + +} + + +/****************************************************************************** +* * +* Paramètres : item = élément d'appel à consulter. * +* target = désignation de l'objet d'appel à identifier. * +* ctx = contexte de suivi de l'analyse courante. * +* scope = portée courante des variables locales. * +* out = zone d'enregistrement de la résolution opérée. [OUT]* +* * +* Description : Lance une résolution d'élément à solliciter. * +* * +* Retour : Bilan de l'opération : false en cas d'erreur irrécupérable. * +* * +* Remarques : - * +* * +******************************************************************************/ + +static bool g_scan_namespace_resolve(GScanNamespace *item, const char *target, GScanContext *ctx, GScanScope *scope, GScanRegisteredItem **out) +{ + bool result; /* Bilan à retourner */ + size_t i; /* Boucle de parcours */ + + result = false; + + for (i = 0; i < item->count; i++) + if (strcmp(target, item->names[i]) == 0) + { + *out = item->children[i]; + g_object_ref(G_OBJECT(*out)); + + result = true; + break; + } + + return result; + +} diff --git a/src/analysis/scan/space.h b/src/analysis/scan/space.h new file mode 100644 index 0000000..1b998d8 --- /dev/null +++ b/src/analysis/scan/space.h @@ -0,0 +1,65 @@ + +/* Chrysalide - Outil d'analyse de fichiers binaires + * space.h - prototypes pour la définition d'un espace de noms pour les fonctions de scan + * + * Copyright (C) 2022 Cyrille Bagard + * + * This file is part of Chrysalide. + * + * Chrysalide is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Chrysalide is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Foobar. If not, see <http://www.gnu.org/licenses/>. + */ + + +#ifndef _ANALYSIS_SCAN_SPACE_H +#define _ANALYSIS_SCAN_SPACE_H + + +#include <glib-object.h> +#include <stdbool.h> + + +#include "item.h" + + + +#define G_TYPE_SCAN_NAMESPACE g_scan_namespace_get_type() +#define G_SCAN_NAMESPACE(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), G_TYPE_SCAN_NAMESPACE, GScanNamespace)) +#define G_IS_SCAN_NAMESPACE(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), G_TYPE_SCAN_NAMESPACE)) +#define G_SCAN_NAMESPACE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), G_TYPE_SCAN_NAMESPACE, GScanNamespaceClass)) +#define G_IS_SCAN_NAMESPACE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), G_TYPE_SCAN_NAMESPACE)) +#define G_SCAN_NAMESPACE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), G_TYPE_SCAN_NAMESPACE, GScanNamespaceClass)) + + +/* Espace de noms pour un groupe de fonctions (instance) */ +typedef struct _GScanNamespace GScanNamespace; + +/* Espace de noms pour un groupe de fonctions (classe) */ +typedef struct _GScanNamespaceClass GScanNamespaceClass; + + +/* Indique le type défini pour une définition d'espace de noms. */ +GType g_scan_namespace_get_type(void); + +/* Construit un nouvel espace de noms pour scan. */ +GScanNamespace *g_scan_namespace_new(const char *); + +/* Intègre un nouvel élément dans l'espace de noms. */ +bool g_scan_namespace_register_item(GScanNamespace *, GScanRegisteredItem *); + +/* Réalise l'inventaire d'un espace de noms. */ +char **g_scan_namespace_explore(const GScanNamespace *, size_t *); + + + +#endif /* _ANALYSIS_SCAN_SPACE_H */ diff --git a/src/analysis/scan/tokens.l b/src/analysis/scan/tokens.l new file mode 100644 index 0000000..e075cee --- /dev/null +++ b/src/analysis/scan/tokens.l @@ -0,0 +1,1236 @@ + +%top { + +#include "grammar.h" + +} + + +%{ + + +#include <assert.h> +#include <stdbool.h> +#include <stdlib.h> + + +/* Tête de lecture pour conversions */ +typedef union _read_ptr_t +{ + const uint8_t *byte_pos; /* Lecture par blocs de 8 bits */ + const uint16_t *hword_pos; /* Lecture par blocs de 16 bits*/ + +} read_ptr_t; + + +#if __BYTE_ORDER == __LITTLE_ENDIAN + +# define MAKE_HWORD(ch1, ch2) ((uint16_t)(ch2 << 8 | ch1)) + +#elif __BYTE_ORDER == __BIG_ENDIAN + +# define MAKE_HWORD(ch1, ch2) ((uint16_t)(ch1 << 8 | ch2)) + +#else + + /* __PDP_ENDIAN et Cie... */ +# error "Congratulations! Your byte order is not supported!" + +#endif + + + +/****************************************************************************** +* * +* Paramètres : src = liste d'octets à traiter. * +* len = taille de cette liste. * +* out = série d'octets bruts obtenue. [OUT] * +* * +* Description : Transcrit une série d'octets en en remplaçant certains. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void rost_unescape_string(const char *src, size_t len, sized_string_t *out) +{ + read_ptr_t reader; /* Tête de lecture */ + const bin_t *max; /* Fin du parcours */ + uint16_t half; /* Moitié de mot */ + bin_t byte; /* Octet à analyser */ + bin_t *writer; /* Tête d'écriture */ + + reader.byte_pos = (const uint8_t *)src; + max = reader.byte_pos + len; + + writer = out->bin_data; + + while (reader.byte_pos < max) + { + /** + * La lecture par groupes de deux octets n'est pas forcément toujours + * logique : pour "\nabc", la dernière lecture va considérer 'c"', + * incluant ainsi le caractère '"' qui a été écarté pour l'appel. + * + * Le code est cependant suffisamment souple pour ignore le superflu. + */ + switch (*reader.hword_pos) + { + case MAKE_HWORD('\\', 'a'): + reader.hword_pos++; + *writer++ = '\a'; + break; + + case MAKE_HWORD('\\', 'b'): + reader.hword_pos++; + *writer++ = '\b'; + break; + + case MAKE_HWORD('\\', 't'): + reader.hword_pos++; + *writer++ = '\t'; + break; + + case MAKE_HWORD('\\', 'n'): + reader.hword_pos++; + *writer++ = '\n'; + break; + + case MAKE_HWORD('\\', 'v'): + reader.hword_pos++; + *writer++ = '\v'; + break; + + case MAKE_HWORD('\\', 'f'): + reader.hword_pos++; + *writer++ = '\f'; + break; + + case MAKE_HWORD('\\', 'r'): + reader.hword_pos++; + *writer++ = '\r'; + break; + + case MAKE_HWORD('\\', 'e'): + reader.hword_pos++; + *writer++ = '\e'; + break; + + case MAKE_HWORD('\\', '"'): + reader.hword_pos++; + *writer++ = '\"'; + break; + + case MAKE_HWORD('\\', '\\'): + reader.hword_pos++; + *writer++ = '\\'; + break; + + case MAKE_HWORD('\\', 'x'): + reader.hword_pos++; + + /** + * Le jeu des expressions régulières qui amène à l'appel de + * cette fonction limite les caractères possibles à trois + * ensembles : chiffres et lettres en majuscules et minuscules. + * + * La bascule des lettres en minuscules ramène les possibles + * à deux ensembles uniquement, simplifiant ainsi les règles + * de filtrage : aucun switch case n'est ainsi requis ! + */ + + half = *reader.hword_pos++; + +#if __BYTE_ORDER == __LITTLE_ENDIAN + byte = (half & 0xff); +#elif __BYTE_ORDER == __BIG_ENDIAN + byte = (half >> 8); +#endif + + /* '0' ... '9' */ + if (byte <= '9') + *writer = (byte - '0'); + + /* 'A' ... 'F' || 'a' ... 'f' */ + else + { + byte |= 0x20; + *writer = 0xa + (byte - 'a'); + } + + *writer <<= 4; + +#if __BYTE_ORDER == __LITTLE_ENDIAN + byte = (half >> 8); +#elif __BYTE_ORDER == __BIG_ENDIAN + byte = (half & 0xff); +#endif + + /* '0' ... '9' */ + if (byte <= '9') + *writer++ |= (byte - '0'); + + /* 'A' ... 'F' || 'a' ... 'f' */ + else + { + byte |= 0x20; + *writer++ |= 0xa + (byte - 'a'); + } + + break; + + default: + *writer++ = *reader.byte_pos++; + break; + + } + + } + + out->len = writer - out->bin_data; + +} + + +/****************************************************************************** +* * +* Paramètres : src = liste d'octets à traiter. * +* len = taille de cette liste. * +* out = série d'octets bruts obtenue. [OUT] * +* * +* Description : Transcrit une série d'octets en en remplaçant certains. * +* * +* Retour : - * +* * +* Remarques : - * +* * +******************************************************************************/ + +static void rost_unescape_regex(const char *src, size_t len, sized_string_t *out) +{ + read_ptr_t reader; /* Tête de lecture */ + const bin_t *max; /* Fin du parcours */ + uint16_t half; /* Moitié de mot */ + bin_t byte; /* Octet à analyser */ + bin_t *writer; /* Tête d'écriture */ + + reader.byte_pos = (const uint8_t *)src; + max = reader.byte_pos + len; + + writer = out->bin_data; + + while (reader.byte_pos < max) + { + /** + * La lecture par groupes de deux octets n'est pas forcément toujours + * logique : pour "\nabc", la dernière lecture va considérer 'c"', + * incluant ainsi le caractère '"' qui a été écarté pour l'appel. + * + * Le code est cependant suffisamment souple pour ignore le superflu. + */ + switch (*reader.hword_pos) + { + case MAKE_HWORD('\\', 'a'): + reader.hword_pos++; + *writer++ = '\a'; + break; + + case MAKE_HWORD('\\', 'b'): + reader.hword_pos++; + *writer++ = '\b'; + break; + + case MAKE_HWORD('\\', 't'): + reader.hword_pos++; + *writer++ = '\t'; + break; + + case MAKE_HWORD('\\', 'n'): + reader.hword_pos++; + *writer++ = '\n'; + break; + + case MAKE_HWORD('\\', 'v'): + reader.hword_pos++; + *writer++ = '\v'; + break; + + case MAKE_HWORD('\\', 'f'): + reader.hword_pos++; + *writer++ = '\f'; + break; + + case MAKE_HWORD('\\', 'r'): + reader.hword_pos++; + *writer++ = '\r'; + break; + + case MAKE_HWORD('\\', 'e'): + reader.hword_pos++; + *writer++ = '\e'; + break; + + case MAKE_HWORD('\\', '"'): + reader.hword_pos++; + *writer++ = '\"'; + break; + + case MAKE_HWORD('\\', '\\'): + reader.hword_pos++; + *writer++ = '\\'; + break; + + case MAKE_HWORD('\\', 'x'): + reader.hword_pos++; + + /** + * Le jeu des expressions régulières qui amène à l'appel de + * cette fonction limite les caractères possibles à trois + * ensembles : chiffres et lettres en majuscules et minuscules. + * + * La bascule des lettres en minuscules ramène les possibles + * à deux ensembles uniquement, simplifiant ainsi les règles + * de filtrage : aucun switch case n'est ainsi requis ! + */ + + half = *reader.hword_pos++; + +#if __BYTE_ORDER == __LITTLE_ENDIAN + byte = (half & 0xff); +#elif __BYTE_ORDER == __BIG_ENDIAN + byte = (half >> 8); +#endif + + /* '0' ... '9' */ + if (byte <= '9') + *writer = (byte - '0'); + + /* 'A' ... 'F' || 'a' ... 'f' */ + else + { + byte |= 0x20; + *writer = 0xa + (byte - 'a'); + } + + *writer <<= 4; + +#if __BYTE_ORDER == __LITTLE_ENDIAN + byte = (half >> 8); +#elif __BYTE_ORDER == __BIG_ENDIAN + byte = (half & 0xff); +#endif + + /* '0' ... '9' */ + if (byte <= '9') + *writer++ |= (byte - '0'); + + /* 'A' ... 'F' || 'a' ... 'f' */ + else + { + byte |= 0x20; + *writer++ |= 0xa + (byte - 'a'); + } + + break; + + case MAKE_HWORD('\\', '{'): + reader.hword_pos++; + *writer++ = '{'; + break; + + case MAKE_HWORD('\\', '}'): + reader.hword_pos++; + *writer++ = '}'; + break; + + default: + *writer++ = *reader.byte_pos++; + break; + + } + + } + + out->len = writer - out->bin_data; + +} + + +#define PUSH_STATE(s) yy_push_state(s, yyscanner) +#define POP_STATE yy_pop_state(yyscanner) + + +#define STOP_LEXER(msg, fbmsg) \ + do \ + { \ + char *__text; \ + int __ret; \ + __ret = asprintf(&__text, "%s: '%s'", msg, yytext); \ + if (__ret == -1) \ + YY_FATAL_ERROR(fbmsg); \ + else \ + { \ + YY_FATAL_ERROR(__text); \ + free(__text); \ + } \ + } \ + while (0) + +#define HANDLE_UNCOMPLETED_TOKEN \ + STOP_LEXER("Uncompleted token in rule definition", "Undisclosed uncompleted token in rule definition") + + +%} + + +%option bison-bridge reentrant +%option stack +%option nounput +%option noinput +%option noyywrap +%option noyy_top_state +%option yylineno +%option never-interactive + +%x inc_path + +%x rule_intro +%x raw_block + +%x meta +%x meta_value + +%x bytes +%x bytes_value +%x bytes_value_raw + +%x bytes_hex +%x bytes_hex_range + +%x bytes_regex +%x bytes_regex_quantifier +%x bytes_regex_range + +%x condition + +%x wait_for_colon + + +%x comment + + +str_not_escaped [^\"\\] +str_escaped \\a|\\b|\\t|\\n|\\v|\\f|\\r|\\e|\\\"|\\\\|\\x{hbyte} +str_mixed ({str_not_escaped}|{str_escaped}) + +hbyte [0-9a-fA-F]{2} +mbyte (\?[0-9a-fA-F]|[0-9a-fA-F]\?) + +reg_allowed [^^$.|/{}()\[\]*+?\\] +reg_allowed_escaped \\^|\\$|\\\.|\\\||\\\/|\\\{|\\\}|\\\(|\\\)|\\\[|\\\]|\\\*|\\\+|\\\?|\\\\ +reg_escaped \\a|\\t|\\n|\\v|\\f|\\r +reg_byte \\x[0-9a-fA-F]{2} + +regular_chars {reg_allowed}|{reg_allowed_escaped}|{reg_escaped}|{reg_byte} + +reg_classes \\w|\\W|\\s|\\S|\\d|\\D|\\b|\\B + + +bytes_id [A-Za-z_][A-Za-z0-9_]* +bytes_fuzzy_id [\*A-Za-z_][\*A-Za-z0-9_]* + + +%% + + +"include" { PUSH_STATE(inc_path); return INCLUDE; } + +<inc_path>\"{str_not_escaped}+\" { + POP_STATE; + + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 2; + + return PLAIN_TEXT; + } + +<inc_path>\"{str_mixed}+\" { + POP_STATE; + + rost_unescape_string(yytext + 1, yyleng - 2, tmp_0); + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; +#endif + + yylval->tmp_cstring = tmp_0; + + return ESCAPED_TEXT; + } + + +%{ /* Définition locale d'une règle */ %} + + "global" { return GLOBAL; } + "private" { return PRIVATE; } + + "rule" { + PUSH_STATE(rule_intro); + return RAW_RULE; + } + + <rule_intro>{bytes_id} { + yylval->sized_cstring.data = yytext; + yylval->sized_cstring.len = yyleng; + return RULE_IDENTIFIER; + } + + <rule_intro>":" { return COLON; } + + <rule_intro>[ \t]* { } + + <rule_intro>"{" { + POP_STATE; + PUSH_STATE(raw_block); + return BRACE_IN; + } + + <raw_block>"meta" { + POP_STATE; + PUSH_STATE(meta); + PUSH_STATE(wait_for_colon); + return META; + } + + <raw_block,meta>"bytes" { + POP_STATE; + PUSH_STATE(bytes); + PUSH_STATE(wait_for_colon); + return BYTES; + } + + <raw_block,meta,bytes>"condition" { + POP_STATE; + PUSH_STATE(condition); + PUSH_STATE(wait_for_colon); + return CONDITION; + } + + <wait_for_colon>":" { + POP_STATE; + return COLON; + } + +<raw_block,meta,bytes,condition>"}" { + POP_STATE; + return BRACE_OUT; + } + + +%{ /* Définitions communes pour la section "meta:" */ %} + + <meta>{bytes_id} { + yylval->sized_cstring.data = yytext; + yylval->sized_cstring.len = yyleng; + return INFO_KEY; + } + + <meta>"=" { PUSH_STATE(meta_value); return ASSIGN; } + + <meta_value>"true" { POP_STATE; return TRUE_; } + <meta_value>"false" { POP_STATE; return FALSE_; } + + <meta_value>-(0|[1-9][0-9]*) { + POP_STATE; + yylval->signed_integer = strtoll(yytext, NULL, 10); + return SIGNED_INTEGER; + } + + <meta_value>-0x[0-9a-f]+ { + POP_STATE; + yylval->signed_integer = strtoll(yytext, NULL, 16); + return SIGNED_INTEGER; + } + + <meta_value>(0|[1-9][0-9]*) { + POP_STATE; + yylval->unsigned_integer = strtoull(yytext, NULL, 10); + return UNSIGNED_INTEGER; + } + + <meta_value>0x[0-9a-f]+ { + POP_STATE; + yylval->unsigned_integer = strtoull(yytext, NULL, 16); + return UNSIGNED_INTEGER; + } + + <meta_value>\"{str_not_escaped}*\" { + POP_STATE; + + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 2; + + return PLAIN_TEXT; + } + + <meta_value>\"{str_mixed}*\" { + POP_STATE; + + rost_unescape_string(yytext + 1, yyleng - 2, tmp_0); + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; +#endif + + yylval->tmp_cstring = tmp_0; + + return ESCAPED_TEXT; + } + + +%{ /* A déplacer... */ %} + + +<condition>"true" { return TRUE_; } +<condition>"false" { return FALSE_; } + +<condition>-(0|[1-9][0-9]*) { yylval->signed_integer = strtoll(yytext, NULL, 10); return SIGNED_INTEGER; } +<condition>-0x[0-9a-f]+ { yylval->signed_integer = strtoll(yytext, NULL, 16); return SIGNED_INTEGER; } + +<bytes_hex_range,bytes_regex_quantifier,condition>(0|[1-9][0-9]*) { yylval->unsigned_integer = strtoull(yytext, NULL, 10); return UNSIGNED_INTEGER; } +<bytes_hex_range,bytes_regex_quantifier,condition>0x[0-9a-f]+ { yylval->unsigned_integer = strtoull(yytext, NULL, 16); return UNSIGNED_INTEGER; } + +<condition>[kK][bB] { return KB; } +<condition>[mM][bB] { return MB; } +<condition>[gG][bB] { return GB; } + +<condition>\"{str_not_escaped}*\" { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 2; + + return PLAIN_TEXT; + } + +<condition>\"{str_mixed}*\" { + rost_unescape_string(yytext + 1, yyleng - 2, tmp_0); + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; +#endif + + yylval->tmp_cstring = tmp_0; + + return ESCAPED_TEXT; + } + + +%{ /* Définitions communes pour la section "bytes:" */ %} + + <bytes>"fullword" { return FULLWORD; } + <bytes>"nocase" { return NOCASE; } + <bytes>"private" { return PRIVATE; } + + <bytes>"=" { PUSH_STATE(bytes_value); return ASSIGN; } + + +%{ /* Définition de motif en texte brut */ %} + +<bytes_value>\"{str_not_escaped}+\" { + POP_STATE; + + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 2; + + return PLAIN_TEXT; + } + +<bytes_value>\"{str_mixed}+\" { + POP_STATE; + + rost_unescape_string(yytext + 1, yyleng - 2, tmp_0); + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; +#endif + + yylval->tmp_cstring = tmp_0; + + return ESCAPED_TEXT; + } + + + +<bytes>[A-Za-z_][A-Za-z0-9_]* { + yylval->sized_cstring.data = yytext; + yylval->sized_cstring.len = yyleng; + return NAME; + } + + + <bytes>"((" { return MOD_GROUP_O; } + + <bytes>"))" { return MOD_GROUP_C; } + + <bytes>"(" { return PAREN_O; } + + <bytes>")" { return PAREN_C; } + + <bytes>"," { return COMMA; } + + +<bytes>\"{str_not_escaped}+\" { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 2; + + return PLAIN_TEXT; + } + + + + + +%{ /* Définition de motif en hexadécimal */ %} + + <bytes_value>"{" { + POP_STATE; + PUSH_STATE(bytes_hex); + } + + <bytes_hex>"}" { POP_STATE; } + + <bytes_hex>"[" { + PUSH_STATE(bytes_hex_range); + return HOOK_O; + } + + <bytes_hex_range>"-" { return MINUS; } + + <bytes_hex_range>"]" { + POP_STATE; + return HOOK_C; + } + + <bytes_hex>"(" { return PAREN_O; } + + <bytes_hex>")" { return PAREN_C; } + + <bytes_hex>"|" { return PIPE; } + + <bytes_hex>"~" { return TILDE; } + + <bytes_hex>{hbyte}([ ]*{hbyte})*[ ]* { + bool even; + size_t i; + bin_t byte; + bin_t value; + + tmp_0->len = 0; + + even = true; + + for (i = 0; i < yyleng; i++) + { + byte = yytext[i]; + + switch (byte) + { + case ' ': + continue; + break; + + case '0' ... '9': + value = (byte - '0'); + break; + + case 'A' ... 'F': + value = 0xa + (byte - 'A'); + break; + + case 'a' ... 'f': + value = 0xa + (byte - 'a'); + break; + + } + + if (even) + tmp_0->data[tmp_0->len] = (value << 4); + else + tmp_0->data[tmp_0->len++] |= value; + + even = !even; + + } + + assert(even); + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; +#endif + + yylval->tmp_cstring = tmp_0; + return HEX_BYTES; + + } + + <bytes_hex>[\?]{2}([ ]*[\?]{2})*[ ]* { + unsigned long long counter; + size_t i; + + counter = 0; + + for (i = 0; i < yyleng; i++) + if (yytext[i] == '?') + counter++; + + assert(counter % 2 == 0); + + yylval->unsigned_integer = counter / 2; + return FULL_MASK; + + } + + <bytes_hex>{mbyte}([ ]*{mbyte})*[ ]* { + bool even; + size_t i; + bin_t byte; + bin_t value; + + tmp_0->len = 0; + tmp_1->len = 0; + + even = true; + + for (i = 0; i < yyleng; i++) + { + byte = yytext[i]; + + switch (byte) + { + case ' ': + continue; + break; + + case '?': + even = !even; + continue; + break; + + case '0' ... '9': + value = (byte - '0'); + break; + + case 'A' ... 'F': + value = 0xa + (byte - 'A'); + break; + + case 'a' ... 'f': + value = 0xa + (byte - 'a'); + break; + + } + + if (even) + { + tmp_0->data[tmp_0->len++] = (value << 4); + tmp_1->data[tmp_1->len++] = 0xf0; + } + else + { + tmp_0->data[tmp_0->len++] = value; + tmp_1->data[tmp_1->len++] = 0x0f; + } + + even = !even; + + } + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; + tmp_1->data[tmp_1->len] = '\0'; +#endif + + yylval->masked.tmp_values = tmp_0; + yylval->masked.tmp_masks = tmp_1; + return SEMI_MASK; + + } + + +%{ /* Définition d'expressions régulières */ %} + + <bytes_value>"/" { + POP_STATE; + printf(" -- regex\n"); + PUSH_STATE(bytes_regex); + } + + <bytes_regex>"/" { printf("exit regex\n"); POP_STATE; } + + <bytes_regex>"." { return DOT; } + + <bytes_regex>({regular_chars})+ { + rost_unescape_regex(yytext, yyleng, tmp_0); + + printf(" regular: '%s'\n", yytext); + +#ifndef NDEBUG + /* Pour rendre plus lisibles les impressions de débogage */ + tmp_0->data[tmp_0->len] = '\0'; +#endif + + yylval->tmp_cstring = tmp_0; + return REGEX_BYTES; + + } + + <bytes_regex>({reg_classes})+ { + + return REGEX_CLASSES; + + } + +%{ /* <bytes_regex>\[({regular_chars}|({regular_chars})-z|{reg_classes})+\] { */ %} + + + <bytes_regex>"[" { + PUSH_STATE(bytes_regex_range); + printf(" !! entering range\n"); + return HOOK_O; + } + + <bytes_regex_range>"]" { + POP_STATE; + printf(" !! exiting range\n"); + return HOOK_C; + } + + + + +<bytes_regex_range>({regular_chars}|({regular_chars}-{regular_chars})|{reg_classes})+ { + + printf("range: '%s'\n", yytext); + return REGEX_RANGE; + + } + + <bytes_regex>"(" { return PAREN_O; } + + <bytes_regex>")" { return PAREN_C; } + + <bytes_regex>"|" { return PIPE; } + + <bytes_regex>"*" { return MUL; } + <bytes_regex>"+" { return PLUS; } + <bytes_regex>"?" { return QUESTION; } + + <bytes_regex>"{" { + PUSH_STATE(bytes_regex_quantifier); + return BRACE_IN; + } + + <bytes_regex_quantifier>"," { return COMMA; } + + <bytes_regex_quantifier>"}" { + POP_STATE; + return BRACE_OUT; + } + + +%{ /* Condition de correspondance */ %} + +<condition>"and" { return AND; } +<condition>"or" { return OR; } +<condition>"not" { return NOT; } + +<condition>"<" { return LT; } +<condition>"<=" { return LE; } +<condition>"==" { return EQ; } +<condition>"!=" { return NE; } +<condition>">" { return GT; } +<condition>">=" { return GE; } + +<condition>"contains" { return CONTAINS; } +<condition>"startswith" { return STARTSWITH; } +<condition>"endswith" { return ENDSWITH; } +<condition>"matches" { return MATCHES; } +<condition>"icontains" { return ICONTAINS; } +<condition>"istartswith" { return ISTARTSWITH; } +<condition>"iendswith" { return IENDSWITH; } +<condition>"iequals" { return IEQUALS; } + +<condition>"+" { return PLUS; } +<condition>"-" { return MINUS; } +<condition>"*" { return MUL; } +<condition>"/" { return DIV; } +<condition>"%" { return MOD; } + +<condition>"(" { return PAREN_O; } +<condition>")" { return PAREN_C; } +<condition>"," { return COMMA; } + + +<condition>"[" { return HOOK_O; } +<condition>"]" { return HOOK_C; } + + +<condition>"." { return DOT; } +<bytes>"|" { return PIPE; } + +<condition>"none" { return NONE; } +<condition>"any" { return ANY; } +<condition>"all" { return ALL; } +<condition>"of" { return OF; } +<condition>"them" { return THEM; } +<condition>"in" { return IN; } + + + <bytes,condition>${bytes_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_ID; + } + + <condition>${bytes_fuzzy_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_FUZZY_ID; + } + + <condition>#{bytes_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_ID_COUNTER; + } + + <condition>#{bytes_fuzzy_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_FUZZY_ID_COUNTER; + } + + <condition>@{bytes_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_ID_START; + } + + <condition>@{bytes_fuzzy_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_FUZZY_ID_START; + } + + <condition>!{bytes_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_ID_LENGTH; + } + + <condition>!{bytes_fuzzy_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_FUZZY_ID_LENGTH; + } + + <condition>~{bytes_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_ID_END; + } + + <condition>~{bytes_fuzzy_id} { + yylval->sized_cstring.data = yytext + 1; + yylval->sized_cstring.len = yyleng - 1; + return BYTES_FUZZY_ID_END; + } + + + + + + +<condition>[A-Za-z_][A-Za-z0-9_]* { + yylval->sized_cstring.data = yytext; + yylval->sized_cstring.len = yyleng; + return NAME; + } + + + + + + + +%{ /* Commentaires */ %} + +<*>"/*" { PUSH_STATE(comment); } +<comment>"*/" { POP_STATE; } +<comment>(.|\n) { } + +<*>"//"[^\n]* { } + + +%{ /* Suppression du besoin de sauvegardes pour retours en arrière */ %} + +"i" { HANDLE_UNCOMPLETED_TOKEN; } +"in" { HANDLE_UNCOMPLETED_TOKEN; } +"inc" { HANDLE_UNCOMPLETED_TOKEN; } +"incl" { HANDLE_UNCOMPLETED_TOKEN; } +"inclu" { HANDLE_UNCOMPLETED_TOKEN; } +"includ" { HANDLE_UNCOMPLETED_TOKEN; } + +<inc_path>\" { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"{str_not_escaped}+ { HANDLE_UNCOMPLETED_TOKEN; } + +<inc_path>\"\\ { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"\\x { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"{str_mixed}+ { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"{str_mixed}+\\ { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"{str_mixed}+\\x { HANDLE_UNCOMPLETED_TOKEN; } +<inc_path>\"{str_mixed}+\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + +"g" { HANDLE_UNCOMPLETED_TOKEN; } +"gl" { HANDLE_UNCOMPLETED_TOKEN; } +"glo" { HANDLE_UNCOMPLETED_TOKEN; } +"glob" { HANDLE_UNCOMPLETED_TOKEN; } +"globa" { HANDLE_UNCOMPLETED_TOKEN; } + +"p" { HANDLE_UNCOMPLETED_TOKEN; } +"pr" { HANDLE_UNCOMPLETED_TOKEN; } +"pri" { HANDLE_UNCOMPLETED_TOKEN; } +"priv" { HANDLE_UNCOMPLETED_TOKEN; } +"priva" { HANDLE_UNCOMPLETED_TOKEN; } +"privat" { HANDLE_UNCOMPLETED_TOKEN; } + +"r" { HANDLE_UNCOMPLETED_TOKEN; } +"ru" { HANDLE_UNCOMPLETED_TOKEN; } +"rul" { HANDLE_UNCOMPLETED_TOKEN; } + +<raw_block>"m" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block>"me" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block>"met" { HANDLE_UNCOMPLETED_TOKEN; } + +<raw_block,meta>"b" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta>"by" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta>"byt" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta>"byte" { HANDLE_UNCOMPLETED_TOKEN; } + +<raw_block,meta,bytes>"c" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"co" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"con" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"cond" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"condi" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"condit" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"conditi" { HANDLE_UNCOMPLETED_TOKEN; } +<raw_block,meta,bytes>"conditio" { HANDLE_UNCOMPLETED_TOKEN; } + + +<meta_value>"t" { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>"tr" { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>"tru" { HANDLE_UNCOMPLETED_TOKEN; } + +<meta_value>"f" { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>"fa" { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>"fal" { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>"fals" { HANDLE_UNCOMPLETED_TOKEN; } + +<meta_value>-0x { HANDLE_UNCOMPLETED_TOKEN; } + +<meta_value>0x { HANDLE_UNCOMPLETED_TOKEN; } + +<meta_value>\"{str_mixed}* { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>\"{str_mixed}*\\ { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>\"{str_mixed}*\\x { HANDLE_UNCOMPLETED_TOKEN; } +<meta_value>\"{str_mixed}*\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +<condition>-0x { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_hex_range,bytes_regex_quantifier,condition>0x { HANDLE_UNCOMPLETED_TOKEN; } + + +<condition>\"{str_not_escaped}* { HANDLE_UNCOMPLETED_TOKEN; } + +<condition>\" { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"\\ { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"\\x { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"{str_mixed}+ { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"{str_mixed}+\\ { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"{str_mixed}+\\x { HANDLE_UNCOMPLETED_TOKEN; } +<condition>\"{str_mixed}+\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_value>\" { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"\\ { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"\\x { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"{str_mixed}+ { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"{str_mixed}+\\ { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"{str_mixed}+\\x { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_value>\"{str_mixed}+\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes>\"{str_not_escaped}+ { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_hex>{hbyte}([ ]*{hbyte})*[ ]*[0-9a-fA-F]/[^?] { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_hex>[\?]{2}([ ]*[\?]{2})*[ ]*[\?]/[^0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_hex>{mbyte}([ ]*{mbyte})*[ ]*\?/[^?] { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_hex>{mbyte}([ ]*{mbyte})*[ ]*[0-9a-fA-F]/[^0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_regex>\\ { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex>\\x { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex>\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex>({regular_chars})+\\ { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex>({regular_chars})+\\x { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex>({regular_chars})+\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +<bytes_regex>({reg_classes})+\\ + + +<bytes_regex_range>({regular_chars}|({regular_chars}-{regular_chars})|{reg_classes})+\\ { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex_range>({regular_chars}|({regular_chars}-{regular_chars})|{reg_classes})+\\x { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex_range>({regular_chars}|({regular_chars}-{regular_chars})|{reg_classes})+\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex_range>\\x { HANDLE_UNCOMPLETED_TOKEN; } +<bytes_regex_range>\\x[0-9a-fA-F] { HANDLE_UNCOMPLETED_TOKEN; } + + +%{ /* Actions par défaut */ %} + +<*>[ \t]+ { } + +<*>[\n] { static int ln = 1; if (0) printf("----------- %%< -------------- %%< ---- %d\n", ln++); } + +<*>. { + char *msg; + int ret; + ret = asprintf(&msg, "Unhandled token in rule definition: '%s'", yytext); + if (ret == -1) + YY_FATAL_ERROR("Unhandled token in undisclosed rule definition"); + else + { + YY_FATAL_ERROR(msg); + free(msg); + } + } + + +%% diff --git a/src/analysis/storage/Makefile.am b/src/analysis/storage/Makefile.am index aee0faf..3eb287b 100644 --- a/src/analysis/storage/Makefile.am +++ b/src/analysis/storage/Makefile.am @@ -13,18 +13,9 @@ libanalysisstorage_la_SOURCES = \ storage.h storage.c \ tpmem.h tpmem.c -libanalysisstorage_la_LIBADD = - -libanalysisstorage_la_LDFLAGS = $(LIBSSL_LIBS) +libanalysisstorage_la_CFLAGS = $(TOOLKIT_CFLAGS) $(LIBXML_CFLAGS) devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysisstorage_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) $(LIBARCHIVE_CFLAGS) $(LIBSQLITE_CFLAGS) $(LIBSSL_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = diff --git a/src/analysis/storage/storage.c b/src/analysis/storage/storage.c index e286641..c641a52 100644 --- a/src/analysis/storage/storage.c +++ b/src/analysis/storage/storage.c @@ -28,6 +28,7 @@ #include <malloc.h> #include <string.h> #include <unistd.h> +#include <stdarg.h> #include "storage-int.h" @@ -702,6 +703,67 @@ GSerializableObject *g_object_storage_unpack_object(GObjectStorage *storage, con /****************************************************************************** * * +* Paramètres : storage = gestionnaire à manipuler. * +* name = désignation d'un nouveau groupe d'objets. * +* pbuf = zone tampon à parcourir. * +* expected = type d'objet attendu. * +* ... = élément restauré ou NULL en cas d'échec. [OUT] * +* * +* Description : Charge un objet interne à partir de données rassemblées. * +* * +* Retour : Bilan de l'opération. * +* * +* Remarques : - * +* * +******************************************************************************/ + +bool g_object_storage_unpack_object_2(GObjectStorage *storage, const char *name, packed_buffer_t *pbuf, GType expected, ...) +{ + bool result; /* Bilan d'une opération */ + uint64_t pos; /* Localisation des données */ + GSerializableObject *instance; /* Objet rechargé à valider */ + va_list ap; /* Liste d'arguments variables */ + void **object; /* Lieu d'enregistrement final */ + + result = extract_packed_buffer(pbuf, &pos, sizeof(uint64_t), true); + + if (result) + { + if (pos == 0) + *object = NULL; + + else + { + instance = g_object_storage_load_object(storage, name, pos); + + result = G_TYPE_CHECK_INSTANCE_TYPE(instance, expected); + + if (result) + { + va_start(ap, expected); + + object = va_arg(ap, void **); + + *object = instance; + + va_end(ap); + + } + + else + g_clear_object(&instance); + + } + + } + + return result; + +} + + +/****************************************************************************** +* * * Paramètres : storage = gestionnaire à manipuler. * * name = désignation d'un nouveau groupe d'objets. * * object = objet sérialisable à traiter. * @@ -787,10 +849,17 @@ bool g_object_storage_pack_object(GObjectStorage *storage, const char *name, con bool result; /* Bilan à retourner */ off64_t pos; /* Localisation des données */ - result = g_object_storage_store_object(storage, name, object, &pos); + if (object == NULL) + result = extend_packed_buffer(pbuf, (uint64_t []){ 0 }, sizeof(uint64_t), true); - if (result) - result = extend_packed_buffer(pbuf, (uint64_t []){ pos }, sizeof(uint64_t), true); + else + { + result = g_object_storage_store_object(storage, name, object, &pos); + + if (result) + result = extend_packed_buffer(pbuf, (uint64_t []){ pos }, sizeof(uint64_t), true); + + } return result; diff --git a/src/analysis/storage/storage.h b/src/analysis/storage/storage.h index 0d35d78..cc0caad 100644 --- a/src/analysis/storage/storage.h +++ b/src/analysis/storage/storage.h @@ -78,6 +78,9 @@ GSerializableObject *g_object_storage_unpack_object(GObjectStorage *, const char /* Sauvegarde un object sous forme de données rassemblées. */ bool g_object_storage_store_object(GObjectStorage *, const char *, const GSerializableObject *, off64_t *); +/* Charge un objet interne à partir de données rassemblées. */ +bool g_object_storage_unpack_object_2(GObjectStorage *, const char *, packed_buffer_t *, GType, ...); + /* Sauvegarde un object interne sous forme de données. */ bool g_object_storage_pack_object(GObjectStorage *, const char *, const GSerializableObject *, packed_buffer_t *); diff --git a/src/analysis/type-int.h b/src/analysis/type-int.h index 8999b19..5a804ab 100644 --- a/src/analysis/type-int.h +++ b/src/analysis/type-int.h @@ -88,7 +88,7 @@ struct _GDataType { GObject parent; /* A laisser en premier */ -#if __SIZEOF_INT__ == __SIZEOF_LONG__ +#if 1 //__SIZEOF_INT__ == __SIZEOF_LONG__ /** * L'inclusion des informations suivantes dépend de l'architecture. @@ -128,7 +128,7 @@ struct _GDataTypeClass * Accès aux informations éventuellement déportées. */ -#if __SIZEOF_INT__ == __SIZEOF_LONG__ +#if 1 //__SIZEOF_INT__ == __SIZEOF_LONG__ # define GET_DATA_TYPE_EXTRA(tp) (type_extra_data_t *)&tp->extra diff --git a/src/analysis/type.c b/src/analysis/type.c index f05b9a8..9ed5f3f 100644 --- a/src/analysis/type.c +++ b/src/analysis/type.c @@ -43,7 +43,7 @@ static void g_data_type_class_init(GDataTypeClass *); static void g_data_type_init(GDataType *); /* Procède à l'initialisation de l'interface de sérialisation. */ -static void g_serializable_object_interface_init(GSerializableObjectIface *); +static void g_data_type_serializable_interface_init(GSerializableObjectIface *); /* Supprime toutes les références externes. */ static void g_data_type_dispose(GDataType *); @@ -67,7 +67,7 @@ static bool g_data_type_store(const GDataType *, GObjectStorage *, packed_buffer /* Indique le type défini pour un type quelconque. */ G_DEFINE_TYPE_WITH_CODE(GDataType, g_data_type, G_TYPE_OBJECT, - G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_serializable_object_interface_init)); + G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_data_type_serializable_interface_init)); /****************************************************************************** @@ -136,7 +136,7 @@ static void g_data_type_init(GDataType *type) * * ******************************************************************************/ -static void g_serializable_object_interface_init(GSerializableObjectIface *iface) +static void g_data_type_serializable_interface_init(GSerializableObjectIface *iface) { iface->load = (load_serializable_object_cb)g_data_type_load; iface->store = (store_serializable_object_cb)g_data_type_store; diff --git a/src/analysis/types/Makefile.am b/src/analysis/types/Makefile.am index e3cbda0..bc6ff14 100644 --- a/src/analysis/types/Makefile.am +++ b/src/analysis/types/Makefile.am @@ -12,18 +12,9 @@ libanalysistypes_la_SOURCES = \ proto.h proto.c \ template.h template.c -libanalysistypes_la_LIBADD = - -libanalysistypes_la_LDFLAGS = +libanalysistypes_la_CFLAGS = $(TOOLKIT_CFLAGS) devdir = $(includedir)/chrysalide/$(subdir:src/%=core/%) dev_HEADERS = $(libanalysistypes_la_SOURCES:%c=) - - -AM_CPPFLAGS = $(LIBGTK_CFLAGS) $(LIBXML_CFLAGS) - -AM_CFLAGS = $(DEBUG_CFLAGS) $(WARNING_FLAGS) $(COMPLIANCE_FLAGS) - -SUBDIRS = |