вторник, 19 ноября 2013 г.

Добавление крайней секции в PE файл

Техника добавления крайней секции в PE файлы. Демонстрируются следующие фитчи:
- Добавление последней секции и внесение в неё данных из файла
- Пересчёт PE checksum (IMAGE_OPTIONAL_HEADER.Checksum)
- Сдвиг оверлея
- Сдвиг Bound Import заголовков
- Поддержка PE и PE+(x64)

TODO:
- Выравнивание согласно IMAGE_OPTIONAL_HEADER.FileAligment

  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
// --------------------------------------------------------------
// This is example, how to add section to PE file,
// supported PE and PE+(x86-64)
// by JKornev <c> http://k0rnev.blogspot.com
// --------------------------------------------------------------
#include <stdio.h>
#include <Windows.h>
#include <ImageHlp.h>

#pragma comment(lib, "ImageHlp")

#define NEW_SECTION_NAME ".new"
#define NEW_SECT_CHARACTERISTICS 0xC0000040

UINT Aligment(UINT size, UINT aligm_base)
{
    UINT new_size = size;
    if (size % aligm_base != 0) {
        new_size += aligm_base - (size % aligm_base);
    }
    return new_size;
}

void OutputSections(PIMAGE_SECTION_HEADER psect, int count)
{
    char name[IMAGE_SIZEOF_SHORT_NAME + 1] = {0};
    int i;

    for (i = 0; i < count; i++) {
        memcpy(name, psect[i].Name, IMAGE_SIZEOF_SHORT_NAME);
        printf(" %8s VA:0x%08X VS:0x%08X RA:0x%08X RS:0x%08X\n",
            name, psect[i].VirtualAddress, psect[i].Misc.VirtualSize,
            psect[i].PointerToRawData, psect[i].SizeOfRawData);
    }
}

DWORD MoveBoundImport(PVOID pbase, UINT base_size, DWORD lowbound, PIMAGE_DATA_DIRECTORY pdir, int move_dist)
{
    DWORD offset;

    if (!pdir->VirtualAddress || !move_dist) {
        return 0;
    }

    offset = (DWORD)((int)pdir->VirtualAddress + move_dist);//new offset pdir->VirtualAddress 
    if (lowbound > offset || offset + pdir->Size > base_size) {
        return 0;//overflow
    }

    //move bound block, recalculate offsets not need
    memmove((PVOID)((UINT)pbase + offset), (PVOID)((UINT)pbase + pdir->VirtualAddress), pdir->Size);

    return offset;
}

int main(int argc, char *argv[])
{
    enum { PE_DEFAULT_HEADER_SIZE = 0x400 };//usually PE header raw size is 0x400
    char *phead, *pdata, *poverl;
    HANDLE hfile, hfile2, hmap;
    DWORD pe_size, readed, written, offset, i, 
        data_size, overl_size, old_checksum, new_checksum;
    PIMAGE_DOS_HEADER pdos;
    PIMAGE_FILE_HEADER pimg;
    PIMAGE_SECTION_HEADER psect, pnew_sect;
    PIMAGE_OPTIONAL_HEADER32 popt32;
    PIMAGE_OPTIONAL_HEADER64 popt64;
    PIMAGE_DATA_DIRECTORY pdir;
    PIMAGE_NT_HEADERS32 pnt32;
    PIMAGE_NT_HEADERS64 pnt64;
    BOOL is_x64, have_checksum;
    PVOID pview;

    if (argc < 3) {
        printf("Error, incorrect arguments!\n"
            "Format: add.exe \"pe file name\" \"data file name\"\n");
        return 1;
    }

    // Read PE header
    phead = (char *)malloc(PE_DEFAULT_HEADER_SIZE);
    if (!phead) {
        printf("Error, can't allocate buffer!\n");
        return 1;
    }

    hfile = CreateFileA(argv[1], GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hfile == INVALID_HANDLE_VALUE) {
        printf("Error, can't open PE file '%s'!\n", argv[1]);
        return 1;
    }

    pe_size = GetFileSize(hfile, NULL);

    if (!ReadFile(hfile, phead, PE_DEFAULT_HEADER_SIZE, &readed, NULL)) {
        printf("Error, reading PE file failed!\n");
        return 1;
    }

    // Check DOS header
    offset = 0;
    pdos = (PIMAGE_DOS_HEADER)phead;
    if (pdos->e_magic != IMAGE_DOS_SIGNATURE) {
        printf("Error, '%s' isn't PE file!\n", argv[1]);
        return 1;
    }
    offset = pdos->e_lfanew + sizeof(DWORD)/*PE signature*/;

    pimg = (PIMAGE_FILE_HEADER)(phead + offset);
    offset += sizeof(IMAGE_FILE_HEADER);

    // Check architecture
    if (pimg->Machine == IMAGE_FILE_MACHINE_I386) {
        is_x64 = FALSE;
        popt32 = (PIMAGE_OPTIONAL_HEADER32)(phead + offset);
        offset += sizeof(IMAGE_OPTIONAL_HEADER32);
    } else if (pimg->Machine == IMAGE_FILE_MACHINE_AMD64) {
        is_x64 = TRUE;
        popt64 = (PIMAGE_OPTIONAL_HEADER64)(phead + offset);
        offset += sizeof(IMAGE_OPTIONAL_HEADER64);
    } else {
        printf("Error, architecture not supported!\n");
        return 1;
    }

    // Get section ptr
    psect = (PIMAGE_SECTION_HEADER)(phead + offset);
    offset += sizeof(IMAGE_SECTION_HEADER) * pimg->NumberOfSections;

    printf("Sections before:\n");
    OutputSections(psect, pimg->NumberOfSections);

    // Check bound import table and shift it if need
    if (is_x64) {
        pdir = &popt64->DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT];
    } else {
        pdir = &popt32->DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT];
    }
    if (pdir->VirtualAddress < offset + sizeof(IMAGE_SECTION_HEADER)) {//if need more space for new section header
        //try to move or disable bound import
        pdir->VirtualAddress = MoveBoundImport(phead, PE_DEFAULT_HEADER_SIZE, offset,
            pdir, offset + sizeof(IMAGE_SECTION_HEADER) - pdir->VirtualAddress);
        if (!pdir->VirtualAddress) {
            printf("Warning, can't move bound import table! Bound import disabled.\n");
            pdir->Size = 0;
        }
    }

    // Read data
    hfile2 = CreateFileA(argv[2], GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (hfile2 == INVALID_HANDLE_VALUE) {
        printf("Error, can't open data file '%s'!\n", argv[2]);
        return 1;
    }

    data_size = GetFileSize(hfile2, NULL);
    if (!data_size) {
        printf("Error, file '%s' is empty!\n", argv[2]);
        return 1;
    }

    pdata = (char *)malloc(data_size);
    if (!pdata) {
        printf("Error, can't allocate data buffer!\n");
        return 1;
    }

    if (!ReadFile(hfile2, pdata, data_size, &readed, NULL)) {
        printf("Error, reading data file failed!\n");
        return 1;
    }

    // Create new section header
    pnew_sect = &psect[pimg->NumberOfSections];
    memset(pnew_sect, 0, sizeof(IMAGE_SECTION_HEADER));
    memcpy(pnew_sect->Name, NEW_SECTION_NAME, strlen(NEW_SECTION_NAME));
    pnew_sect->Characteristics = NEW_SECT_CHARACTERISTICS;//rwi 
    pnew_sect->SizeOfRawData = data_size;
    if (is_x64) {
        pnew_sect->VirtualAddress = popt64->SizeOfImage;
        pnew_sect->Misc.VirtualSize = Aligment(data_size, popt64->SectionAlignment);
    } else {
        pnew_sect->VirtualAddress = popt32->SizeOfImage;
        pnew_sect->Misc.VirtualSize = Aligment(data_size, popt32->SectionAlignment);
    }
    for (i = 0; i < pimg->NumberOfSections; i++) {//search raw offset
        if (pnew_sect->PointerToRawData <= psect[i].PointerToRawData && psect[i].SizeOfRawData) {
            pnew_sect->PointerToRawData = psect[i].PointerToRawData + psect[i].SizeOfRawData;
        }
    }

    // Shift overlay
    overl_size = pe_size - pnew_sect->PointerToRawData;//calculate overlay size
    if (overl_size > 0) {
        poverl = (char *)malloc(overl_size);
        if (!poverl) {
            printf("Error, can't allocate temp buffer!\n");
            return 1;
        }

        SetFilePointer(hfile, pnew_sect->PointerToRawData, 0, FILE_BEGIN);
        if (!ReadFile(hfile, poverl, overl_size, &readed, NULL)) {
            printf("Error, reading overlay failed!\n");
            return 1;
        }

        SetFilePointer(hfile, pnew_sect->PointerToRawData + data_size, 0, FILE_BEGIN);
        if (!WriteFile(hfile, poverl, overl_size, &written, NULL)) {
            printf("Error, can't save overlay!\n");
            return 1;
        }
        free(poverl);
    }

    // Put data
    SetFilePointer(hfile, pnew_sect->PointerToRawData, 0, FILE_BEGIN);
    if (!WriteFile(hfile, pdata, data_size, &written, NULL)) {
        printf("Error, can't save new data!\n");
        return 1;
    }

    // Change header info
    pimg->NumberOfSections++;
    if (is_x64) {
        popt64->SizeOfImage = pnew_sect->VirtualAddress + pnew_sect->Misc.VirtualSize;
    } else {
        popt32->SizeOfImage = pnew_sect->VirtualAddress + pnew_sect->Misc.VirtualSize;
    }

    // Save header
    SetFilePointer(hfile, 0, 0, FILE_BEGIN);
    if (!WriteFile(hfile, phead, PE_DEFAULT_HEADER_SIZE, &written, NULL)) {
        printf("Error, can't save new header!\n");
        return 1;
    }
    FlushFileBuffers(hfile);

    // Recalculate checksum (optional feature)
    if (is_x64) {
        have_checksum = (popt64->CheckSum ? TRUE : FALSE);
    } else {
        have_checksum = (popt32->CheckSum ? TRUE : FALSE);
    }
    if (have_checksum) {
        hmap = CreateFileMapping(hfile, NULL, PAGE_READWRITE, 0, 0, NULL);
        pview = MapViewOfFile(hmap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
        if (pview) {
            if (is_x64) {
                if (pnt64 = (PIMAGE_NT_HEADERS64)CheckSumMappedFile(pview, pe_size + data_size, &old_checksum, &new_checksum)) {
                    pnt64->OptionalHeader.CheckSum = new_checksum;
                } else {
                    printf("Warning, can't recalc header checksum!\n");
                }
            } else {
                if (pnt32 = (PIMAGE_NT_HEADERS32)CheckSumMappedFile(pview, pe_size + data_size, &old_checksum, &new_checksum)) {
                    pnt32->OptionalHeader.CheckSum = new_checksum;
                } else {
                    printf("Warning, can't recalc header checksum!\n");
                }
            }
            UnmapViewOfFile(pview);
        } else {
            printf("Warning, can't recalc header checksum!\n");
        }
        if (hmap) {
            CloseHandle(hmap);
        }
    }

    printf("Sections after:\n");
    OutputSections(psect, pimg->NumberOfSections);
    printf("Operation successful!\n");

    free(phead);
    free(pdata);
    CloseHandle(hfile2);
    CloseHandle(hfile);

    return 0;
}

Комментариев нет:

Отправить комментарий