File: parse.go

package info (click to toggle)
golang-github-jasonish-go-idsrules 0.0~git20170503.0.c646b91-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 96 kB
  • sloc: makefile: 3
file content (334 lines) | stat: -rw-r--r-- 7,369 bytes parent folder | download | duplicates (2)
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
// The MIT License (MIT)
// Copyright (c) 2016 Jason Ish
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package idsrules

import (
	"bufio"
	"fmt"
	"io"
	"strconv"
	"strings"
)

// RuleParseError is the error returned when a parsing error occurs.
type RuleParseError struct {
	// The rule that failed to parse.
	Rule string

	// Some message describing the parse error.
	Message string
}

func (e *RuleParseError) Error() string {
	return fmt.Sprintf("%s: %s", e.Message, e.Rule)
}

func newIcompleteRuleError(rule string) *RuleParseError {
	return &RuleParseError{
		Rule:    rule,
		Message: "incomplete",
	}
}

// Remove leading and trailing quotes from a string.
func trimQuotes(buf string) string {
	buflen := len(buf)
	if buflen == 0 {
		return buf
	}
	if buf[0:1] == "\"" && buf[buflen-1:buflen] == "\"" {
		return buf[1: buflen-1]
	}
	return buf
}

// Remove leading white space from a string.
func trimLeadingWhiteSpace(buf string) string {
	return strings.TrimLeft(buf, " ")
}

func splitAt(buf string, sep string) (string, string) {
	var leading string
	var trailing string

	parts := strings.SplitN(buf, sep, 2)
	if len(parts) > 1 {
		trailing = strings.TrimSpace(parts[1])
	}
	leading = strings.TrimSpace(parts[0])

	return leading, trailing
}

// Parse the next rule option from the provided rule.
//
// The option, argument and the remainder of the rule are returned.
func parseOption(rule string) (string, string, string, error) {
	var option string
	var arg string

	// Strip any leading space.
	rule = trimLeadingWhiteSpace(rule)

	hasArg := false
	optend := strings.IndexFunc(rule, func(r rune) bool {
		switch r {
		case ';':
			return true
		case ':':
			hasArg = true
			return true
		}
		return false
	})
	if optend < 0 {
		return option, arg, rule, fmt.Errorf("unterminated option")
	}

	option = rule[0:optend]

	rule = rule[optend+1:]

	if hasArg {
		if len(rule) == 0 {
			return option, arg, rule, fmt.Errorf("no argument")
		}
		escaped := false
		argend := strings.IndexFunc(rule, func(r rune) bool {
			if escaped {
				escaped = false
			} else if r == '\\' {
				escaped = true
			} else if r == ';' {
				return true
			}
			return false
		})
		if argend < 0 {
			return option, arg, rule,
				fmt.Errorf("unterminated option argument")
		}
		arg = rule[:argend]
		rule = rule[argend+1:]
	}

	return option, trimQuotes(arg), rule, nil
}

// Parse an IDS rule from the provided string buffer.
func Parse(buf string) (Rule, error) {
	rule := Rule{
		Raw: buf,
	}

	// Removing leading space.
	buf = trimLeadingWhiteSpace(buf)

	// Check enable/disable status.
	if !strings.HasPrefix(buf, "#") {
		rule.Enabled = true
	} else {
		buf = strings.TrimPrefix(buf, "#")
		buf = trimLeadingWhiteSpace(buf)
	}

	action, rem := splitAt(buf, " ")
	rule.Action = action
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	proto, rem := splitAt(rem, " ")
	rule.Proto = proto
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	sourceAddr, rem := splitAt(rem, " ")
	rule.SourceAddr = sourceAddr
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	sourcePort, rem := splitAt(rem, " ")
	rule.SourcePort = sourcePort
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	direction, rem := splitAt(rem, " ")
	if !validateDirection(direction) {
		return rule, fmt.Errorf("invalid direction: %s", direction)
	}
	rule.Direction = direction
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	destAddr, rem := splitAt(rem, " ")
	rule.DestAddr = destAddr
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	destPort, rem := splitAt(rem, " ")
	rule.DestPort = destPort
	if len(rem) == 0 {
		return rule, newIcompleteRuleError(buf)
	}

	offset := 0

	// Check that then next char is a (.
	if rem[offset:offset+1] != "(" {
		return rule, fmt.Errorf("expected (, got %s", rem[0:1])
	}
	offset++

	buf = rem[offset:]

	// Parse options.
	var option string
	var arg string
	var err error
	for {
		if len(buf) == 0 {
			return rule, newIcompleteRuleError(buf)
		}

		buf = trimLeadingWhiteSpace(buf)

		if strings.HasPrefix(buf, ")") {
			// Done.
			break
		}

		option, arg, buf, err = parseOption(buf)
		if err != nil {
			return rule, err
		}

		ruleOption := RuleOption{option, arg}
		rule.Options = append(rule.Options, ruleOption)

		switch option {
		case "msg":
			rule.Msg = arg
		case "sid":
			sid, err := strconv.ParseUint(arg, 10, 64)
			if err != nil {
				return rule, fmt.Errorf("failed to parse sid: %s", arg)
			}
			rule.Sid = sid
		case "gid":
			gid, err := strconv.ParseUint(arg, 10, 64)
			if err != nil {
				return rule, fmt.Errorf("failed to parse sid: %s", arg)
			}
			rule.Gid = gid
		}
	}

	return rule, nil
}

// ParseReader parses multiple rules from a reader.
func ParseReader(reader io.Reader) ([]Rule, error) {
	rules := make([]Rule, 0)

	ruleReader := NewRuleReader(reader)

	for {
		rule, err := ruleReader.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			continue
		}
		rules = append(rules, rule)
	}

	return rules, nil
}

// RuleReader parses rules one by from an underlying reader.
type RuleReader struct {
	reader *bufio.Reader
}

// NewRuleReader creates a new RuleReader reading from a reader.
func NewRuleReader(reader io.Reader) *RuleReader {
	ruleReader := &RuleReader{
		reader: bufio.NewReader(reader),
	}
	return ruleReader
}

func (r *RuleReader) readLine() (string, error) {
	bytes, err := r.reader.ReadBytes('\n')
	if err != nil && len(bytes) == 0 {
		return "", err
	}
	return strings.TrimSpace(string(bytes)), nil
}

// Next returns the next rule read from the reader. Empty lines and commented
// out lines are skipped. Any other line that doesn't parse as a rule is
// considered an error.
func (r *RuleReader) Next() (Rule, error) {

	ruleString := ""

	for {
		line, err := r.readLine()
		if err != nil && line == "" {
			return Rule{}, err
		}

		if len(line) == 0 {
			continue
		}

		if strings.HasSuffix(line, "\\") {
			ruleString = fmt.Sprintf("%s%s",
				ruleString, line[0:len(line)-1])
			continue
		}

		ruleString = fmt.Sprintf("%s%s", ruleString, line)

		rule, err := Parse(ruleString)
		if err != nil {
			if strings.HasPrefix(ruleString, "#") {
				ruleString = ""
				continue
			}
			return Rule{}, err
		}
		ruleString = ""
		return rule, err
	}

}