-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathfile.go
307 lines (261 loc) · 8.72 KB
/
file.go
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
// Copyright 2018 Saferwall. All rights reserved.
// Use of this source code is governed by Apache v2 license
// license that can be found in the LICENSE file.
package pe
import (
"errors"
"os"
mmap "github.com/edsrzf/mmap-go"
"github.com/saferwall/pe/log"
)
// A File represents an open PE file.
type File struct {
DOSHeader ImageDOSHeader `json:"dos_header,omitempty"`
RichHeader RichHeader `json:"rich_header,omitempty"`
NtHeader ImageNtHeader `json:"nt_header,omitempty"`
COFF COFF `json:"coff,omitempty"`
Sections []Section `json:"sections,omitempty"`
Imports []Import `json:"imports,omitempty"`
Export Export `json:"export,omitempty"`
Debugs []DebugEntry `json:"debugs,omitempty"`
Relocations []Relocation `json:"relocations,omitempty"`
Resources ResourceDirectory `json:"resources,omitempty"`
TLS TLSDirectory `json:"tls,omitempty"`
LoadConfig LoadConfig `json:"load_config,omitempty"`
Exceptions []Exception `json:"exceptions,omitempty"`
Certificates Certificate `json:"certificates,omitempty"`
DelayImports []DelayImport `json:"delay_imports,omitempty"`
BoundImports []BoundImportDescriptorData `json:"bound_imports,omitempty"`
GlobalPtr uint32 `json:"global_ptr,omitempty"`
CLR CLRData `json:"clr,omitempty"`
IAT []IATEntry `json:"iat,omitempty"`
Anomalies []string `json:"anomalies,omitempty"`
Header []byte
data mmap.MMap
FileInfo
size uint32
OverlayOffset int64
f *os.File
opts *Options
logger *log.Helper
}
// Options for Parsing
type Options struct {
// Parse only the PE header and do not parse data directories, by default (false).
Fast bool
// Includes section entropy, by default (false).
SectionEntropy bool
// Maximum COFF symbols to parse, by default (MaxDefaultCOFFSymbolsCount).
MaxCOFFSymbolsCount uint32
// Maximum relocations to parse, by default (MaxDefaultRelocEntriesCount).
MaxRelocEntriesCount uint32
// Disable certificate validation, by default (false).
DisableCertValidation bool
// A custom logger.
Logger log.Logger
}
// New instantiates a file instance with options given a file name.
func New(name string, opts *Options) (*File, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
// Memory map the file instead of using read/write.
data, err := mmap.Map(f, mmap.RDONLY, 0)
if err != nil {
f.Close()
return nil, err
}
file := File{}
if opts != nil {
file.opts = opts
} else {
file.opts = &Options{}
}
if file.opts.MaxCOFFSymbolsCount == 0 {
file.opts.MaxCOFFSymbolsCount = MaxDefaultCOFFSymbolsCount
}
if file.opts.MaxRelocEntriesCount == 0 {
file.opts.MaxRelocEntriesCount = MaxDefaultRelocEntriesCount
}
var logger log.Logger
if opts.Logger == nil {
logger = log.NewStdLogger(os.Stdout)
file.logger = log.NewHelper(log.NewFilter(logger,
log.FilterLevel(log.LevelError)))
} else {
file.logger = log.NewHelper(opts.Logger)
}
file.data = data
file.size = uint32(len(file.data))
file.f = f
return &file, nil
}
// NewBytes instantiates a file instance with options given a memory buffer.
func NewBytes(data []byte, opts *Options) (*File, error) {
file := File{}
if opts != nil {
file.opts = opts
} else {
file.opts = &Options{}
}
if file.opts.MaxCOFFSymbolsCount == 0 {
file.opts.MaxCOFFSymbolsCount = MaxDefaultCOFFSymbolsCount
}
if file.opts.MaxRelocEntriesCount == 0 {
file.opts.MaxRelocEntriesCount = MaxDefaultRelocEntriesCount
}
var logger log.Logger
if opts.Logger == nil {
logger = log.NewStdLogger(os.Stdout)
file.logger = log.NewHelper(log.NewFilter(logger,
log.FilterLevel(log.LevelError)))
} else {
file.logger = log.NewHelper(opts.Logger)
}
file.data = data
file.size = uint32(len(file.data))
return &file, nil
}
// Close closes the File.
func (pe *File) Close() error {
if pe.data != nil {
_ = pe.data.Unmap()
}
if pe.f != nil {
return pe.f.Close()
}
return nil
}
// Parse performs the file parsing for a PE binary.
func (pe *File) Parse() error {
// check for the smallest PE size.
if len(pe.data) < TinyPESize {
return ErrInvalidPESize
}
// Parse the DOS header.
err := pe.ParseDOSHeader()
if err != nil {
return err
}
// Parse the Rich header.
err = pe.ParseRichHeader()
if err != nil {
pe.logger.Errorf("rich header parsing failed: %v", err)
}
// Parse the NT header.
err = pe.ParseNTHeader()
if err != nil {
return err
}
// Parse COFF symbol table.
err = pe.ParseCOFFSymbolTable()
if err != nil {
pe.logger.Debugf("coff symbols parsing failed: %v", err)
}
// Parse the Section Header.
err = pe.ParseSectionHeader()
if err != nil {
return err
}
// In fast mode, do not parse data directories.
if pe.opts.Fast {
return nil
}
// Parse the Data Directory entries.
return pe.ParseDataDirectories()
}
// String stringify the data directory entry.
func (entry ImageDirectoryEntry) String() string {
dataDirMap := map[ImageDirectoryEntry]string{
ImageDirectoryEntryExport: "Export",
ImageDirectoryEntryImport: "Import",
ImageDirectoryEntryResource: "Resource",
ImageDirectoryEntryException: "Exception",
ImageDirectoryEntryCertificate: "Security",
ImageDirectoryEntryBaseReloc: "Relocation",
ImageDirectoryEntryDebug: "Debug",
ImageDirectoryEntryArchitecture: "Architecture",
ImageDirectoryEntryGlobalPtr: "GlobalPtr",
ImageDirectoryEntryTLS: "TLS",
ImageDirectoryEntryLoadConfig: "LoadConfig",
ImageDirectoryEntryBoundImport: "BoundImport",
ImageDirectoryEntryIAT: "IAT",
ImageDirectoryEntryDelayImport: "DelayImport",
ImageDirectoryEntryCLR: "CLR",
ImageDirectoryEntryReserved: "Reserved",
}
return dataDirMap[entry]
}
// ParseDataDirectories parses the data directories. The DataDirectory is an
// array of 16 structures. Each array entry has a predefined meaning for what
// it refers to.
func (pe *File) ParseDataDirectories() error {
foundErr := false
oh32 := ImageOptionalHeader32{}
oh64 := ImageOptionalHeader64{}
switch pe.Is64 {
case true:
oh64 = pe.NtHeader.OptionalHeader.(ImageOptionalHeader64)
case false:
oh32 = pe.NtHeader.OptionalHeader.(ImageOptionalHeader32)
}
// Maps data directory index to function which parses that directory.
funcMaps := map[ImageDirectoryEntry](func(uint32, uint32) error){
ImageDirectoryEntryExport: pe.parseExportDirectory,
ImageDirectoryEntryImport: pe.parseImportDirectory,
ImageDirectoryEntryResource: pe.parseResourceDirectory,
ImageDirectoryEntryException: pe.parseExceptionDirectory,
ImageDirectoryEntryCertificate: pe.parseSecurityDirectory,
ImageDirectoryEntryBaseReloc: pe.parseRelocDirectory,
ImageDirectoryEntryDebug: pe.parseDebugDirectory,
ImageDirectoryEntryArchitecture: pe.parseArchitectureDirectory,
ImageDirectoryEntryGlobalPtr: pe.parseGlobalPtrDirectory,
ImageDirectoryEntryTLS: pe.parseTLSDirectory,
ImageDirectoryEntryLoadConfig: pe.parseLoadConfigDirectory,
ImageDirectoryEntryBoundImport: pe.parseBoundImportDirectory,
ImageDirectoryEntryIAT: pe.parseIATDirectory,
ImageDirectoryEntryDelayImport: pe.parseDelayImportDirectory,
ImageDirectoryEntryCLR: pe.parseCLRHeaderDirectory,
}
// Iterate over data directories and call the appropriate function.
for entryIndex := ImageDirectoryEntry(0); entryIndex < ImageNumberOfDirectoryEntries; entryIndex++ {
var va, size uint32
switch pe.Is64 {
case true:
dirEntry := oh64.DataDirectory[entryIndex]
va = dirEntry.VirtualAddress
size = dirEntry.Size
case false:
dirEntry := oh32.DataDirectory[entryIndex]
va = dirEntry.VirtualAddress
size = dirEntry.Size
}
if va != 0 {
func() {
// keep parsing data directories even though some entries fails.
defer func() {
if e := recover(); e != nil {
pe.logger.Errorf("unhandled exception when parsing data directory %s, reason: %v",
entryIndex.String(), e)
foundErr = true
}
}()
// the last entry in the data directories is reserved and must be zero.
if entryIndex == ImageDirectoryEntryReserved {
pe.Anomalies = append(pe.Anomalies, AnoReservedDataDirectoryEntry)
return
}
err := funcMaps[entryIndex](va, size)
if err != nil {
pe.logger.Warnf("failed to parse data directory %s, reason: %v",
entryIndex.String(), err)
}
}()
}
}
if foundErr {
return errors.New("Data directory parsing failed")
}
return nil
}