-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrawler_files.go
343 lines (271 loc) · 8.64 KB
/
crawler_files.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
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
package main
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"golang.org/x/text/encoding/htmlindex"
)
type FilesCrawler struct {
Rules []*RuleConfig
SystemState *SystemState
NextChannel chan *SecurityEventsContainer
_firstRun bool
_inited bool
_crawlPeriod time.Duration
_defaultPeriodToParse time.Duration
}
func (crawler *FilesCrawler) Init() {
if len(crawler.Rules) < 1 {
return
}
crawler._crawlPeriod = 60 * time.Second
crawler._defaultPeriodToParse = time.Hour * 24 * 30
crawler._inited = true
}
func (crawler *FilesCrawler) Run() {
if crawler._inited {
emit(logLevel.verbose, "files crawler started")
crawler._firstRun = true
for {
crawler._RunOnce()
crawler._firstRun = false
time.Sleep(crawler._crawlPeriod)
}
}
}
func (crawler *FilesCrawler) _RunOnce() {
pathOnRulesMap := crawler._GetFilesListMap()
// debugJson(pathOnRulesMap)
for path, rules := range pathOnRulesMap {
fileId := GetFileOsUniqueKey(path)
if len(fileId) < 1 {
continue
}
fileInfo, err := os.Stat(path)
if err != nil {
emit(logLevel.important, "failed reading file stat. file: %s, error: %s\n", path, err)
continue
}
if fileInfo.IsDir() {
continue
}
maxFileDeadTime := time.Second * 1
// find max dead time among rules
for _, rule := range rules {
if rule.deadtime > maxFileDeadTime {
maxFileDeadTime = rule.deadtime
}
}
fileModified := fileInfo.ModTime()
if time.Now().Sub(fileModified) > maxFileDeadTime {
// the file is so old for parsing
// emitLine(logLevel.verbose, "file '%s' so old. Last modified time: %s, max file deadtime: %s", path, fileModified.String(), maxFileDeadTime.String())
continue
}
sourceState := crawler.SystemState.Find(fileId)
// debugJson(sourceState)
var position int64 = 0
var linePosition int64 = 1
if sourceState.Offset > 0 {
position = sourceState.Offset
linePosition = sourceState.Line
}
if crawler._firstRun {
ruleNames := make([]string, 0)
for _, rule := range rules {
ruleNames = append(ruleNames, rule.RuleFileName)
}
if linePosition > 0 {
emitLine(logLevel.important, "resume observing file '%s' from position %d (line:%d); rules: '%s'.", path, position, linePosition, strings.Join(ruleNames, ", "))
} else {
emitLine(logLevel.important, "resume observing file '%s' from position %d; rules: '%s'.", path, position, strings.Join(ruleNames, ", "))
}
}
fileSize := fileInfo.Size()
if position > fileSize {
position = 0
linePosition = 1
} else if position == fileSize {
continue
}
// read file from position to end
file, err := ReadOpen(path)
if err != nil {
emitLine(logLevel.important, "failed reading file '%s'. Error: %s", path, err)
continue
}
defer file.Close()
// get encoding from the first rule
encodingName := rules[0].Encoding
if len(encodingName) > 0 {
_, err = htmlindex.Get(encodingName)
if err != nil {
emitLine(logLevel.important, "incorrect encoding '%s' specified for file '%s'. default encoding will be used.", encodingName, path)
encodingName = ""
}
}
decodingReader, err := Utf8Reader(file, encodingName)
if err != nil {
emitLine(logLevel.important, "failed reading file '%s'. encoding: '%s'", path, encodingName)
continue
}
if position > 0 {
file.Seek(position, io.SeekStart)
}
reader := bufio.NewReaderSize(decodingReader, 10*1024)
eventsContainer := &SecurityEventsContainer{}
eventsContainer.SourceId = sourceState.SourceId
eventsContainer.Source = path
src := path
for {
segment, err := reader.ReadBytes('\n')
line := string(segment)
if len(line) > 0 {
// remove \r\n from the end of the string
if line[len(line)-1] == '\n' {
drop := 1
if len(line) > 1 && line[len(line)-2] == '\r' {
drop = 2
}
line = line[:len(line)-drop]
} else if err == io.EOF {
// this is the last line before file END, need to decide - process or not to process
// if file is still modifiying, break the last line
if time.Now().Sub(fileModified) < time.Second*60 {
// debug(time.Now().Sub(fileModified).String())
break
}
}
}
if linePosition > 0 {
linePosition++
}
position, _ := file.Seek(0, io.SeekCurrent)
sourceState.Line = linePosition
sourceState.Offset = position
eventsContainer.Offset = sourceState.Offset
eventsContainer.Line = sourceState.Line
if len(line) > 0 {
// process line by correspondent rules
for _, rule := range rules {
crawler.ParseLine(&src, linePosition, &line, rule, eventsContainer)
}
}
if err != nil {
if err == io.EOF {
break
} else if err == bufio.ErrBufferFull {
continue
} else {
emitLine(logLevel.important, "unexpected error during reading the file '%s'. error: %s", path, err)
break
}
}
}
eventsContainer.CleanSecurityEventsFromDublicates()
crawler.NextChannel <- eventsContainer
// debug("finished processing file %s. security events: %d. rules: %d", path, len(eventsContainer.SecurityEvents), len(rules))
} // # end for path, rules := range pathOnRulesMap
}
func (crawler *FilesCrawler) ParseLine(source *string, linePosition int64, text *string, rule *RuleConfig, eventsContainer *SecurityEventsContainer) {
for _, eventFilter := range rule.Events {
regex := eventFilter.CompiledRegex
securityId := eventFilter.Sid
matches := regex.FindStringSubmatch(*text)
if matches != nil && len(matches) > 0 {
resultMap := make(map[string]string)
// fill result map with predefined fields
if len(eventFilter.Fields) > 0 {
for key, value := range eventFilter.Fields {
resultMap[key] = value
}
}
RegexFindAllSubmatches(text, regex, &resultMap)
// emitJson(logLevel.verbose, resultMap)
// parse datetime
eventTimeStr := resultMap["eventTime"]
var eventTime time.Time
var err error
if len(rule.EventTimeFormat) < 1 {
eventTime, err = time.ParseInLocation(eventTimeStr, eventTimeStr, time.Local)
if err != nil {
emit(logLevel.important, "FileReader: Failed parsing '%s'. Error: %s\n", eventTimeStr, err)
continue
}
} else {
eventTime, err = ExYearParseDate(rule.EventTimeFormat, eventTimeStr, time.Local)
if err != nil {
emit(logLevel.important, "FileReader: Failed parsing '%s' to format '%s'. Error: %s\n", eventTimeStr, rule.EventTimeFormat, err)
continue
}
}
eventTimeNumber := DateToCustomLong(eventTime)
ipAddress := resultMap["ip"]
skipEvent := ApplyExcludeFilterToSecurityEvents(eventFilter.ExcludeCompiledRegex, &resultMap)
additionalFieldsMap := make(map[string]string)
for key, value := range resultMap {
if key != "ip" && key != "eventTime" {
additionalFieldsMap[key] = value
}
}
if len(additionalFieldsMap) < 1 {
additionalFieldsMap = nil
}
if skipEvent == false {
securityMessage := eventFilter.Message
securityMessage = ApplyFilterToSecurityMessage(securityMessage, &resultMap)
securityMessage = strings.Replace(securityMessage, "#ip", ipAddress, len(securityMessage))
eventSource := *source
if linePosition > 0 {
eventSource = fmt.Sprintf("%s:%d", eventSource, linePosition-1)
}
securityEvent := &SecurityEvent{
SecurityId: securityId,
SecurityGroupId: eventFilter.Gid,
EventTimeUtcNumber: eventTimeNumber,
Message: securityMessage,
Critical: eventFilter.Critical,
IpAddress: ipAddress,
AdditionalFields: additionalFieldsMap,
Source: &eventSource,
}
eventsContainer.SecurityEvents = append(eventsContainer.SecurityEvents, securityEvent)
// debugJson(eventsContainer)
}
}
}
}
func (crawler *FilesCrawler) _GetFilesListMap() map[string][]*RuleConfig {
pathOnRulesMap := make(map[string][]*RuleConfig)
// find files by all specified paths
for _, rule := range crawler.Rules {
for _, path := range rule.Paths {
files, err := filepath.Glob(path)
if err != nil {
emit(logLevel.important, "Malformed specified path %s in the file %s. \t")
}
for _, file := range files {
file = NormalizeFileName(file)
// check if this rule is already assigned to this path
mapRules := pathOnRulesMap[file]
for _, mapRule := range mapRules {
if mapRule.RuleFileName == rule.RuleFileName {
continue
}
}
// check if file is excluded by the current rule
if rule.CompiledExcludeFilesRegex != nil {
if rule.CompiledExcludeFilesRegex.MatchString(file) {
continue
}
}
pathOnRulesMap[file] = append(pathOnRulesMap[file], rule)
}
}
}
return pathOnRulesMap
}