-
Notifications
You must be signed in to change notification settings - Fork 162
/
dispatcher.go
518 lines (476 loc) · 17.2 KB
/
dispatcher.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Copyright 2023 ETH Zurich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dispatcher
import (
"fmt"
"net"
"net/netip"
"github.com/google/gopacket"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
"github.com/scionproto/scion/pkg/addr"
"github.com/scionproto/scion/pkg/log"
"github.com/scionproto/scion/pkg/private/common"
"github.com/scionproto/scion/pkg/private/serrors"
"github.com/scionproto/scion/pkg/slayers"
"github.com/scionproto/scion/pkg/slayers/path/epic"
"github.com/scionproto/scion/pkg/slayers/path/scion"
)
const ErrUnsupportedL4 common.ErrMsg = "unsupported SCION L4 protocol"
// Server is the main object allowing to forward SCION packets coming
// from legacy BR to the final endhost application and to handle SCMP
// info packets destined to this endhost.
type Server struct {
conn *net.UDPConn
// topo keeps the topology for the local AS. It can keep multiple ASes
// in case we run several topologies locally, e.g., developer environment.
// TODO(JordiSubira): This may be taken from daemon for non self-contained
// applications.
ServiceAddresses map[addr.Addr]netip.AddrPort
buf []byte
oobuf []byte
outBuffer gopacket.SerializeBuffer
decoded []gopacket.LayerType
parser *gopacket.DecodingLayerParser
cmParser controlMessageParser
options gopacket.SerializeOptions
scionLayer slayers.SCION
hbh slayers.HopByHopExtnSkipper
e2e slayers.EndToEndExtn
udpLayer slayers.UDP
scmpLayer slayers.SCMP
}
// NewServer creates new instance of Server.
func NewServer(svcAddrs map[addr.Addr]netip.AddrPort, conn *net.UDPConn) *Server {
server := Server{
ServiceAddresses: svcAddrs,
buf: make([]byte, common.SupportedMTU),
oobuf: make([]byte, 1024),
decoded: make([]gopacket.LayerType, 4),
outBuffer: gopacket.NewSerializeBuffer(),
options: gopacket.SerializeOptions{
ComputeChecksums: true,
FixLengths: true,
},
}
parser := gopacket.NewDecodingLayerParser(
slayers.LayerTypeSCION,
&server.scionLayer,
&server.hbh,
&server.e2e,
&server.udpLayer,
&server.scmpLayer,
)
parser.IgnoreUnsupported = true
server.parser = parser
server.conn, server.cmParser = setIPPktInfo(conn)
server.scionLayer.RecyclePaths()
server.udpLayer.SetNetworkLayerForChecksum(&server.scionLayer)
server.scmpLayer.SetNetworkLayerForChecksum(&server.scionLayer)
return &server
}
// Serve starts reading packets from network and dispatching them to the end application.
// It also replies to SCMPEchoRequest and SCMPTracerouteRequest.
// The function blocks and returns if there's an error or when Close has been called.
func (s *Server) Serve() error {
for {
n, nn, _, prevHop, err := s.conn.ReadMsgUDPAddrPort(s.buf, s.oobuf)
if err != nil {
log.Error("Reading message", "err", err)
continue
}
underlay := s.parseUnderlayAddr(s.oobuf[:nn])
if underlay == nil {
// some error parsing the CM info from the incoming packet;
// we discard the packet and keep serving.
continue
}
outBuf, nextHopAddr, err := s.processMsgNextHop(s.buf[:n], *underlay, prevHop)
if err != nil {
return err
}
if nextHopAddr == nil {
// some error processing the incoming packet;
// we discard the packet and keep serving.
continue
}
m, err := s.conn.WriteToUDPAddrPort(outBuf, *nextHopAddr)
if err != nil {
log.Error("writing packet out", "err", err)
continue
}
if m != len(outBuf) {
log.Error("writing packet out", "message len", len(outBuf), "written bytes", n)
}
}
}
// processMsgNextHop processes the message arriving to the shim dispatcher and returns
// a byte array corresponding to the packet that has to be forwarded.
// The input byte array *buf* is the raw incoming packet; the *underlay* address MUST NOT
// be nil and corresponds to the IP address in the encapsulation UDP/IP header; *prevHop*
// address is the address from the previous SCION hop in the local network.
// The intended nextHop address, either the end application or the next BR (for SCMP
// informational response), is returned.
// It returns a non-nil error for non-recoverable errors, only.
// If the incoming packet couldn't be processed due to a recoverable error or due to
// incorrect address validation the returned buffer and address will be nil.
// The caller must check both values consistently.
func (s *Server) processMsgNextHop(
buf []byte,
underlay netip.Addr,
prevHop netip.AddrPort,
) ([]byte, *netip.AddrPort, error) {
err := s.parser.DecodeLayers(buf, &s.decoded)
if err != nil {
log.Error("Decoding layers", "err", err)
return nil, nil, nil
}
if len(s.decoded) < 2 {
log.Error("Unexpected decode packet", "layers decoded", len(s.decoded))
return nil, nil, nil
}
err = s.outBuffer.Clear()
if err != nil {
return nil, nil, err
}
// Retrieve DST UDP/SCION addr and compare to underlay address if it applies,
// i.e., all cases expect SCMPInfo request messages, which are to be replied
// by the shim dispatcher itself.
var dstAddrPort netip.AddrPort
switch s.decoded[len(s.decoded)-1] {
case slayers.LayerTypeSCMP:
// send response to BR
if s.scmpLayer.TypeCode.Type() == slayers.SCMPTypeTracerouteRequest ||
s.scmpLayer.TypeCode.Type() == slayers.SCMPTypeEchoRequest {
dstAddrPort = prevHop
} else { // relay to end application
dstAddrPort, err = s.getDstSCMP()
if err != nil {
log.Error("Getting destination for SCMP message", "err", err)
return nil, nil, nil
}
if dstAddrPort.Addr().Unmap().Compare(underlay.Unmap()) != 0 {
log.Error("UDP/IP addr destination different from UDP/SCION addr",
"UDP/IP:", underlay.Unmap().String(),
"UDP/SCION:", dstAddrPort.Addr().Unmap().String())
return nil, nil, nil
}
}
case slayers.LayerTypeSCIONUDP:
dstAddrPort, err = s.getDstSCIONUDP()
if err != nil {
log.Error("Getting destination for SCION/UDP message", "err", err)
return nil, nil, nil
}
if dstAddrPort.Addr().Unmap().Compare(underlay.Unmap()) != 0 {
log.Error("UDP/IP addr destination different from UDP/SCION addr",
"UDP/IP:", underlay.Unmap().String(),
"UDP/SCION:", dstAddrPort.Addr().Unmap().String())
return nil, nil, nil
}
}
var outBuf []byte
// generate SCMPInfo response
if s.decoded[len(s.decoded)-1] == slayers.LayerTypeSCMP &&
(s.scmpLayer.TypeCode.Type() == slayers.SCMPTypeTracerouteRequest ||
s.scmpLayer.TypeCode.Type() == slayers.SCMPTypeEchoRequest) {
err = s.replyToSCMPInfoRequest()
if err != nil {
log.Error("Reversing SCMP information", "err", err)
return nil, nil, nil
}
payload := gopacket.Payload(s.scmpLayer.Payload)
err = payload.SerializeTo(s.outBuffer, s.options)
if err != nil {
log.Error("Serializing payload", "err", err)
return nil, nil, nil
}
s.outBuffer.PushLayer(payload.LayerType())
err = s.scmpLayer.SerializeTo(s.outBuffer, s.options)
if err != nil {
log.Error("Serializing SCMP header", "err", err)
return nil, nil, nil
}
s.outBuffer.PushLayer(s.scmpLayer.LayerType())
if s.decoded[len(s.decoded)-2] == slayers.LayerTypeEndToEndExtn {
err = s.e2e.SerializeTo(s.outBuffer, s.options)
if err != nil {
log.Error("Serializing e2e extension", "err", err)
return nil, nil, nil
}
s.outBuffer.PushLayer(s.e2e.LayerType())
}
err = s.scionLayer.SerializeTo(s.outBuffer, s.options)
if err != nil {
log.Error("Serializing SCION header", "err", err)
return nil, nil, nil
}
s.outBuffer.PushLayer(s.scionLayer.LayerType())
outBuf = s.outBuffer.Bytes()
} else { //forward incoming byte array
outBuf = buf
}
return outBuf, &dstAddrPort, nil
}
func (s *Server) replyToSCMPInfoRequest() error {
// Translate request to a reply.
switch s.scmpLayer.NextLayerType() {
case slayers.LayerTypeSCMPEcho:
s.scmpLayer.TypeCode = slayers.CreateSCMPTypeCode(slayers.SCMPTypeEchoReply, 0)
case slayers.LayerTypeSCMPTraceroute:
s.scmpLayer.TypeCode = slayers.CreateSCMPTypeCode(slayers.SCMPTypeTracerouteReply, 0)
default:
return serrors.New("unsupported SCMP informational message")
}
if err := s.reverseSCION(); err != nil {
return err
}
// XXX(roosd): This does not take HBH and E2E extensions into consideration.
// See: https://github.com/scionproto/scion/issues/4128
// TODO(JordiSubira): Add support for SPAO-E2E
s.scionLayer.NextHdr = slayers.L4SCMP
return nil
}
func (s *Server) reverseSCION() error {
// Reverse the SCION packet.
s.scionLayer.DstIA, s.scionLayer.SrcIA = s.scionLayer.SrcIA, s.scionLayer.DstIA
src, err := s.scionLayer.SrcAddr()
if err != nil {
return serrors.WrapStr("parsing source address", err)
}
dst, err := s.scionLayer.DstAddr()
if err != nil {
return serrors.WrapStr("parsing destination address", err)
}
if err := s.scionLayer.SetSrcAddr(dst); err != nil {
return serrors.WrapStr("setting source address", err)
}
if err := s.scionLayer.SetDstAddr(src); err != nil {
return serrors.WrapStr("setting destination address", err)
}
if s.scionLayer.PathType == epic.PathType {
// Received packet with EPIC path type, hence extract the SCION path
epicPath, ok := s.scionLayer.Path.(*epic.Path)
if !ok {
return serrors.New("path type and path data do not match")
}
s.scionLayer.Path = epicPath.ScionPath
s.scionLayer.PathType = scion.PathType
}
if s.scionLayer.Path, err = s.scionLayer.Path.Reverse(); err != nil {
return serrors.WrapStr("reversing path", err)
}
return nil
}
func (s *Server) getDstSCMP() (netip.AddrPort, error) {
// Check if its SCMPEcho or SCMPTraceroute reply
if s.scmpLayer.TypeCode.Type() == slayers.SCMPTypeEchoReply {
var scmpEcho slayers.SCMPEcho
err := scmpEcho.DecodeFromBytes(s.scmpLayer.Payload, gopacket.NilDecodeFeedback)
if err != nil {
return netip.AddrPort{}, err
}
return addrPortFromBytes(s.scionLayer.RawDstAddr, scmpEcho.Identifier)
}
if s.scmpLayer.TypeCode.Type() == slayers.SCMPTypeTracerouteReply {
var scmpTraceroute slayers.SCMPTraceroute
err := scmpTraceroute.DecodeFromBytes(s.scmpLayer.Payload, gopacket.NilDecodeFeedback)
if err != nil {
return netip.AddrPort{}, err
}
return addrPortFromBytes(s.scionLayer.RawDstAddr, scmpTraceroute.Identifier)
}
// Drop unknown SCMP error messages.
if s.scmpLayer.NextLayerType() == gopacket.LayerTypePayload {
return netip.AddrPort{}, serrors.New("unsupported SCMP error message",
"type", s.scmpLayer.TypeCode.Type())
}
l, err := decodeSCMP(&s.scmpLayer)
if err != nil {
return netip.AddrPort{}, err
}
if len(l) != 2 {
return netip.AddrPort{}, serrors.New("SCMP error message without payload")
}
gpkt := gopacket.NewPacket(*l[1].(*gopacket.Payload), slayers.LayerTypeSCION,
gopacket.DecodeOptions{
NoCopy: true,
},
)
// If the offending packet was UDP/SCION, use the source port to deliver.
if udp := gpkt.Layer(slayers.LayerTypeSCIONUDP); udp != nil {
port := udp.(*slayers.UDP).SrcPort
// XXX(roosd): We assume that the zero value means the UDP header is
// truncated. This flags packets of misbehaving senders as truncated, if
// they set the source port to 0. But there is no harm, since those
// packets are destined to be dropped anyway.
if port == 0 {
return netip.AddrPort{}, serrors.New("SCMP error with truncated UDP header")
}
return addrPortFromBytes(s.scionLayer.RawDstAddr, port)
}
// If the offending packet was SCMP/SCION, and it is an echo or traceroute,
// use the Identifier to deliver. In all other cases, the message is dropped.
if scmp := gpkt.Layer(slayers.LayerTypeSCMP); scmp != nil {
tc := scmp.(*slayers.SCMP).TypeCode
// SCMP Error messages in response to an SCMP error message are not allowed.
if !tc.InfoMsg() {
return netip.AddrPort{},
serrors.New("SCMP error message in response to SCMP error message",
"type", tc.Type())
}
// We only support echo and traceroute requests.
t := tc.Type()
if t != slayers.SCMPTypeEchoRequest && t != slayers.SCMPTypeTracerouteRequest {
return netip.AddrPort{}, serrors.New("unsupported SCMP info message", "type", t)
}
var port uint16
// Extract the port from the echo or traceroute ID field.
if echo := gpkt.Layer(slayers.LayerTypeSCMPEcho); echo != nil {
port = echo.(*slayers.SCMPEcho).Identifier
} else if tr := gpkt.Layer(slayers.LayerTypeSCMPTraceroute); tr != nil {
port = tr.(*slayers.SCMPTraceroute).Identifier
} else {
return netip.AddrPort{}, serrors.New("SCMP error with truncated payload")
}
return addrPortFromBytes(s.scionLayer.RawDstAddr, port)
}
return netip.AddrPort{}, ErrUnsupportedL4
}
func (s *Server) getDstSCIONUDP() (netip.AddrPort, error) {
host, err := s.scionLayer.DstAddr()
if err != nil {
return netip.AddrPort{}, err
}
switch host.Type() {
case addr.HostTypeSVC:
hostAddr := addr.Addr{IA: s.scionLayer.DstIA, Host: host}
addrPort, ok := s.ServiceAddresses[hostAddr]
if !ok {
return netip.AddrPort{}, serrors.New("SVC destination not found",
"Host", hostAddr)
}
return addrPort, nil
case addr.HostTypeIP:
return addrPortFromBytes(s.scionLayer.RawDstAddr, s.udpLayer.DstPort)
default:
return netip.AddrPort{}, serrors.New("Invalid host type", "type", host.Type().String())
}
}
type controlMessageParser interface {
Destination() net.IP
Parse(b []byte) error
String() string
}
type ipv4ControlMessage struct {
*ipv4.ControlMessage
}
func (m ipv4ControlMessage) Destination() net.IP {
return m.Dst
}
type ipv6ControlMessage struct {
*ipv6.ControlMessage
}
func (m ipv6ControlMessage) Destination() net.IP {
return m.Dst
}
// parseUnderlayAddr returns the underlay destination address on the UDP/IP wrapper.
// It returns nil, if the control message information is not present or cannot be parsed.
// This is useful for checking that this address corresponds to the address of the encapsulated
// UDP/SCION header. This refers to the safeguard for traffic reflection as discussed in:
// https://github.com/scionproto/scion/pull/4280#issuecomment-1775177351
func (s *Server) parseUnderlayAddr(oobuffer []byte) *netip.Addr {
if err := s.cmParser.Parse(oobuffer); err != nil {
log.Error("Parsing Control Message Information", "err", err)
return nil
}
if !s.cmParser.Destination().IsUnspecified() {
pktAddr, ok := netip.AddrFromSlice(s.cmParser.Destination())
if !ok {
log.Error("Getting DST from IP_PKTINFO", "DST", s.cmParser.Destination())
return nil
}
return &pktAddr
}
log.Error("Destination in IP_PKTINFO is unspecified")
return nil
}
func ListenAndServe(svcAddrs map[addr.Addr]netip.AddrPort, addr *net.UDPAddr) error {
conn, err := net.ListenUDP(addr.Network(), addr)
if err != nil {
return err
}
defer conn.Close()
log.Debug(fmt.Sprintf("local address: %s", conn.LocalAddr()))
dispServer := NewServer(svcAddrs, conn)
return dispServer.Serve()
}
// decodeSCMP decodes the SCMP payload. WARNING: Decoding is done with NoCopy set.
func decodeSCMP(scmp *slayers.SCMP) ([]gopacket.SerializableLayer, error) {
gpkt := gopacket.NewPacket(scmp.Payload, scmp.NextLayerType(),
gopacket.DecodeOptions{NoCopy: true})
layers := gpkt.Layers()
if len(layers) == 0 || len(layers) > 2 {
return nil, serrors.New("invalid number of SCMP layers", "count", len(layers))
}
ret := make([]gopacket.SerializableLayer, len(layers))
for i, l := range layers {
s, ok := l.(gopacket.SerializableLayer)
if !ok {
return nil, serrors.New("invalid SCMP layer, not serializable", "index", i)
}
ret[i] = s
}
return ret, nil
}
func addrPortFromBytes(addr []byte, port uint16) (netip.AddrPort, error) {
a, ok := netip.AddrFromSlice(addr)
if !ok {
return netip.AddrPort{}, serrors.New("Unexpected raw address byte slice format")
}
return netip.AddrPortFrom(a, port), nil
}
// setIPPktInfo sets the IP_PKTINFO.DST flag to the underlay socket. The IPv4 part
// covers the case for IPv4-only hosts. For hosts supporting dual stack, the IPv6
// part handles both 6 and 4 (with mapped addresses).
// The argument conn must not be nil. The returned conn will have the flag set,
// and the returned controlMessageParser can be used as a facilitator to
// parse the OOB after reading on the conn.
func setIPPktInfo(conn *net.UDPConn) (*net.UDPConn, controlMessageParser) {
udpAddr, ok := conn.LocalAddr().(*net.UDPAddr)
if !ok {
panic(fmt.Sprintln("Connection address is not UDPAddr",
"conn", conn.LocalAddr().Network()))
}
var cm controlMessageParser
if udpAddr.AddrPort().Addr().Unmap().Is4() {
err := ipv4.NewPacketConn(conn).SetControlMessage(ipv4.FlagDst, true)
if err != nil {
panic(fmt.Sprintf("cannot set IP_PKTINFO on socket: %s", err))
}
cm = ipv4ControlMessage{
ControlMessage: new(ipv4.ControlMessage),
}
}
if udpAddr.AddrPort().Addr().Unmap().Is6() {
err := ipv6.NewPacketConn(conn).SetControlMessage(ipv6.FlagDst, true)
if err != nil {
panic(fmt.Sprintf("cannot set IP_PKTINFO on socket: %s", err))
}
cm = ipv6ControlMessage{
ControlMessage: new(ipv6.ControlMessage),
}
}
return conn, cm
}