-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_test.go
670 lines (561 loc) · 17.2 KB
/
tls_test.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
// Copyright (c) 2024 homuler
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
package mitm_test
import (
"bytes"
"crypto/tls"
"crypto/x509/pkix"
"errors"
"io"
"net"
"testing"
"github.com/homuler/mitm-go"
"github.com/homuler/mitm-go/internal/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type tlsEchoServer struct {
l net.Listener
tl net.Listener
err error
}
func newTLSEchoServer(t *testing.T) *tlsEchoServer {
l := testutil.NewTCPListener(t)
return &tlsEchoServer{l: l}
}
func (s *tlsEchoServer) addr() net.Addr {
return s.l.Addr()
}
func (s *tlsEchoServer) serverName() string {
addr := s.addr().String()
host, _, err := net.SplitHostPort(addr)
if err != nil {
panic(err)
}
return host
}
func (s *tlsEchoServer) close() error {
if s.tl != nil {
return s.tl.Close()
}
return s.l.Close()
}
func (s *tlsEchoServer) start(config *tls.Config) error {
if s.tl != nil {
return errors.New("already started")
}
s.tl = tls.NewListener(s.l, config)
go func() {
var lerr error
for {
conn, err := s.tl.Accept()
if err != nil {
lerr = err
break
}
go func() {
_, err := io.Copy(conn, conn)
if err != nil {
s.err = errors.Join(s.err, err)
}
}()
}
s.err = errors.Join(lerr, s.tl.Close())
}()
return nil
}
func setupServer(t *testing.T, mitmConfig *mitm.TLSConfig) (*tlsEchoServer, net.Listener) {
t.Helper()
// start a true server
tlsServer := newTLSEchoServer(t)
// start an MITM server
l := testutil.NewTCPListener(t)
mitmConfig.GetDestination = func(conn net.Conn, serverName string) net.Addr {
return tlsServer.addr()
}
tl, err := mitm.NewTLSListener(l, mitmConfig)
require.NoError(t, err, "failed to create an MITM listener")
return tlsServer, tl
}
func assertTLSError(t *testing.T, err error, expected string) bool {
t.Helper()
if expected == "" {
return assert.NoError(t, err)
} else {
return assert.ErrorContains(t, err, expected)
}
}
func TestNewTLSListener_fails_if_the_root_certificate_is_missing(t *testing.T) {
t.Parallel()
_, err := mitm.NewTLSListener(nil, &mitm.TLSConfig{})
assert.ErrorIs(t, err, mitm.ErrInvalidTLSConfig)
}
func TestNewTLSListner_dials_remote_server(t *testing.T) {
t.Parallel()
mitmCACert := testutil.MITMCACert(t)
rootCAs := testutil.RootCAs(t)
clientRootCAs := testutil.ClientRootCAs(t)
getInvalidServerConfig := func(t *testing.T, _ *tlsEchoServer) *tls.Config {
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, &net.IPAddr{})
return &tls.Config{Certificates: []tls.Certificate{*serverCert}}
}
getValidServerConfig := func(t *testing.T, s *tlsEchoServer) *tls.Config {
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, s.addr())
return &tls.Config{Certificates: []tls.Certificate{*serverCert}, NextProtos: []string{"a", "b"}}
}
cases := []struct {
name string
mitmListenerConfig *mitm.TLSConfig
getServerConfig func(*testing.T, *tlsEchoServer) *tls.Config
nextProtos []string
mitmErr string
clientErr string
}{
{
name: "server certificate is not valid for any names",
mitmListenerConfig: &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetClientConfig: func(serverName string, _ []string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: rootCAs}
},
},
getServerConfig: getInvalidServerConfig,
mitmErr: mitm.ErrHandshakeWithServer.Error(),
clientErr: "remote error: tls: internal error",
},
{
name: "server certificate is not valid but the validation is skipped",
mitmListenerConfig: &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetClientConfig: func(serverName string, _ []string) *tls.Config {
return &tls.Config{ServerName: serverName, InsecureSkipVerify: true}
},
},
getServerConfig: getInvalidServerConfig,
mitmErr: "remote error: tls: bad certificate",
clientErr: "tls: failed to verify certificate",
},
{
name: "server certificate is signed by unknown authority",
mitmListenerConfig: &mitm.TLSConfig{
RootCertificate: mitmCACert,
},
getServerConfig: getValidServerConfig,
mitmErr: mitm.ErrHandshakeWithServer.Error(),
clientErr: "remote error: tls: internal error",
},
{
name: "server certificate is invalid and client supports ALPN",
mitmListenerConfig: &mitm.TLSConfig{
RootCertificate: mitmCACert,
},
getServerConfig: getValidServerConfig,
nextProtos: []string{"a"},
mitmErr: mitm.ErrHandshakeWithServer.Error(),
clientErr: "remote error: tls: internal error",
},
{
name: "server certificate is valid",
mitmListenerConfig: &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetClientConfig: func(serverName string, _ []string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: rootCAs}
},
},
getServerConfig: getValidServerConfig,
},
}
for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
t.Parallel()
tlsServer, tl := setupServer(t, c.mitmListenerConfig)
defer tlsServer.close()
defer tl.Close()
// start a true server
serverConfig := c.getServerConfig(t, tlsServer)
err := tlsServer.start(serverConfig)
require.NoError(t, err, "failed to start a TLS echo server")
// start an MITM server
done := make(chan struct{})
go func() {
// only serve the first connection
conn, err := tl.Accept()
if !assert.NoErrorf(t, err, "unexpected listener error") {
return
}
defer conn.Close()
_, err = io.Copy(io.Discard, conn)
assertTLSError(t, err, c.mitmErr)
close(done)
}()
// a client dials the MITM server
mitmAddr := tl.Addr()
clientConn, err := tls.Dial(mitmAddr.Network(), mitmAddr.String(), &tls.Config{
ServerName: tlsServer.serverName(),
RootCAs: clientRootCAs,
NextProtos: c.nextProtos,
})
assertTLSError(t, err, c.clientErr)
if clientConn != nil {
clientConn.Close()
}
<-done
})
}
}
func TestNewTLSListner_supports_ALPN(t *testing.T) {
t.Parallel()
mitmCACert := testutil.MITMCACert(t)
rootCAs := testutil.RootCAs(t)
clientRootCAs := testutil.ClientRootCAs(t)
cases := []struct {
name string
serverNextProtos []string
mitmNextProtos []string
clientNextProtos []string
expectedProto string
mitmErr string
clientErr string
}{
{
name: "server & client does not support ALPN",
mitmNextProtos: []string{"a", "b", "c", "d"},
expectedProto: "",
},
{
name: "server rejects all",
serverNextProtos: []string{"c"},
clientNextProtos: []string{"a", "b"},
expectedProto: "",
mitmErr: mitm.ErrHandshakeWithServer.Error(),
clientErr: "remote error: tls: internal error",
},
{
name: "server accepts the 2nd",
serverNextProtos: []string{"b", "c"},
clientNextProtos: []string{"a", "b"},
expectedProto: "b",
},
{
name: "server accepts the first",
serverNextProtos: []string{"a", "b"},
clientNextProtos: []string{"a", "b"},
expectedProto: "a",
},
{
name: "MITM server rejects the first",
serverNextProtos: []string{"a", "b"},
mitmNextProtos: []string{"b"},
clientNextProtos: []string{"a", "b"},
expectedProto: "b",
},
{
name: "client does not support ALPN",
serverNextProtos: []string{"a", "b"},
expectedProto: "",
},
{
name: "server does not support ALPN",
serverNextProtos: nil,
mitmNextProtos: []string{"a", "b"},
clientNextProtos: []string{"a", "b"},
expectedProto: "",
},
}
for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
t.Parallel()
tlsServer, tl := setupServer(t, &mitm.TLSConfig{
RootCertificate: mitmCACert,
NextProtos: c.mitmNextProtos,
GetClientConfig: func(serverName string, alpnProtocols []string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: rootCAs, NextProtos: alpnProtocols}
},
})
defer tlsServer.close()
defer tl.Close()
// start a true server
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, tlsServer.addr())
err := tlsServer.start(&tls.Config{
Certificates: []tls.Certificate{*serverCert},
NextProtos: c.serverNextProtos,
})
require.NoError(t, err, "failed to start a TLS echo server")
// start an MITM server
done := make(chan struct{})
go func() {
// only serve the first connection
conn, err := tl.Accept()
if !assert.NoError(t, err, "unexpected listener error") {
return
}
defer conn.Close()
_, err = io.Copy(io.Discard, conn)
assertTLSError(t, err, c.mitmErr)
close(done)
}()
// a client dials the MITM server
mitmAddr := tl.Addr()
clientConn, err := tls.Dial(mitmAddr.Network(), mitmAddr.String(), &tls.Config{
ServerName: tlsServer.serverName(),
RootCAs: clientRootCAs,
NextProtos: c.clientNextProtos,
})
assertTLSError(t, err, c.clientErr)
if clientConn == nil {
assert.Emptyf(t, c.expectedProto, "expected proto %s, but client connection is nil", c.expectedProto)
} else {
assert.Equalf(t, c.expectedProto, clientConn.ConnectionState().NegotiatedProtocol, "unexpected negotiated protocol")
clientConn.Close()
}
<-done
})
}
}
func TestNewTLSListner_can_serve_different_protocols(t *testing.T) {
t.Parallel()
mitmCACert := testutil.MITMCACert(t)
rootCAs := testutil.RootCAs(t)
clientRootCAs := testutil.ClientRootCAs(t)
tlsServer, tl := setupServer(t, &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetClientConfig: func(serverName string, alpnProtocols []string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: rootCAs, NextProtos: alpnProtocols}
},
})
defer tlsServer.close()
defer tl.Close()
// start a true server
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, tlsServer.addr())
err := tlsServer.start(&tls.Config{
Certificates: []tls.Certificate{*serverCert},
NextProtos: []string{"a", "b"},
})
require.NoError(t, err, "failed to start a TLS echo server")
// start an MITM server
errs := make(chan error)
go func() {
for {
conn, err := tl.Accept()
if err != nil {
break
}
defer conn.Close()
go func() {
_, err := io.Copy(io.Discard, conn)
errs <- err
}()
}
}()
// multiple client dials the MITM server
mitmAddr := tl.Addr()
cases := []struct {
name string
nextProtos []string
expectedProto string
mitmErr string
clientErr string
}{
{
name: "client does not support ALPN",
expectedProto: "",
},
{
name: "client and server supports the same protocols",
nextProtos: []string{"a", "b"},
expectedProto: "a",
},
{
name: "client and server supports the same protocols but the preference is different",
nextProtos: []string{"b", "a"},
expectedProto: "a",
},
{
name: "client and server agree on the 2nd protocol",
nextProtos: []string{"c", "b"},
expectedProto: "b",
},
{
name: "client and server fail to agree on the protocol",
nextProtos: []string{"c"},
mitmErr: mitm.ErrHandshakeWithServer.Error(),
clientErr: "remote error: tls: internal error",
},
{
name: "client have requested the same nextProtos once (ok)",
nextProtos: []string{"c", "b"},
expectedProto: "b",
},
{
name: "client have requested the same naxtProtos once (error)",
nextProtos: []string{"c"},
mitmErr: mitm.ErrHandshakeWithServer.Error(),
clientErr: "remote error: tls: internal error",
},
}
for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
clientConn, err := tls.Dial(mitmAddr.Network(), mitmAddr.String(), &tls.Config{
ServerName: tlsServer.serverName(),
RootCAs: clientRootCAs,
NextProtos: c.nextProtos,
})
assertTLSError(t, err, c.clientErr)
if clientConn == nil {
assert.Emptyf(t, c.expectedProto, "expected proto %s, but client connection is nil", c.expectedProto)
} else {
assert.Equalf(t, c.expectedProto, clientConn.ConnectionState().NegotiatedProtocol, "unexpected negotiated protocol")
clientConn.Close()
}
err = <-errs
assertTLSError(t, err, c.mitmErr)
})
}
}
func TestNewTLSListner_can_read_messages_from_client(t *testing.T) {
t.Parallel()
mitmCACert := testutil.MITMCACert(t)
rootCAs := testutil.RootCAs(t)
clientRootCAs := testutil.ClientRootCAs(t)
tlsServer, tl := setupServer(t, &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetClientConfig: func(serverName string, alpnProtocols []string) *tls.Config {
return &tls.Config{RootCAs: rootCAs}
},
})
defer tlsServer.close()
defer tl.Close()
// start a true server
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, tlsServer.addr())
err := tlsServer.start(&tls.Config{
Certificates: []tls.Certificate{*serverCert},
})
require.NoError(t, err, "failed to start a TLS echo server")
// start an MITM server
done := make(chan struct{})
buf := bytes.NewBuffer(nil)
go func() {
// only serve the first connection
conn, err := tl.Accept()
if !assert.NoError(t, err, "unexpected listener error") {
return
}
defer conn.Close()
_, err = io.Copy(buf, conn)
assert.NoError(t, err)
close(done)
}()
mitmAddr := tl.Addr()
clientConn, err := tls.Dial(mitmAddr.Network(), mitmAddr.String(), &tls.Config{
ServerName: tlsServer.serverName(),
RootCAs: clientRootCAs,
})
require.NoError(t, err, "failed to dial the MITM server")
msg := "hello, world\n"
_, err = clientConn.Write([]byte(msg))
require.NoError(t, err, "failed to send a message to the MITM server")
clientConn.Close()
<-done
assert.Equal(t, msg, buf.String(), "MITM server received an unexpected message")
}
func TestNewTLSListner_can_serve_if_client_does_not_support_SNI(t *testing.T) {
t.Parallel()
mitmCACert := testutil.MITMCACert(t)
rootCAs := testutil.RootCAs(t)
clientRootCAs := testutil.ClientRootCAs(t)
// start a true server
tlsServer := newTLSEchoServer(t)
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, tlsServer.addr())
err := tlsServer.start(&tls.Config{
Certificates: []tls.Certificate{*serverCert},
})
require.NoError(t, err, "failed to start a TLS echo server")
defer tlsServer.close()
// start an MITM server
l := testutil.NewTCPListener(t)
tl, err := mitm.NewTLSListener(l, &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetDestination: func(conn net.Conn, serverName string) net.Addr {
return tlsServer.addr()
},
GetClientConfig: func(serverName string, alpnProtocols []string) *tls.Config {
return &tls.Config{RootCAs: rootCAs}
},
})
require.NoError(t, err, "failed to create an MITM listener")
defer tl.Close()
done := make(chan struct{})
buf := bytes.NewBuffer(nil)
go func() {
// only serve the first connection
conn, err := tl.Accept()
if !assert.NoError(t, err, "unexpected listener error") {
return
}
defer conn.Close()
_, err = io.Copy(buf, conn)
assert.NoError(t, err)
close(done)
}()
mitmAddr := tl.Addr()
clientConn, err := tls.Dial(mitmAddr.Network(), mitmAddr.String(), &tls.Config{
RootCAs: clientRootCAs,
})
require.NoError(t, err, "failed to dial the MITM server")
msg := "hello, world\n"
_, err = clientConn.Write([]byte(msg))
require.NoError(t, err, "failed to send a message to the MITM server")
clientConn.Close()
<-done
assert.Equal(t, msg, buf.String(), "MITM server received an unexpected message")
}
func TestNewTLSListner_can_handle_invalid_client(t *testing.T) {
t.Parallel()
mitmCACert := testutil.MITMCACert(t)
rootCAs := testutil.RootCAs(t)
tlsServer, tl := setupServer(t, &mitm.TLSConfig{
RootCertificate: mitmCACert,
GetClientConfig: func(serverName string, alpnProtocols []string) *tls.Config {
return &tls.Config{ServerName: serverName, RootCAs: rootCAs}
},
})
defer tlsServer.close()
defer tl.Close()
// start a true server
serverCert := testutil.MustIssueCertificate(t, pkix.Name{CommonName: "example.com"}, tlsServer.addr())
err := tlsServer.start(&tls.Config{
Certificates: []tls.Certificate{*serverCert},
})
require.NoError(t, err, "failed to start a TLS echo server")
// start an MITM server
done := make(chan struct{})
go func() {
// only serve the first connection
conn, err := tl.Accept()
if !assert.NoError(t, err, "unexpected listener error") {
return
}
defer conn.Close()
_, err = io.Copy(io.Discard, conn)
assertTLSError(t, err, "tls: first record does not look like a TLS handshake")
close(done)
}()
mitmAddr := tl.Addr()
clientConn, err := net.Dial(mitmAddr.Network(), mitmAddr.String())
require.NoError(t, err, "failed to dial the MITM server")
defer clientConn.Close()
_, err = clientConn.Write([]byte("hello, world\n"))
assert.NoError(t, err, "failed to write to the MITM server")
<-done
}
func TestNewTLSServer_fails_if_the_root_certificate_is_missing(t *testing.T) {
t.Parallel()
_, err := mitm.NewTLSServer(nil, &mitm.TLSConfig{})
assert.ErrorIs(t, err, mitm.ErrInvalidTLSConfig)
}