-
Notifications
You must be signed in to change notification settings - Fork 44
/
decoder.go
409 lines (344 loc) · 8.85 KB
/
decoder.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package packet
import (
"bytes"
"fmt"
"net"
"github.com/bio-routing/bio-rd/util/decode"
"github.com/bio-routing/tflow2/convert"
"github.com/pkg/errors"
)
// Decode decodes a BGP message
func Decode(buf *bytes.Buffer, opt *DecodeOptions) (*BGPMessage, error) {
hdr, err := decodeHeader(buf)
if err != nil {
return nil, errors.Wrap(err, "Failed to decode header")
}
body, err := decodeMsgBody(buf, hdr.Type, hdr.Length-MinLen, opt)
if err != nil {
return nil, errors.Wrap(err, "Failed to decode message")
}
return &BGPMessage{
Header: hdr,
Body: body,
}, nil
}
func decodeMsgBody(buf *bytes.Buffer, msgType uint8, l uint16, opt *DecodeOptions) (interface{}, error) {
switch msgType {
case OpenMsg:
return DecodeOpenMsg(buf)
case UpdateMsg:
return decodeUpdateMsg(buf, l, opt)
case KeepaliveMsg:
return nil, nil // Nothing to decode in Keepalive message
case NotificationMsg:
return decodeNotificationMsg(buf)
}
return nil, fmt.Errorf("Unknown message type: %d", msgType)
}
func decodeUpdateMsg(buf *bytes.Buffer, l uint16, opt *DecodeOptions) (*BGPUpdate, error) {
msg := &BGPUpdate{}
err := decode.DecodeUint16(buf, &msg.WithdrawnRoutesLen)
if err != nil {
return msg, err
}
msg.WithdrawnRoutes, err = decodeNLRIs(buf, uint16(msg.WithdrawnRoutesLen), IPv4AFI, opt.AddPathIPv4Unicast)
if err != nil {
return msg, err
}
err = decode.DecodeUint16(buf, &msg.TotalPathAttrLen)
if err != nil {
return msg, err
}
msg.PathAttributes, err = decodePathAttrs(buf, msg.TotalPathAttrLen, opt)
if err != nil {
return msg, err
}
nlriLen := uint16(l) - 4 - uint16(msg.TotalPathAttrLen) - uint16(msg.WithdrawnRoutesLen)
if nlriLen > 0 {
msg.NLRI, err = decodeNLRIs(buf, nlriLen, IPv4AFI, opt.AddPathIPv4Unicast)
if err != nil {
return msg, err
}
}
return msg, nil
}
func decodeNotificationMsg(buf *bytes.Buffer) (*BGPNotification, error) {
msg := &BGPNotification{}
fields := []interface{}{
&msg.ErrorCode,
&msg.ErrorSubcode,
}
err := decode.Decode(buf, fields)
if err != nil {
return msg, err
}
if msg.ErrorCode > Cease {
return msg, fmt.Errorf("Invalid error code: %d", msg.ErrorSubcode)
}
switch msg.ErrorCode {
case MessageHeaderError:
if msg.ErrorSubcode > BadMessageType || msg.ErrorSubcode == 0 {
return invalidErrCode(msg)
}
case OpenMessageError:
if msg.ErrorSubcode > UnacceptableHoldTime || msg.ErrorSubcode == 0 || msg.ErrorSubcode == DeprecatedOpenMsgError5 {
return invalidErrCode(msg)
}
case UpdateMessageError:
if msg.ErrorSubcode > MalformedASPath || msg.ErrorSubcode == 0 || msg.ErrorSubcode == DeprecatedUpdateMsgError7 {
return invalidErrCode(msg)
}
case HoldTimeExpired:
if msg.ErrorSubcode != 0 {
return invalidErrCode(msg)
}
case FiniteStateMachineError:
if msg.ErrorSubcode != 0 {
return invalidErrCode(msg)
}
case Cease:
if !(msg.ErrorSubcode == 0 || msg.ErrorSubcode == AdministrativeShutdown || msg.ErrorSubcode == AdministrativeReset) {
return invalidErrCode(msg)
}
default:
return invalidErrCode(msg)
}
return msg, nil
}
func invalidErrCode(n *BGPNotification) (*BGPNotification, error) {
return n, fmt.Errorf("Invalid error sub code: %d/%d", n.ErrorCode, n.ErrorSubcode)
}
// DecodeOpenMsg decodes a BGP OPEN message
func DecodeOpenMsg(buf *bytes.Buffer) (*BGPOpen, error) {
msg, err := _decodeOpenMsg(buf)
if err != nil {
return nil, errors.Wrap(err, "Unable to decode OPEN message")
}
return msg.(*BGPOpen), err
}
func _decodeOpenMsg(buf *bytes.Buffer) (interface{}, error) {
msg := &BGPOpen{}
fields := []interface{}{
&msg.Version,
&msg.ASN,
&msg.HoldTime,
&msg.BGPIdentifier,
&msg.OptParmLen,
}
err := decode.Decode(buf, fields)
if err != nil {
return msg, err
}
err = validateOpen(msg)
if err != nil {
return nil, err
}
msg.OptParams, err = decodeOptParams(buf, msg.OptParmLen)
if err != nil {
return nil, errors.Wrap(err, "Unable to decode optional parameters")
}
return msg, nil
}
func decodeOptParams(buf *bytes.Buffer, optParmLen uint8) ([]OptParam, error) {
optParams := make([]OptParam, 0)
read := uint8(0)
for read < optParmLen {
o := OptParam{}
fields := []interface{}{
&o.Type,
&o.Length,
}
err := decode.Decode(buf, fields)
if err != nil {
return nil, err
}
read += 2
switch o.Type {
case CapabilitiesParamType:
caps, err := decodeCapabilities(buf, o.Length)
if err != nil {
return nil, errors.Wrap(err, "Unable to decode capabilities")
}
o.Value = caps
optParams = append(optParams, o)
for _, cap := range caps {
read += cap.Length + 2
}
default:
return nil, fmt.Errorf("Unrecognized option: %d", o.Type)
}
}
return optParams, nil
}
func decodeCapabilities(buf *bytes.Buffer, length uint8) (Capabilities, error) {
ret := make(Capabilities, 0)
read := uint8(0)
for read < length {
cap, err := decodeCapability(buf)
if err != nil {
return nil, errors.Wrap(err, "Unable to decode capability")
}
ret = append(ret, cap)
read += cap.Length + 2
}
return ret, nil
}
func decodeCapability(buf *bytes.Buffer) (Capability, error) {
cap := Capability{}
fields := []interface{}{
&cap.Code,
&cap.Length,
}
err := decode.Decode(buf, fields)
if err != nil {
return cap, err
}
switch cap.Code {
case MultiProtocolCapabilityCode:
mpCap, err := decodeMultiProtocolCapability(buf)
if err != nil {
return cap, fmt.Errorf("Unable to decode multi protocol capability")
}
cap.Value = mpCap
case AddPathCapabilityCode:
addPathCap, err := decodeAddPathCapability(buf)
if err != nil {
return cap, errors.Wrap(err, "Unable to decode add path capability")
}
cap.Value = addPathCap
case ASN4CapabilityCode:
asn4Cap, err := decodeASN4Capability(buf)
if err != nil {
return cap, errors.Wrap(err, "Unable to decode 4 octet ASN capability")
}
cap.Value = asn4Cap
default:
for i := uint8(0); i < cap.Length; i++ {
_, err := buf.ReadByte()
if err != nil {
return cap, errors.Wrap(err, "Read failed")
}
}
}
return cap, nil
}
func decodeMultiProtocolCapability(buf *bytes.Buffer) (MultiProtocolCapability, error) {
mpCap := MultiProtocolCapability{}
reserved := uint8(0)
fields := []interface{}{
&mpCap.AFI, &reserved, &mpCap.SAFI,
}
err := decode.Decode(buf, fields)
if err != nil {
return mpCap, err
}
return mpCap, nil
}
func decodeAddPathCapability(buf *bytes.Buffer) (AddPathCapability, error) {
addPathCap := AddPathCapability{}
fields := []interface{}{
&addPathCap.AFI,
&addPathCap.SAFI,
&addPathCap.SendReceive,
}
err := decode.Decode(buf, fields)
if err != nil {
return addPathCap, err
}
return addPathCap, nil
}
func decodeASN4Capability(buf *bytes.Buffer) (ASN4Capability, error) {
asn4Cap := ASN4Capability{}
fields := []interface{}{
&asn4Cap.ASN4,
}
err := decode.Decode(buf, fields)
if err != nil {
return asn4Cap, err
}
return asn4Cap, nil
}
func validateOpen(msg *BGPOpen) error {
if msg.Version != BGP4Version {
return BGPError{
ErrorCode: OpenMessageError,
ErrorSubCode: UnsupportedVersionNumber,
ErrorStr: fmt.Sprintf("Unsupported version number"),
}
}
if !isValidIdentifier(msg.BGPIdentifier) {
return BGPError{
ErrorCode: OpenMessageError,
ErrorSubCode: BadBGPIdentifier,
ErrorStr: fmt.Sprintf("Invalid BGP identifier"),
}
}
return nil
}
func isValidIdentifier(id uint32) bool {
addr := net.IP(convert.Uint32Byte(id))
if addr.IsLoopback() {
return false
}
if addr.IsMulticast() {
return false
}
if addr[0] == 0 {
return false
}
if addr[0] == 255 && addr[1] == 255 && addr[2] == 255 && addr[3] == 255 {
return false
}
return true
}
func decodeHeader(buf *bytes.Buffer) (*BGPHeader, error) {
hdr := &BGPHeader{}
for i := 0; i < MarkerLen; i++ {
b, err := buf.ReadByte()
if err != nil {
return hdr, BGPError{
ErrorCode: Cease,
ErrorSubCode: 0,
ErrorStr: fmt.Sprintf("Failed to read from buffer: %v", err),
}
}
if b != 0xff {
return nil, BGPError{
ErrorCode: MessageHeaderError,
ErrorSubCode: ConnectionNotSync,
ErrorStr: fmt.Sprintf("Invalid marker"),
}
}
}
err := decode.DecodeUint16(buf, &hdr.Length)
if err != nil {
return hdr, BGPError{
ErrorCode: Cease,
ErrorSubCode: 0,
ErrorStr: fmt.Sprintf("%v", err.Error()),
}
}
err = decode.DecodeUint8(buf, &hdr.Type)
if err != nil {
return hdr, BGPError{
ErrorCode: Cease,
ErrorSubCode: 0,
ErrorStr: fmt.Sprintf("%v", err.Error()),
}
}
if hdr.Length < MinLen || hdr.Length > MaxLen {
return hdr, BGPError{
ErrorCode: MessageHeaderError,
ErrorSubCode: BadMessageLength,
ErrorStr: fmt.Sprintf("Invalid length in BGP header: %v", hdr.Length),
}
}
if hdr.Type > KeepaliveMsg || hdr.Type == 0 {
return hdr, BGPError{
ErrorCode: MessageHeaderError,
ErrorSubCode: BadMessageType,
ErrorStr: fmt.Sprintf("Invalid message type: %d", hdr.Type),
}
}
return hdr, nil
}