/* Chrysalide - Outil d'analyse de fichiers binaires * client.c - connexion à un serveur Chrysalide * * Copyright (C) 2014-2017 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 . */ #include "client.h" #include #include #include #include #include #include #include #include #include "keymgn.h" #include "protocol.h" #include "misc/rlestr.h" #include "../../common/io.h" #include "../../common/xdg.h" #include "../../gui/panels/log.h" /* Description de client à l'écoute (instance) */ struct _GDbClient { GObject parent; /* A laisser en premier */ char *author; /* Utilisateur représenté */ char *key_file; /* Accès sa la clef privée */ const char *name; /* Désignation du binaire */ rle_string hash; /* Empreinte du binaire lié */ GList *collections; /* Collections d'un binaire */ int fd; /* Canal de communication */ GMutex sending_lock; /* Concurrence des envois */ GThread *update; /* Procédure de traitement */ }; /* Description de client à l'écoute (classe) */ struct _GDbClientClass { GObjectClass parent; /* A laisser en premier */ }; /* Initialise la classe des descriptions de fichier binaire. */ static void g_db_client_class_init(GDbClientClass *); /* Initialise une description de fichier binaire. */ static void g_db_client_init(GDbClient *); /* Procède à la libération totale de la mémoire. */ static void g_db_client_finalize(GDbClient *); /* Démarre réellement la connexion à la base de données. */ static bool g_db_client_start_common(GDbClient *, const char *); /* Assure l'accueil des nouvelles mises à jour. */ static void *g_db_client_update(GDbClient *); /* Indique le type défini pour une description de client à l'écoute. */ G_DEFINE_TYPE(GDbClient, g_db_client, G_TYPE_OBJECT); /****************************************************************************** * * * Paramètres : klass = classe à initialiser. * * * * Description : Initialise la classe des descriptions de fichier binaire. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ static void g_db_client_class_init(GDbClientClass *klass) { GObjectClass *object; /* Autre version de la classe */ object = G_OBJECT_CLASS(klass); object->finalize = (GObjectFinalizeFunc)g_db_client_finalize; } /****************************************************************************** * * * Paramètres : client = instance à initialiser. * * * * Description : Initialise une description de fichier binaire. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ static void g_db_client_init(GDbClient *client) { client->fd = -1; } /****************************************************************************** * * * Paramètres : client = instance d'objet GLib à traiter. * * * * Description : Procède à la libération totale de la mémoire. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ static void g_db_client_finalize(GDbClient *client) { free(client->author); free(client->key_file); unset_rle_string(&client->hash); G_OBJECT_CLASS(g_db_client_parent_class)->finalize(G_OBJECT(client)); } /****************************************************************************** * * * Paramètres : author = utilisateur à représenter via le client. * * kfile = clef menant à sa clef privée. * * name = désignation humaine du binaire associé. * * hash = empreinte d'un binaire en cours d'analyse. * * collections = ensemble de collections existantes. * * * * Description : Prépare un client pour une connexion à une BD. * * * * Retour : Structure mise en place ou NULL en cas d'échec. * * * * Remarques : - * * * ******************************************************************************/ GDbClient *g_db_client_new(char *author, char *kfile, const char *name, const char *hash, GList *collections) { GDbClient *result; /* Adresse à retourner */ result = g_object_new(G_TYPE_DB_CLIENT, NULL); result->author = author; result->key_file = kfile; result->name = name; init_static_rle_string(&result->hash, hash); result->collections = collections; return result; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * * * Description : Démarre la connexion à la base de données interne. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ bool g_db_client_start_internal(GDbClient *client) { char *suffix; /* Suffixe pour un fichier */ char *sock_path; /* Chemin vers le canal UNIX */ struct sockaddr_un addr; /* Adresse de transmission */ int ret; /* Bilan d'un appel */ char *desc; /* Description du serveur ciblé*/ bool status; /* Bilan de la connexion */ /* Identification du serveur à contacter */ asprintf(&suffix, "chrysalide" G_DIR_SEPARATOR_S ".internal_server.%d", getpid()); sock_path = get_xdg_config_dir(suffix); free(suffix); memset(&addr, 0, sizeof(struct sockaddr_un)); #define UNIX_PATH_MAX 108 addr.sun_family = AF_UNIX; strncpy(addr.sun_path, sock_path, UNIX_PATH_MAX - 1); free(sock_path); /* Création d'un canal de communication */ client->fd = socket(AF_UNIX, SOCK_STREAM, 0); if (client->fd == -1) { perror("socket"); return false; } ret = connect(client->fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)); if (ret == -1) { perror("connect"); goto gdcsi_no_listening; } asprintf(&desc, "unix://.internal_server.%d", getpid()); status = g_db_client_start_common(client, desc); free(desc); if (!status) goto gdcsi_no_listening; return true; gdcsi_no_listening: close(client->fd); client->fd = -1; return false; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * host = hôte à représenter pour le service. * * port = port de connexion pour les clients. * * * * Description : Démarre la connexion à la base de données distante. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ bool g_db_client_start_remote(GDbClient *client, const char *host, unsigned short port) { struct hostent *hp; /* Informations sur l'hôte */ struct sockaddr_in addr; /* Adresse de transmission */ int ret; /* Bilan d'un appel */ char *desc; /* Description du serveur ciblé*/ bool status; /* Bilan de la connexion */ /* Identification du serveur à contacter */ hp = gethostbyname(host); if (hp == NULL) return false; addr.sin_family = hp->h_addrtype; memcpy(&addr.sin_addr, hp->h_addr_list[0], sizeof(struct in_addr)); addr.sin_port = htons(port); /* Création d'un canal de communication */ client->fd = socket(AF_INET, SOCK_STREAM, 0); if (client->fd == -1) { perror("socket"); return false; } ret = connect(client->fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); if (ret == -1) { perror("connect"); goto gdcsr_no_listening; } asprintf(&desc, "%s:%hu", host, port); status = g_db_client_start_common(client, desc); free(desc); if (!status) goto gdcsr_no_listening; return true; gdcsr_no_listening: close(client->fd); client->fd = -1; return false; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * host = hôte à représenter pour le service. * * port = port de connexion pour les clients. * * * * Description : Démarre réellement la connexion à la base de données. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ static bool g_db_client_start_common(GDbClient *client, const char *desc) { packed_buffer out_pbuf; /* Tampon d'émission */ bool status; /* Bilan d'une opération */ rle_string user; /* Nom d'utilisateur associé */ GChecksum *checksum; /* Empreinte MD5 à signer */ unsigned char md5_digest[16]; /* Empreinte MD5 calculée */ RSA *key; /* Clef pour la signature */ unsigned char sig[RSA_USED_SIZE]; /* Signature effectuée */ packed_buffer in_pbuf; /* Tampon de réception */ uint32_t data; /* Mot de données lues */ DBError error; /* Validation de la connexion */ /** * On réalise l'envoi initial ; le premier paquet doit contenir : * - la commande 'DBC_HELO'. * - le numéro de version du client. * - l'empreinte du binaire analysé. * - l'identifiant de l'utilisateur effectuant des modifications. * - la signature de l'empreinte MD5 de l'identifiant. * * Tout ceci est à synchroniser avec la fonction g_db_server_listener(). */ init_packed_buffer(&out_pbuf); status = extend_packed_buffer(&out_pbuf, (uint32_t []) { DBC_HELO }, sizeof(uint32_t), true); if (!status) goto gdcs_error; status = extend_packed_buffer(&out_pbuf, (uint32_t []) { CDB_PROTOCOL_VERSION }, sizeof(uint32_t), true); if (!status) goto gdcs_error; status = pack_rle_string(&client->hash, &out_pbuf); if (!status) goto gdcs_error; dup_into_rle_string(&user, client->author); /* FIXME : src ? */ status = pack_rle_string(&user, &out_pbuf); if (!status) goto gdcs_error; checksum = g_checksum_new(G_CHECKSUM_MD5); g_checksum_update(checksum, (guchar *)get_rle_string(&user), get_rle_length(&user)); g_checksum_get_digest(checksum, (guint8 *)md5_digest, (gsize []) { sizeof(md5_digest) }); g_checksum_free(checksum); key = load_rsa_key(client->key_file, true); if (key == NULL) goto gdcs_error; if (!sign_md5_hash(key, md5_digest, sig)) goto gdcs_error; RSA_free(key); status = extend_packed_buffer(&out_pbuf, sig, RSA_USED_SIZE, false); if (!status) goto gdcs_error; status = send_packed_buffer(&out_pbuf, client->fd); if (!status) goto gdcs_error; /** * Le serveur doit répondre pour un message type : * - la commande 'DBC_WELCOME'. * - un identifiant d'erreur ('DBE_NONE', 'DBE_BAD_EXCHANGE' * ou 'DBE_WRONG_VERSION' ... 'DBE_LOADING_ERROR'). */ status = recv_packed_buffer(&in_pbuf, client->fd); if (!status) goto gdsc_error; status = extract_packed_buffer(&in_pbuf, &data, sizeof(uint32_t), true); if (!status) goto gdsc_error; if (data != DBC_WELCOME) { log_variadic_message(LMT_ERROR, _("The server '%s' did not welcome us!"), desc); goto gdsc_error; } status = extract_packed_buffer(&in_pbuf, &data, sizeof(uint32_t), true); if (!status) goto gdsc_error; error = data; switch (error) { case DBE_NONE: log_variadic_message(LMT_INFO, _("Connected to the server '%s'!"), desc); break; case DBE_WRONG_VERSION: log_variadic_message(LMT_ERROR, _("The server '%s' does not use our protocol version (0x%08x)..."), desc, CDB_PROTOCOL_VERSION); goto gdsc_error; break; case DBE_XML_VERSION_ERROR: log_variadic_message(LMT_ERROR, _("The archive from the server '%s' does not use our protocol version (0x%08x)..."), desc, CDB_PROTOCOL_VERSION); goto gdsc_error; break; case DBE_DB_LOADING_ERROR: log_variadic_message(LMT_ERROR, _("The server '%s' got into troubles while loading the database...."), desc); goto gdsc_error; break; default: log_variadic_message(LMT_ERROR, _("The server '%s' has run into an error (%u)..."), desc, error); goto gdsc_error; break; } client->update = g_thread_try_new("cdb_client", (GThreadFunc)g_db_client_update, client, NULL); if (client->update == NULL) { log_variadic_message(LMT_ERROR, _("Failed to start a listening thread for the server '%s'!"), desc); goto gdsc_error; } exit_packed_buffer(&out_pbuf); exit_packed_buffer(&in_pbuf); return true; gdsc_error: exit_packed_buffer(&in_pbuf); gdcs_error: exit_packed_buffer(&out_pbuf); unset_rle_string(&user); close(client->fd); client->fd = -1; return false; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * * * Description : Assure l'accueil des nouvelles mises à jour. * * * * Retour : NULL. * * * * Remarques : - * * * ******************************************************************************/ static void *g_db_client_update(GDbClient *client) { struct pollfd fds; /* Surveillance des flux */ int ret; /* Bilan d'un appel */ packed_buffer in_pbuf; /* Tampon de réception */ uint32_t tmp32; /* Valeur sur 32 bits */ bool status; /* Bilan d'une opération */ uint32_t command; /* Commande de la requête */ DBError error; /* Bilan d'une commande passée */ GDbCollection *collec; /* Collection visée au final */ fds.fd = client->fd; fds.events = POLLIN | POLLPRI; while (1) { ret = poll(&fds, 1, -1); if (ret != 1) continue; printf("fds.revents :: %x\n", fds.revents); /* Le canal est fermé, une sortie doit être demandée... */ if (fds.revents & POLLNVAL) break; if (fds.revents & (POLLIN | POLLPRI)) { status = recv_packed_buffer(&in_pbuf, fds.fd); if (!status) goto gdcu_bad_exchange; status = extract_packed_buffer(&in_pbuf, &command, sizeof(uint32_t), true); if (!status) goto gdcu_bad_exchange; switch (command) { case DBC_SAVE: status = extract_packed_buffer(&in_pbuf, &tmp32, sizeof(uint32_t), true); if (!status) goto gdcu_bad_exchange; error = tmp32; if (error == DBE_NONE) log_variadic_message(LMT_INFO, _("Archive saved for binary '%s'"), client->name); else log_variadic_message(LMT_ERROR, _("Failed to save the archive for binary '%s'"), client->name); break; case DBC_COLLECTION: status = extract_packed_buffer(&in_pbuf, &tmp32, sizeof(uint32_t), true); if (!status) goto gdcu_bad_exchange; collec = find_collection_in_list(client->collections, tmp32); if (collec == NULL) goto gdcu_bad_exchange; status = g_db_collection_unpack(collec, &in_pbuf, NULL); if (!status) goto gdcu_bad_exchange; printf("## CLIENT ## Got Something to read...\n"); break; } exit_packed_buffer(&in_pbuf); continue; gdcu_bad_exchange: printf("Bad reception...\n"); exit_packed_buffer(&in_pbuf); /* TODO : close conn */ ; } } //g_db_client_stop(client); return NULL; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * * * Description : Arrête la connexion à la base de données. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ void g_db_client_stop(GDbClient *client) { if (client->fd != -1) return; close(client->fd); client->fd = -1; g_thread_join(client->update); } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * * * Description : Identifie le canal de communication pour envois au serveur. * * * * Retour : Descripteur de flux normalement ouvert. * * * * Remarques : - * * * ******************************************************************************/ int g_db_client_get_fd(GDbClient *client) { g_mutex_lock(&client->sending_lock); return client->fd; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * * * Description : Marque le canal de communication comme disponible. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ void g_db_client_put_fd(GDbClient *client) { g_mutex_unlock(&client->sending_lock); } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * * * Description : Effectue une demande de sauvegarde de l'état courant. * * * * Retour : true si la commande a bien été envoyée, false sinon. * * * * Remarques : - * * * ******************************************************************************/ bool g_db_client_save(GDbClient *client) { bool result; /* Bilan partiel à remonter */ g_db_client_get_fd(client); result = safe_send(client->fd, (uint32_t []) { htobe32(DBC_SAVE) }, sizeof(uint32_t), 0); g_db_client_put_fd(client); return result; } /****************************************************************************** * * * Paramètres : client = client pour les accès distants à manipuler. * * timestamp = date du dernier élément à garder comme actif. * * * * Description : Active les éléments en amont d'un horodatage donné. * * * * Retour : true si la commande a bien été envoyée, false sinon. * * * * Remarques : - * * * ******************************************************************************/ bool g_db_client_set_last_active(GDbClient *client, timestamp_t timestamp) { bool result; /* Bilan partiel à remonter */ packed_buffer out_pbuf; /* Tampon d'émission */ init_packed_buffer(&out_pbuf); g_db_client_get_fd(client); result = extend_packed_buffer(&out_pbuf, (uint32_t []) { DBC_SET_LAST_ACTIVE }, sizeof(uint32_t), true); if (result) result = pack_timestamp(×tamp, &out_pbuf); g_db_client_put_fd(client); if (result) result = send_packed_buffer(&out_pbuf, client->fd); exit_packed_buffer(&out_pbuf); return result; }