понедельник, 11 ноября 2013 г.

Расширение крайней секции PE файла

Пример техники расширения крайней секции исполняемого файла. Демонстрируются следующие фитчи:
- Растягивание последней секции и внесение в неё данных из файла
- Пересчёт PE checksum (IMAGE_OPTIONAL_HEADER.Checksum)
- Сдвиг оверлея
- Поддержка 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
// --------------------------------------------------------------
// This is example, how to inject data to the last PE section,
// supported PE and PE+(x64)
// by JKornev <c> http://k0rnev.blogspot.com
// --------------------------------------------------------------
#include <stdio.h>
#include <Windows.h>
#include <ImageHlp.h>

#pragma comment(lib, "ImageHlp")


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 OutputSection(PIMAGE_SECTION_HEADER psect)
{
    char name[IMAGE_SIZEOF_SHORT_NAME + 1] = {0};
    memcpy(name, psect->Name, IMAGE_SIZEOF_SHORT_NAME);
    printf(" Name:%s\n"
        " Virual adress: 0x%08X\n"
        " Virual size: 0x%08X\n"
        " Raw adress: 0x%08X\n"
        " Raw size: 0x%08X\n"
        " Characteristics: 0x%08X\n",
        name, psect->VirtualAddress, psect->Misc.VirtualSize, psect->PointerToRawData, 
        psect->SizeOfRawData, psect->Characteristics);
}

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 readed, written, offset, pe_size, data_size, overl_size, 
        roffset, old_checksum, new_checksum;
    PIMAGE_DOS_HEADER pdos;
    PIMAGE_FILE_HEADER pimg;
    PIMAGE_SECTION_HEADER psect;
    PIMAGE_OPTIONAL_HEADER32 popt32;
    PIMAGE_OPTIONAL_HEADER64 popt64;
    PIMAGE_NT_HEADERS32 pnt32;
    PIMAGE_NT_HEADERS64 pnt64;
    BOOL is_x64, have_checksum;
    PVOID pview;
    
    if (argc < 3) {
        printf("Error, incorrect arguments!\n"
            "Format: inject.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 pointer to the last section
    psect = (PIMAGE_SECTION_HEADER)(phead + offset);
    psect = &psect[pimg->NumberOfSections - 1];
    if (!psect->SizeOfRawData) {
        //maybe this section contains uninitialized data
        printf("Error, can't resize last section!\n");
        return 1;
    }

    printf("Resizable section, before:\n");
    OutputSection(psect);

    // Unset 'discardable' flag
    if (psect->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) {
        psect->Characteristics ^= IMAGE_SCN_MEM_DISCARDABLE;
    }

    // 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;
    }

    // Shift overlay
    roffset = psect->PointerToRawData + psect->SizeOfRawData;//raw(in file) offset to the end of last section data
    overl_size = pe_size - roffset;//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, roffset, 0, FILE_BEGIN);
        if (!ReadFile(hfile, poverl, overl_size, &readed, NULL)) {
            printf("Error, reading overlay failed!\n");
            return 1;
        }

        SetFilePointer(hfile, roffset + 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, roffset, 0, FILE_BEGIN);
    if (!WriteFile(hfile, pdata, data_size, &written, NULL)) {
        printf("Error, can't save new data!\n");
        return 1;
    }

    // Change header info
    psect->SizeOfRawData += data_size;
    if (psect->SizeOfRawData > psect->Misc.VirtualSize) {
        if (is_x64) {
            //change size of image
            popt64->SizeOfImage += Aligment(psect->SizeOfRawData, popt64->SectionAlignment) - Aligment(psect->Misc.VirtualSize, popt64->SectionAlignment);
            //change section virtual size
            psect->Misc.VirtualSize = Aligment(psect->SizeOfRawData, popt64->SectionAlignment);
        } else {
            popt32->SizeOfImage += Aligment(psect->SizeOfRawData, popt32->SectionAlignment) - Aligment(psect->Misc.VirtualSize, popt32->SectionAlignment);
            psect->Misc.VirtualSize = Aligment(psect->SizeOfRawData, popt32->SectionAlignment);
        }
    }

    // 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("\nResizable section, after:\n");
    OutputSection(psect);
    printf("Operation successful\n");

    free(pdata);
    free(phead);
    CloseHandle(hfile);
    CloseHandle(hfile2);
    return 0;
}

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

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