summaryrefslogtreecommitdiff
path: root/src/analysis/db/client.c
blob: 769eab7f2878e4ae6a5f81ecb55f5a2dc2ca02de (plain)
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

/* 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 <http://www.gnu.org/licenses/>.
 */


#include "client.h"


#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>


#include <i18n.h>


#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(&timestamp, &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;

}