summaryrefslogtreecommitdiff
path: root/plugins/ropgadgets/finder.c
blob: 98871b5468a028c5d28bdf84ba4dd3595b6acf89 (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

/* Chrysalide - Outil d'analyse de fichiers binaires
 * finder.c - recherche de gadgets pour ROP
 *
 * Copyright (C) 2015 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 "finder.h"


#include <string.h>


#include <core/processors.h>
#include <format/format.h>


#include <i18n.h>


#include "helper_arm.h"



/* Données utiles à transmettre */
typedef struct _search_domain
{
    GExeFormat *format;                     /* Format du fichier binaire   */
    GBinContent *content;                   /* Contenu associé récupéré    */
    GArchProcessor *proc;                   /* Processeur idéal en place   */
    GProcContext *ctx;                      /* Contexte de désassemblage   */

    mrange_t *exe_ranges;                   /* Liste de zones exécutables  */
    size_t exe_count;                       /* Nombre de ces zones         */

    phys_t sum;                             /* Surface totale à parcourir  */
    size_t runs_count;                      /* Nombre de passages à faire  */
    size_t runs_done;                       /* Nombre de passages effectués*/

} search_domain;


/* Désassemble rapidement une instruction. */
static GArchInstruction *disassemble_instruction_in_domain(const search_domain *, vmpa2t *);

/* Désassemble en amont d'une position autant que possible. */
static GArchInstruction *look_backward_for_gadgets(const search_domain *, const mrange_t *, const vmpa2t *, unsigned int);

/* Etablit une liste de tous les gadgets présents. */
static GArchInstruction **list_all_gadgets_in_domain(const search_domain *, unsigned int, update_search_progress_cb, GObject *, size_t *);



/******************************************************************************
*                                                                             *
*  Paramètres  : domain = ensemble d'auxiliaires à disposition.               *
*                pos    = tête de lecture pour le désassemblage.              *
*                                                                             *
*  Description : Désassemble rapidement une instruction.                      *
*                                                                             *
*  Retour      : Instruction créée ou NULL en cas d'échec.                    *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static GArchInstruction *disassemble_instruction_in_domain(const search_domain *domain, vmpa2t *pos)
{
    GArchInstruction *result;               /* Instruction à retourner     */
    GProcContext *ctx;                      /* Contexte de désassemblage   */

    ctx = domain->ctx;  /* TODO : copie */

    result = g_arch_processor_disassemble(domain->proc, ctx, domain->content, pos, domain->format);

    if (result != NULL)
    {
        g_arch_instruction_call_hook(result, IPH_LINK, domain->proc, ctx, domain->format);
        g_arch_instruction_call_hook(result, IPH_POST, domain->proc, ctx, domain->format);
    }

    //g_object_unref(G_OBJECT(ctx)); /* TODO */

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : domain    = ensemble d'auxiliaires à disposition.            *
*                exe_range = couverture globale dont il ne faut pas sortir.   *
*                ret       = point de retour final déjà trouvé.               *
*                max_depth = profondeur maximale des recherches.              *
*                                                                             *
*  Description : Désassemble en amont d'une position autant que possible.     *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static GArchInstruction *look_backward_for_gadgets(const search_domain *domain, const mrange_t *exe_range, const vmpa2t *ret, unsigned int max_depth)
{
    GArchInstruction *result;               /* Liste de gagdets trouvées   */
    const phys_t *ins_sizes;                /* Tailles potentielles        */
    size_t sizes_count;                     /* Quantité de tailles à tester*/
    vmpa2t last;                            /* Dernier point de départ     */
    unsigned int i;                         /* Boucle de parcours #1       */
    GArchInstruction *instr;                /* Elément de gadget trouvé    */
    size_t k;                               /* Boucle de parcours #2       */
    vmpa2t start;                           /* Point de départ courant     */
    vmpa2t end;                             /* Point d'arrivée obtenu      */
    phys_t diff;                            /* Volume de données traité    */
    mrange_t range;                         /* Couverture de l'instruction */

    result = NULL;

    ins_sizes = (phys_t []){ 2, 4 };    /* FIXME */
    sizes_count = 2;

    copy_vmpa(&last, ret);

    /* On parcours jusqu'à la profondeur maximale */
    for (i = 0; i < max_depth; i++)
    {
        instr = NULL;

        for (k = 0; k < sizes_count && instr == NULL; k++)
        {
            copy_vmpa(&start, &last);
            deminish_vmpa(&start, ins_sizes[k]);

            /* Est-on toujours dans les clous ? */
            if (!mrange_contains_addr(exe_range, &start)) break;

            copy_vmpa(&end, &start);

            instr = disassemble_instruction_in_domain(domain, &end);
            if (instr == NULL) continue;

            /* La jointure est-elle parfaite ? */

            if (cmp_vmpa(&end, &last) != 0)
            {
                g_object_unref(G_OBJECT(instr));
                instr = NULL;
                continue;
            }

            /* S'il s'agit d'un point de retour, on laisse la main à une autre liste */

            if (g_arch_instruction_get_flags(instr) & AIF_RETURN_POINT)
            {
                g_object_unref(G_OBJECT(instr));
                instr = NULL;
                continue;
            }

        }

        /* Aucune instruction n'a été trouvée à cette profondeur, on s'arrête donc */
        if (instr == NULL) break;

        copy_vmpa(&last, &start);

        diff = compute_vmpa_diff(&end, &start);

        init_mrange(&range, &start, diff);

        g_arch_instruction_set_range(instr, &range);


        g_arch_instruction_merge_lists(&result, &instr);

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : domain    = ensemble d'auxiliaires à disposition.            *
*                max_depth = profondeur maximale des recherches.              *
*                update    = fonction de suivi mise à disposition.            *
*                data      = données à associer à une phase d'actualisation.  *
*                count     = nombre de gadgets trouvés. [OUT]                 *
*                                                                             *
*  Description : Etablit une liste de tous les gadgets présents.              *
*                                                                             *
*  Retour      : Liste de listes d'instructions, à libérer après usage.       *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static GArchInstruction **list_all_gadgets_in_domain(const search_domain *domain, unsigned int max_depth, update_search_progress_cb update, GObject *data, size_t *count)
{
    GArchInstruction **result;              /* Liste de listes à renvoyer  */
    phys_t done;                            /* Accumulation des quantités  */
    size_t i;                               /* Boucle de parcours #1       */
    phys_t max;                             /* Borne d'un parcours         */
    phys_t k;                               /* Boucle de parcours #2       */
    gdouble fraction;                       /* Progression générale        */
    vmpa2t ret;                             /* Emplacement du retour       */
    vmpa2t tmp;                             /* Copie de travail modifiable */
    GArchInstruction *gadget;               /* Nouveau gadget détecté      */
    phys_t diff;                            /* Volume de données traité    */
    mrange_t ins_range;                     /* Emplacement d'une instruct° */
    vmpa2t end;                             /* Point d'arrivée obtenu      */
    GArchInstruction *new;                  /* Nouvelle liste de gadgets   */

    result = NULL;
    *count = 0;

    done = 0;

    for (i = 0; i < domain->exe_count; i++)
    {
        max = get_mrange_length(&domain->exe_ranges[i]);

        for (k = 0; k < max; k++)
        {
            /* Affichage de la progression */

            fraction = 1.0 * (domain->runs_done * domain->sum + done + k);
            fraction /= (domain->runs_count * domain->sum);

            update(data, fraction);

            /* Réception de la première / dernière instruction */

            copy_vmpa(&ret, get_mrange_addr(&domain->exe_ranges[i]));
            advance_vmpa(&ret, k);

            copy_vmpa(&tmp, &ret);

            gadget = disassemble_instruction_in_domain(domain, &tmp);
            if (gadget == NULL) continue;

            /* A-t-on bien affaire à une instruction de retour ? */

            if (!(g_arch_instruction_get_flags(gadget) & AIF_RETURN_POINT))
            {
                g_object_unref(G_OBJECT(gadget));
                continue;
            }

            /* Ne déborde-t-on pas dans une zone voisine ? */

            diff = compute_vmpa_diff(&ret, &tmp);
            init_mrange(&ins_range, &ret, diff);

            compute_mrange_end_addr(&ins_range, &end);

            if (!mrange_contains_mrange(&domain->exe_ranges[i], &ins_range))
            {
                g_object_unref(G_OBJECT(gadget));
                continue;
            }

            /* Ajout d'un nouvel ensemble de gadgets */

            g_arch_instruction_set_range(gadget, &ins_range);

            //printf(" ROP @ 0x%08x / 0x%08x\n", gadget->range.addr.virtual, ret.virtual);

            new = look_backward_for_gadgets(domain, &domain->exe_ranges[i], &ret, max_depth);

            g_arch_instruction_merge_lists(&new, &gadget);

            result = (GArchInstruction **)realloc(result, ++(*count) * sizeof(GArchInstruction *));
            result[*count - 1] = new;

        }

        done += max;

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary    = binaire dont le contenu est à traiter.           *
*                max_depth = profondeur maximale des recherches.              *
*                update    = fonction de suivi mise à disposition.            *
*                data      = données à associer à une phase d'actualisation.  *
*                count     = nombre de gadgets trouvés. [OUT]                 *
*                                                                             *
*  Description : Etablit une liste de tous les gadgets présents.              *
*                                                                             *
*  Retour      : Liste de listes d'instructions, à libérer après usage.       *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

found_rop_list *list_all_gadgets(GExeFormat *format, unsigned int max_depth, update_search_progress_cb update, GObject *data, size_t *count)
{
    found_rop_list *result;                 /* Liste de listes à renvoyer  */
    const char *target;                     /* Sous-traitance requise      */
    search_domain domain;                   /* Outils pour la recherche    */
    GBinPortion *portions;                  /* Couche première de portions */
    GProcContext **contexts;                /* Contextes pour recherches   */
    char **names;                           /* Désignations humaines liées */
    size_t i;                               /* Boucle de parcours          */

    /* Constitution du socle commun */

    g_object_ref(G_OBJECT(format));
    domain.format = format;

    domain.content = g_binary_format_get_content(G_BIN_FORMAT(format));

    target = g_exe_format_get_target_machine(format);
    domain.proc = get_arch_processor_for_type(target);

    bool collect_x_ranges(GBinPortion *portion, GBinPortion *parent, BinaryPortionVisit visit, void *unused)
    {
        const mrange_t *range;

        if (visit == BPV_SHOW)
        {
            if (g_binary_portion_get_rights(portion) & PAC_EXEC)
            {
                range = g_binary_portion_get_range(portion);

                domain.exe_ranges = (mrange_t *)realloc(domain.exe_ranges, ++domain.exe_count * sizeof(mrange_t));
                copy_mrange(&domain.exe_ranges[domain.exe_count - 1], range);

            }

        }

        return true;

    }

    domain.exe_ranges = NULL;
    domain.exe_count = 0;

    portions = g_exe_format_get_portions(format);

    g_binary_portion_visit(portions, (visit_portion_fc)collect_x_ranges, NULL);

    g_object_unref(G_OBJECT(portions));

    /* Récupération des différents contextes */

    if (strcmp(target, "armv7") == 0)
        contexts = get_rop_contexts_for_arm(domain.proc, &names, count);

    else
    {
        contexts = (GProcContext **)calloc(1, sizeof(GProcContext *));
        names = (char **)calloc(1, sizeof(char *));
        *count = 1;

        contexts[0] = g_arch_processor_get_context(domain.proc);
        names[0] = _("all");

    }

    /* Calcul de la surface totale à parcourir */

    domain.sum = 0;

    for (i = 0; i < domain.exe_count; i++)
        domain.sum += get_mrange_length(&domain.exe_ranges[i]);

    /* Détermination des différents parcours */

    domain.runs_count = *count;

    domain.runs_done = 0;

    /* Parcours des différentes surfaces */

    result = (found_rop_list *)calloc(*count, sizeof(found_rop_list));

    for (i = 0; i < *count; i++)
    {
        result[i].category = names[i];

        domain.ctx = contexts[i];

        result[i].gadgets = list_all_gadgets_in_domain(&domain, max_depth, update, data, &result[i].count);

        g_object_unref(G_OBJECT(domain.ctx));

        domain.runs_done++;

    }

    free(names);
    free(contexts);

    free(domain.exe_ranges);

    g_object_unref(G_OBJECT(domain.proc));
    g_object_unref(G_OBJECT(domain.content));
    g_object_unref(G_OBJECT(domain.format));

    return result;

}