Debian Codegraph @

vnet/nat.go

raw symbols SCIP
1 package vnet
2
3 import (
4 "errors"
5 "fmt"
6 "net"
7 "sync"
8 "time"
9
10 "github.com/pion/logging"
11 )
12
13 var (
14 errNATRequriesMapping = errors.New("1:1 NAT requires more than one mapping")
15 errMismatchLengthIP = errors.New("length mismtach between mappedIPs and localIPs")
16 errNonUDPTranslationNotSupported = errors.New("non-udp translation is not supported yet")
17 errNoAssociatedLocalAddress = errors.New("no associated local address")
18 errNoNATBindingFound = errors.New("no NAT binding found")
19 errHasNoPermission = errors.New("has no permission")
20 )
21
22 // EndpointDependencyType defines a type of behavioral dependendency on the
23 // remote endpoint's IP address or port number. This is used for the two
24 // kinds of behaviors:
25 // - Port mapping behavior
26 // - Filtering behavior
27 //
28 // See: https://tools.ietf.org/html/rfc4787
29 type EndpointDependencyType uint8
30
31 const (
32 // EndpointIndependent means the behavior is independent of the endpoint's address or port
33 EndpointIndependent EndpointDependencyType = iota
34 // EndpointAddrDependent means the behavior is dependent on the endpoint's address
35 EndpointAddrDependent
36 // EndpointAddrPortDependent means the behavior is dependent on the endpoint's address and port
37 EndpointAddrPortDependent
38 )
39
40 // NATMode defines basic behavior of the NAT
41 type NATMode uint8
42
43 const (
44 // NATModeNormal means the NAT behaves as a standard NAPT (RFC 2663).
45 NATModeNormal NATMode = iota
46 // NATModeNAT1To1 exhibits 1:1 DNAT where the external IP address is statically mapped to
47 // a specific local IP address with port number is preserved always between them.
48 // When this mode is selected, MappingBehavior, FilteringBehavior, PortPreservation and
49 // MappingLifeTime of NATType are ignored.
50 NATModeNAT1To1
51 )
52
53 const (
54 defaultNATMappingLifeTime = 30 * time.Second
55 )
56
57 // NATType has a set of parameters that define the behavior of NAT.
58 type NATType struct {
59 Mode NATMode
60 MappingBehavior EndpointDependencyType
61 FilteringBehavior EndpointDependencyType
62 Hairpinning bool // Not implemented yet
63 PortPreservation bool // Not implemented yet
64 MappingLifeTime time.Duration
65 }
66
67 type natConfig struct {
68 name string
69 natType NATType
70 mappedIPs []net.IP // mapped IPv4
71 localIPs []net.IP // local IPv4, required only when the mode is NATModeNAT1To1
72 loggerFactory logging.LoggerFactory
73 }
74
75 type mapping struct {
76 proto string // "udp" or "tcp"
77 local string // "<local-ip>:<local-port>"
78 mapped string // "<mapped-ip>:<mapped-port>"
79 bound string // key: "[<remote-ip>[:<remote-port>]]"
80 filters map[string]struct{} // key: "[<remote-ip>[:<remote-port>]]"
81 expires time.Time // time to expire
82 }
83
84 type networkAddressTranslator struct {
85 name string
86 natType NATType
87 mappedIPs []net.IP // mapped IPv4
88 localIPs []net.IP // local IPv4, required only when the mode is NATModeNAT1To1
89 outboundMap map[string]*mapping // key: "<proto>:<local-ip>:<local-port>[:remote-ip[:remote-port]]
90 inboundMap map[string]*mapping // key: "<proto>:<mapped-ip>:<mapped-port>"
91 udpPortCounter int
92 mutex sync.RWMutex
93 log logging.LeveledLogger
94 }
95
96 func newNAT(config *natConfig) (*networkAddressTranslator, error) {
97 natType := config.natType
98
99 if natType.Mode == NATModeNAT1To1 {
100 // 1:1 NAT behavior
101 natType.MappingBehavior = EndpointIndependent
102 natType.FilteringBehavior = EndpointIndependent
103 natType.PortPreservation = true
104 natType.MappingLifeTime = 0
105
106 if len(config.mappedIPs) == 0 {
107 return nil, errNATRequriesMapping
108 }
109 if len(config.mappedIPs) != len(config.localIPs) {
110 return nil, errMismatchLengthIP
111 }
112 } else {
113 // Normal (NAPT) behavior
114 natType.Mode = NATModeNormal
115 if natType.MappingLifeTime == 0 {
116 natType.MappingLifeTime = defaultNATMappingLifeTime
117 }
118 }
119
120 return &networkAddressTranslator{
121 name: config.name,
122 natType: natType,
123 mappedIPs: config.mappedIPs,
124 localIPs: config.localIPs,
125 outboundMap: map[string]*mapping{},
126 inboundMap: map[string]*mapping{},
127 log: config.loggerFactory.NewLogger("vnet"),
128 }, nil
129 }
130
131 func (n *networkAddressTranslator) getPairedMappedIP(locIP net.IP) net.IP {
132 for i, ip := range n.localIPs {
133 if ip.Equal(locIP) {
134 return n.mappedIPs[i]
135 }
136 }
137 return nil
138 }
139
140 func (n *networkAddressTranslator) getPairedLocalIP(mappedIP net.IP) net.IP {
141 for i, ip := range n.mappedIPs {
142 if ip.Equal(mappedIP) {
143 return n.localIPs[i]
144 }
145 }
146 return nil
147 }
148
149 func (n *networkAddressTranslator) translateOutbound(from Chunk) (Chunk, error) {
150 n.mutex.Lock()
151 defer n.mutex.Unlock()
152
153 to := from.Clone()
154
155 if from.Network() == udp {
156 if n.natType.Mode == NATModeNAT1To1 {
157 // 1:1 NAT behavior
158 srcAddr := from.SourceAddr().(*net.UDPAddr) //nolint:forcetypeassert
159 srcIP := n.getPairedMappedIP(srcAddr.IP)
160 if srcIP == nil {
161 n.log.Debugf("[%s] drop outbound chunk %s with not route", n.name, from.String())
162 return nil, nil // nolint:nilnil
163 }
164 srcPort := srcAddr.Port
165 if err := to.setSourceAddr(fmt.Sprintf("%s:%d", srcIP.String(), srcPort)); err != nil {
166 return nil, err
167 }
168 } else {
169 // Normal (NAPT) behavior
170 var bound, filterKey string
171 switch n.natType.MappingBehavior {
172 case EndpointIndependent:
173 bound = ""
174 case EndpointAddrDependent:
175 bound = from.getDestinationIP().String()
176 case EndpointAddrPortDependent:
177 bound = from.DestinationAddr().String()
178 }
179
180 switch n.natType.FilteringBehavior {
181 case EndpointIndependent:
182 filterKey = ""
183 case EndpointAddrDependent:
184 filterKey = from.getDestinationIP().String()
185 case EndpointAddrPortDependent:
186 filterKey = from.DestinationAddr().String()
187 }
188
189 oKey := fmt.Sprintf("udp:%s:%s", from.SourceAddr().String(), bound)
190
191 m := n.findOutboundMapping(oKey)
192 if m == nil {
193 // Create a new mapping
194 mappedPort := 0xC000 + n.udpPortCounter
195 n.udpPortCounter++
196
197 m = &mapping{
198 proto: from.SourceAddr().Network(),
199 local: from.SourceAddr().String(),
200 bound: bound,
201 mapped: fmt.Sprintf("%s:%d", n.mappedIPs[0].String(), mappedPort),
202 filters: map[string]struct{}{},
203 expires: time.Now().Add(n.natType.MappingLifeTime),
204 }
205
206 n.outboundMap[oKey] = m
207
208 iKey := fmt.Sprintf("udp:%s", m.mapped)
209
210 n.log.Debugf("[%s] created a new NAT binding oKey=%s iKey=%s",
211 n.name,
212 oKey,
213 iKey)
214
215 m.filters[filterKey] = struct{}{}
216 n.log.Debugf("[%s] permit access from %s to %s", n.name, filterKey, m.mapped)
217 n.inboundMap[iKey] = m
218 } else if _, ok := m.filters[filterKey]; !ok {
219 n.log.Debugf("[%s] permit access from %s to %s", n.name, filterKey, m.mapped)
220 m.filters[filterKey] = struct{}{}
221 }
222
223 if err := to.setSourceAddr(m.mapped); err != nil {
224 return nil, err
225 }
226 }
227
228 n.log.Debugf("[%s] translate outbound chunk from %s to %s", n.name, from.String(), to.String())
229
230 return to, nil
231 }
232
233 return nil, errNonUDPTranslationNotSupported
234 }
235
236 func (n *networkAddressTranslator) translateInbound(from Chunk) (Chunk, error) {
237 n.mutex.Lock()
238 defer n.mutex.Unlock()
239
240 to := from.Clone()
241
242 if from.Network() == udp {
243 if n.natType.Mode == NATModeNAT1To1 {
244 // 1:1 NAT behavior
245 dstAddr := from.DestinationAddr().(*net.UDPAddr) //nolint:forcetypeassert
246 dstIP := n.getPairedLocalIP(dstAddr.IP)
247 if dstIP == nil {
248 return nil, fmt.Errorf("drop %s as %w", from.String(), errNoAssociatedLocalAddress)
249 }
250 dstPort := from.DestinationAddr().(*net.UDPAddr).Port //nolint:forcetypeassert
251 if err := to.setDestinationAddr(fmt.Sprintf("%s:%d", dstIP, dstPort)); err != nil {
252 return nil, err
253 }
254 } else {
255 // Normal (NAPT) behavior
256 iKey := fmt.Sprintf("udp:%s", from.DestinationAddr().String())
257 m := n.findInboundMapping(iKey)
258 if m == nil {
259 return nil, fmt.Errorf("drop %s as %w", from.String(), errNoNATBindingFound)
260 }
261
262 var filterKey string
263 switch n.natType.FilteringBehavior {
264 case EndpointIndependent:
265 filterKey = ""
266 case EndpointAddrDependent:
267 filterKey = from.getSourceIP().String()
268 case EndpointAddrPortDependent:
269 filterKey = from.SourceAddr().String()
270 }
271
272 if _, ok := m.filters[filterKey]; !ok {
273 return nil, fmt.Errorf("drop %s as the remote %s %w", from.String(), filterKey, errHasNoPermission)
274 }
275
276 // See RFC 4847 Section 4.3. Mapping Refresh
277 // a) Inbound refresh may be useful for applications with no outgoing
278 // UDP traffic. However, allowing inbound refresh may allow an
279 // external attacker or misbehaving application to keep a mapping
280 // alive indefinitely. This may be a security risk. Also, if the
281 // process is repeated with different ports, over time, it could
282 // use up all the ports on the NAT.
283
284 if err := to.setDestinationAddr(m.local); err != nil {
285 return nil, err
286 }
287 }
288
289 n.log.Debugf("[%s] translate inbound chunk from %s to %s", n.name, from.String(), to.String())
290
291 return to, nil
292 }
293
294 return nil, errNonUDPTranslationNotSupported
295 }
296
297 // caller must hold the mutex
298 func (n *networkAddressTranslator) findOutboundMapping(oKey string) *mapping {
299 now := time.Now()
300
301 m, ok := n.outboundMap[oKey]
302 if ok {
303 // check if this mapping is expired
304 if now.After(m.expires) {
305 n.removeMapping(m)
306 m = nil // expired
307 } else {
308 m.expires = time.Now().Add(n.natType.MappingLifeTime)
309 }
310 }
311
312 return m
313 }
314
315 // caller must hold the mutex
316 func (n *networkAddressTranslator) findInboundMapping(iKey string) *mapping {
317 now := time.Now()
318 m, ok := n.inboundMap[iKey]
319 if !ok {
320 return nil
321 }
322
323 // check if this mapping is expired
324 if now.After(m.expires) {
325 n.removeMapping(m)
326 return nil
327 }
328
329 return m
330 }
331
332 // caller must hold the mutex
333 func (n *networkAddressTranslator) removeMapping(m *mapping) {
334 oKey := fmt.Sprintf("%s:%s:%s", m.proto, m.local, m.bound)
335 iKey := fmt.Sprintf("%s:%s", m.proto, m.mapped)
336
337 delete(n.outboundMap, oKey)
338 delete(n.inboundMap, iKey)
339 }