-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxmpp.go
More file actions
406 lines (359 loc) · 9.9 KB
/
xmpp.go
File metadata and controls
406 lines (359 loc) · 9.9 KB
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
package main
import (
"bufio"
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/xml"
"flag"
"fmt"
"io"
"log"
"net"
"strings"
)
var (
xmppPort = flag.Int("xmpp-port", 6536, "XMPP proxy port")
enableXMPP = flag.Bool("enable-xmpp", false, "Enable XMPP proxy")
)
type XMPPProxy struct {
Port int
// Default remote port if not specified
DefaultRemotePort int
DefaultRemoteSTLSPort int
// TLS config for upstream connections
TLSConfig *tls.Config
ServerTLSConfig *tls.Config
// Enable debug logging
Debug bool
ServerCA tls.Certificate
}
type XMPPHello struct {
To string `xml:"to,attr"`
}
type XMPPConnection struct {
id string
clientConn net.Conn
serverConn net.Conn
protocol string
targetServer string
realUsername string
authenticated bool
tlsEnabled bool
reader *bufio.Reader
writer *bufio.Writer
serverReader *bufio.Reader
serverWriter *bufio.Writer
debug bool
defaultRemoteSTLSPort int
}
func xmppMain(systemRoots *x509.CertPool, ca tls.Certificate, tlsServerConfig *tls.Config) {
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
RootCAs: systemRoots,
}
if *enableXMPP {
proxy := &XMPPProxy{
Port: *xmppPort,
DefaultRemotePort: 5223,
DefaultRemoteSTLSPort: 5222,
TLSConfig: tlsConfig,
ServerTLSConfig: tlsServerConfig,
Debug: *debug,
ServerCA: ca,
}
proxy.Start()
log.Printf("XMPP Proxy started (%d)", *xmppPort)
}
}
// Start starts the mail proxy listener
func (p *XMPPProxy) Start() {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", p.Port))
if err != nil {
log.Fatalf("Failed to start XMPP proxy on port %d: %s", p.Port, err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
if p.Debug {
log.Printf("XMPP proxy accept error: %v", err)
}
continue
}
go p.handleConnection(conn)
}
}()
}
// handleConnection handles a single client connection
func (p *XMPPProxy) handleConnection(clientConn net.Conn) {
// Check if connection is from localhost unless allow-remote-connections is set
if *blockRemoteConnections {
host, _, err := net.SplitHostPort(clientConn.RemoteAddr().String())
if err != nil {
if p.Debug {
log.Printf("Error parsing remote address: %v", err)
}
clientConn.Close()
return
}
// Check if the connection is from localhost
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
if p.Debug {
log.Printf("Rejected non-localhost connection from %s", host)
}
clientConn.Close()
return
}
}
connID := fmt.Sprintf("%p", clientConn)
c := &XMPPConnection{
id: connID,
clientConn: clientConn,
reader: bufio.NewReader(clientConn),
writer: bufio.NewWriter(clientConn),
debug: p.Debug,
defaultRemoteSTLSPort: p.DefaultRemoteSTLSPort,
}
if c.debug {
log.Printf("[%s] New XMPP connection from %s", connID, clientConn.RemoteAddr())
}
conn := c.clientConn
cReader := bufio.NewReader(conn)
var xh XMPPHello
// Some clients forgets? to send the XML version.
for {
end, data := xmppCommandGet(cReader, c.id, conn, c.debug)
if end {
if c.debug {
log.Printf("XMPP connection got cut off")
}
return
}
if strings.HasPrefix(data, "<?xml version=") {
if c.debug {
log.Printf("Got xml version from client")
}
} else {
xml.Unmarshal([]byte(data), &xh)
if xh.To == "" {
if c.debug {
log.Printf("XMPP connection got cut off as to could not be found")
}
conn.Close()
return
}
break
}
}
conn.Write([]byte("<?xml version='1.0'?><stream:stream id='133742017' xmlns:stream='http://etherx.jabber.org/streams' xml:lang='en' version='1.0' xmlns='jabber:client'><stream:features><register xmlns='http://jabber.org/features/iq-register'/><starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required/></starttls></stream:features>\n"))
for { // until STARTTLS
end, data := xmppCommandGet(cReader, c.id, conn, c.debug)
if end {
if c.debug {
log.Printf("XMPP connection got cut off")
}
return
}
if strings.HasPrefix(data, "<starttls") {
conn.Write([]byte("<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"))
break // Woo!
} else {
if c.debug {
log.Printf("XMPP: Got unknown command, closing")
}
conn.Close()
return
}
}
// Peek at the ClientHello to determine routing
clientHello, err := peekClientHello(conn)
if err != nil {
log.Printf("[%s] Error on peeking handshake: %s", c.id, err)
return
}
if clientHello.isModernClient && *blockModernConnections {
return
}
var sConfig *tls.Config
// Create TLS server config
if p.ServerTLSConfig == nil {
sConfig = new(tls.Config)
} else {
sConfig = p.ServerTLSConfig
}
//sConfig.Certificates = []tls.Certificate{sConfig.RootCAs}
sConfig.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return &p.ServerCA, nil
}
// Create a connection that can replay the ClientHello
var tlsConn *tls.Conn
if clientHello != nil {
// We have already read the ClientHello, so we need to create a special connection
// that will replay it when the TLS handshake starts
replayConn := &replayConn{
Conn: conn,
buffer: bytes.NewBuffer(clientHello.raw),
}
tlsConn = tls.Server(replayConn, sConfig)
} else {
// No ClientHello was peeked, proceed normally
tlsConn = tls.Server(conn, sConfig)
}
// Perform TLS handshake
err = tlsConn.Handshake()
if err != nil {
log.Printf("[%s] Error on handshake: %s", c.id, err)
return
}
if c.debug {
log.Printf("[%s] Handshake finish", c.id)
}
c.targetServer = xh.To
err, stls := c.connectToServer(p.TLSConfig, p.DefaultRemotePort, false)
if stls {
if c.debug {
log.Printf("[%s] Failed DTLS, attempting STLS", c.id)
}
err, _ = c.connectToServer(p.TLSConfig, p.DefaultRemoteSTLSPort, true)
if err == nil {
if c.debug {
log.Printf("[%s] Connected", c.id)
}
scr := bufio.NewReader(c.serverConn)
_, err = c.serverConn.Write([]byte("<?xml version=\"1.0\"?>"))
_, err = c.serverConn.Write([]byte("<stream:stream xmlns:stream=\"http://etherx.jabber.org/streams\" xml:lang=\"en\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" to=\"" + xh.To + "\" xmlns=\"jabber:client\" version=\"1.0\">"))
//_, err = c.serverConn.Write([]byte("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>\r\n"))
for { // until STARTTLS
end, data := xmppCommandGet(scr, c.id, c.serverConn, c.debug)
if end {
if c.debug {
log.Printf("XMPP connection got cut off")
}
return
}
if strings.HasPrefix(data, "<?xml") { // Nobody cares
} else if strings.HasPrefix(data, "<stream:stream") {
} else if strings.HasPrefix(data, "<required") {
} else if strings.HasPrefix(data, "</starttls") {
} else if strings.HasPrefix(data, "</stream:features") {
} else if strings.HasPrefix(data, "<proceed") {
break
} else if strings.HasPrefix(data, "<starttls") {
} else if strings.HasPrefix(data, "<stream:features") {
c.serverConn.Write([]byte("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>\r\n"))
} else {
log.Printf("%s", data)
if c.debug {
log.Printf("XMPP server: Got unknown command, closing")
}
c.serverConn.Close()
return
}
}
if c.debug {
log.Printf("[%s] Handshake...", c.id)
}
var tlsConf *tls.Config
if p.TLSConfig == nil {
tlsConf = &tls.Config{
ServerName: c.targetServer,
}
} else {
tlsConf = p.TLSConfig
tlsConf.ServerName = c.targetServer
}
stlsConn := tls.Client(c.serverConn, tlsConf)
if err := tlsConn.Handshake(); err != nil {
conn.Close()
log.Printf("[%s] Server TLS handshake failed: %s", c.id, err)
}
c.serverConn = stlsConn
if c.debug {
log.Printf("[%s] Handshake should be done now", c.id)
}
}
}
if err != nil {
log.Printf("%s", err)
tlsConn.Close()
return
}
transparentProxy(c.id, c.debug, tlsConn, c.serverConn)
}
func (c *XMPPConnection) connectToServer(tlsConfig *tls.Config, port int, stls bool) (er error, requestsstls bool) {
var sn string
if stls {
sn = "xmpp-client"
} else {
sn = "xmpps-client"
}
host := c.targetServer
fallbackSN := ""
_, addrs, err := net.LookupSRV(sn, "tcp", host)
if !stls && (addrs[0].Target == "." || addrs[0].Port == 5222 || addrs[0].Port == uint16(c.defaultRemoteSTLSPort)) {
return fmt.Errorf("DTLS specified with no server STLS support"), !stls
} else {
fallbackSN = fmt.Sprintf("%s:%d", host, port)
host = addrs[0].Target
port = int(addrs[0].Port)
}
// Add port if not specified
server := host
if !strings.Contains(server, ":") {
server = fmt.Sprintf("%s:%d", server, port)
}
if c.debug {
log.Printf("[%s] Connecting to %s", c.id, server)
}
var tlsConf *tls.Config
if !stls {
if tlsConfig == nil {
tlsConf = &tls.Config{
ServerName: host,
}
} else {
tlsConf = tlsConfig
tlsConf.ServerName = host
}
}
var conn net.Conn
if !stls {
conn, err = tls.Dial("tcp", server, tlsConf)
} else {
conn, err = net.Dial("tcp", server)
}
if err != nil {
if fallbackSN != "" {
var err2 error
if !stls {
conn, err2 = tls.Dial("tcp", fallbackSN, tlsConf)
} else {
conn, err2 = net.Dial("tcp", fallbackSN)
}
if err2 != nil {
return fmt.Errorf("%s, %s", err, err2), !stls
}
c.serverConn = conn
return nil, stls
}
return err, !stls
}
c.serverConn = conn
return nil, stls
}
func xmppCommandGet(cReader *bufio.Reader, mcid string, conn net.Conn, debug bool) (end bool, data string) {
line, err := cReader.ReadString('>')
line = strings.Trim(line, " \n")
if err != nil {
if err != io.EOF {
log.Printf("[%s] Error reading from client: %v", mcid, err)
}
return true, ""
}
if debug {
log.Printf("[%s] Client: %s", mcid, strings.TrimSpace(line))
}
return false, line
}