forked from pion/stun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
332 lines (293 loc) · 9.35 KB
/
main.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
// This cmd implements RFC5780's tests:
// - 4.3. Determining NAT Mapping Behavior
// - 4.4. Determining NAT Filtering Behavior
package main
import (
"errors"
"flag"
"net"
"os"
"time"
"github.com/pion/logging"
"github.com/pion/stun"
)
type stunServerConn struct {
conn net.PacketConn
LocalAddr net.Addr
RemoteAddr *net.UDPAddr
OtherAddr *net.UDPAddr
messageChan chan *stun.Message
}
func (c *stunServerConn) Close() error {
return c.conn.Close()
}
var (
addrStrPtr = flag.String("server", "stun.voip.blackberry.com:3478", "STUN server address") // nolint:gochecknoglobals
timeoutPtr = flag.Int("timeout", 3, "the number of seconds to wait for STUN server's response") // nolint:gochecknoglobals
verbose = flag.Int("verbose", 1, "the verbosity level") // nolint:gochecknoglobals
log logging.LeveledLogger // nolint:gochecknoglobals
)
const (
messageHeaderSize = 20
)
var (
errResponseMessage = errors.New("error reading from response message channel")
errTimedOut = errors.New("timed out waiting for response")
errNoOtherAddress = errors.New("no OTHER-ADDRESS in message")
)
func main() {
flag.Parse()
var logLevel logging.LogLevel
switch *verbose {
case 0:
logLevel = logging.LogLevelWarn
case 1:
logLevel = logging.LogLevelInfo // default
case 2:
logLevel = logging.LogLevelDebug
case 3:
logLevel = logging.LogLevelTrace
}
log = logging.NewDefaultLeveledLoggerForScope("", logLevel, os.Stdout)
if err := mappingTests(*addrStrPtr); err != nil {
log.Warn("NAT mapping behavior: inconclusive")
}
if err := filteringTests(*addrStrPtr); err != nil {
log.Warn("NAT filtering behavior: inconclusive")
}
}
// RFC5780: 4.3. Determining NAT Mapping Behavior
func mappingTests(addrStr string) error {
mapTestConn, err := connect(addrStr)
if err != nil {
log.Warnf("Error creating STUN connection: %s\n", err.Error())
return err
}
// Test I: Regular binding request
log.Info("Mapping Test I: Regular binding request")
request := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
resp, err := mapTestConn.roundTrip(request, mapTestConn.RemoteAddr)
if err != nil {
return err
}
// Parse response message for XOR-MAPPED-ADDRESS and make sure OTHER-ADDRESS valid
resps1 := parse(resp)
if resps1.xorAddr == nil || resps1.otherAddr == nil {
log.Info("Error: NAT discovery feature not supported by this server")
return errNoOtherAddress
}
addr, err := net.ResolveUDPAddr("udp4", resps1.otherAddr.String())
if err != nil {
log.Infof("Failed resolving OTHER-ADDRESS: %v\n", resps1.otherAddr)
return err
}
mapTestConn.OtherAddr = addr
log.Infof("Received XOR-MAPPED-ADDRESS: %v\n", resps1.xorAddr)
// Assert mapping behavior
if resps1.xorAddr.String() == mapTestConn.LocalAddr.String() {
log.Warn("=> NAT mapping behavior: endpoint independent (no NAT)")
return nil
}
// Test II: Send binding request to the other address but primary port
log.Info("Mapping Test II: Send binding request to the other address but primary port")
oaddr := *mapTestConn.OtherAddr
oaddr.Port = mapTestConn.RemoteAddr.Port
resp, err = mapTestConn.roundTrip(request, &oaddr)
if err != nil {
return err
}
// Assert mapping behavior
resps2 := parse(resp)
log.Infof("Received XOR-MAPPED-ADDRESS: %v\n", resps2.xorAddr)
if resps2.xorAddr.String() == resps1.xorAddr.String() {
log.Warn("=> NAT mapping behavior: endpoint independent")
return nil
}
// Test III: Send binding request to the other address and port
log.Info("Mapping Test III: Send binding request to the other address and port")
resp, err = mapTestConn.roundTrip(request, mapTestConn.OtherAddr)
if err != nil {
return err
}
// Assert mapping behavior
resps3 := parse(resp)
log.Infof("Received XOR-MAPPED-ADDRESS: %v\n", resps3.xorAddr)
if resps3.xorAddr.String() == resps2.xorAddr.String() {
log.Warn("=> NAT mapping behavior: address dependent")
} else {
log.Warn("=> NAT mapping behavior: address and port dependent")
}
return mapTestConn.Close()
}
// RFC5780: 4.4. Determining NAT Filtering Behavior
func filteringTests(addrStr string) error {
mapTestConn, err := connect(addrStr)
if err != nil {
log.Warnf("Error creating STUN connection: %s\n", err.Error())
return err
}
// Test I: Regular binding request
log.Info("Filtering Test I: Regular binding request")
request := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
resp, err := mapTestConn.roundTrip(request, mapTestConn.RemoteAddr)
if err != nil || errors.Is(err, errTimedOut) {
return err
}
resps := parse(resp)
if resps.xorAddr == nil || resps.otherAddr == nil {
log.Warn("Error: NAT discovery feature not supported by this server")
return errNoOtherAddress
}
addr, err := net.ResolveUDPAddr("udp4", resps.otherAddr.String())
if err != nil {
log.Infof("Failed resolving OTHER-ADDRESS: %v\n", resps.otherAddr)
return err
}
mapTestConn.OtherAddr = addr
// Test II: Request to change both IP and port
log.Info("Filtering Test II: Request to change both IP and port")
request = stun.MustBuild(stun.TransactionID, stun.BindingRequest)
request.Add(stun.AttrChangeRequest, []byte{0x00, 0x00, 0x00, 0x06})
resp, err = mapTestConn.roundTrip(request, mapTestConn.RemoteAddr)
if err == nil {
parse(resp) // just to print out the resp
log.Warn("=> NAT filtering behavior: endpoint independent")
return nil
} else if !errors.Is(err, errTimedOut) {
return err // something else went wrong
}
// Test III: Request to change port only
log.Info("Filtering Test III: Request to change port only")
request = stun.MustBuild(stun.TransactionID, stun.BindingRequest)
request.Add(stun.AttrChangeRequest, []byte{0x00, 0x00, 0x00, 0x02})
resp, err = mapTestConn.roundTrip(request, mapTestConn.RemoteAddr)
if err == nil {
parse(resp) // just to print out the resp
log.Warn("=> NAT filtering behavior: address dependent")
} else if errors.Is(err, errTimedOut) {
log.Warn("=> NAT filtering behavior: address and port dependent")
}
return mapTestConn.Close()
}
// Parse a STUN message
func parse(msg *stun.Message) (ret struct {
xorAddr *stun.XORMappedAddress
otherAddr *stun.OtherAddress
respOrigin *stun.ResponseOrigin
mappedAddr *stun.MappedAddress
software *stun.Software
}) {
ret.mappedAddr = &stun.MappedAddress{}
ret.xorAddr = &stun.XORMappedAddress{}
ret.respOrigin = &stun.ResponseOrigin{}
ret.otherAddr = &stun.OtherAddress{}
ret.software = &stun.Software{}
if ret.xorAddr.GetFrom(msg) != nil {
ret.xorAddr = nil
}
if ret.otherAddr.GetFrom(msg) != nil {
ret.otherAddr = nil
}
if ret.respOrigin.GetFrom(msg) != nil {
ret.respOrigin = nil
}
if ret.mappedAddr.GetFrom(msg) != nil {
ret.mappedAddr = nil
}
if ret.software.GetFrom(msg) != nil {
ret.software = nil
}
log.Debugf("%v\n", msg)
log.Debugf("\tMAPPED-ADDRESS: %v\n", ret.mappedAddr)
log.Debugf("\tXOR-MAPPED-ADDRESS: %v\n", ret.xorAddr)
log.Debugf("\tRESPONSE-ORIGIN: %v\n", ret.respOrigin)
log.Debugf("\tOTHER-ADDRESS: %v\n", ret.otherAddr)
log.Debugf("\tSOFTWARE: %v\n", ret.software)
for _, attr := range msg.Attributes {
switch attr.Type {
case
stun.AttrXORMappedAddress,
stun.AttrOtherAddress,
stun.AttrResponseOrigin,
stun.AttrMappedAddress,
stun.AttrSoftware:
break //nolint: staticcheck
default:
log.Debugf("\t%v (l=%v)\n", attr, attr.Length)
}
}
return ret
}
// Given an address string, returns a StunServerConn
func connect(addrStr string) (*stunServerConn, error) {
log.Infof("connecting to STUN server: %s\n", addrStr)
addr, err := net.ResolveUDPAddr("udp4", addrStr)
if err != nil {
log.Warnf("Error resolving address: %s\n", err.Error())
return nil, err
}
c, err := net.ListenUDP("udp4", nil)
if err != nil {
return nil, err
}
log.Infof("Local address: %s\n", c.LocalAddr())
log.Infof("Remote address: %s\n", addr.String())
mChan := listen(c)
return &stunServerConn{
conn: c,
LocalAddr: c.LocalAddr(),
RemoteAddr: addr,
messageChan: mChan,
}, nil
}
// Send request and wait for response or timeout
func (c *stunServerConn) roundTrip(msg *stun.Message, addr net.Addr) (*stun.Message, error) {
_ = msg.NewTransactionID()
log.Infof("Sending to %v: (%v bytes)\n", addr, msg.Length+messageHeaderSize)
log.Debugf("%v\n", msg)
for _, attr := range msg.Attributes {
log.Debugf("\t%v (l=%v)\n", attr, attr.Length)
}
_, err := c.conn.WriteTo(msg.Raw, addr)
if err != nil {
log.Warnf("Error sending request to %v\n", addr)
return nil, err
}
// Wait for response or timeout
select {
case m, ok := <-c.messageChan:
if !ok {
return nil, errResponseMessage
}
return m, nil
case <-time.After(time.Duration(*timeoutPtr) * time.Second):
log.Infof("Timed out waiting for response from server %v\n", addr)
return nil, errTimedOut
}
}
// taken from https://github.com/pion/stun/blob/master/cmd/stun-traversal/main.go
func listen(conn *net.UDPConn) (messages chan *stun.Message) {
messages = make(chan *stun.Message)
go func() {
for {
buf := make([]byte, 1024)
n, addr, err := conn.ReadFromUDP(buf)
if err != nil {
close(messages)
return
}
log.Infof("Response from %v: (%v bytes)\n", addr, n)
buf = buf[:n]
m := new(stun.Message)
m.Raw = buf
err = m.Decode()
if err != nil {
log.Infof("Error decoding message: %v\n", err)
close(messages)
return
}
messages <- m
}
}()
return
}