forked from elastic/logstash-forwarder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher1_test.go
231 lines (201 loc) · 6.69 KB
/
publisher1_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
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"io/ioutil"
"log"
"math/big"
"net"
"os"
"sync"
"testing"
"time"
)
const strict bool = true
const insecure bool = false
const caKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDXQK+POFCtDlYgc2nQTnZ+WfaPQg1ms9JjomZ9vZXpqH9JaxBj
jWKTyg7k6GOXpNbaET76nlWLtAKKofesOGwadil/HtyEwXxvXJY/UTdkqtwCFjPS
5XR5fNTkVK2sLw23Z67TIBApIGR42a7WhaP/BFv6zc/wpxDnokpLtJkvlQIDAQAB
AoGAA6paUvoGhavk05CjkKSFaAloJXBegg012/R8AlAkKWJxKHLmSIuzzgh20HcU
mxR3hCcfB22Cz2o1UN8JNKmRTaoMrPHf4gv0MIlcEBumxh8nyFiBocXimqJKHWHY
PMWzOoyhgBIXPoAIkm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67TIBApIGR42a7WhaP/BFv6zc/wpxDnokpLtJkv
lQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFzkH8T+dU40g330QnDp2qO0XTfhNOsC
fjUOGYo7F6eqfBcQColcE+BLKc1aKEAAEvzokQi72L7xuOenJUzpGaIJXGkmGZsV
2OIO5Zf4ChZTMuut9yPjer9sTt0pZUNsOSg6o7hBeXlCMEvoM/31ag2sxZaOKA/Z
p/X0O4Qz0RTF
-----END CERTIFICATE-----`
var listening sync.WaitGroup
func init() { log.SetFlags(0) }
func makeCert(host string) tls.Certificate {
ca, err := tls.X509KeyPair([]byte(caCert), []byte(caKey))
caCert, err := x509.ParseCertificate(ca.Certificate[0])
if err != nil {
panic(err)
}
tpl := x509.Certificate{
SerialNumber: new(big.Int).SetInt64(0),
Subject: pkix.Name{CommonName: host},
NotBefore: time.Now().AddDate(-1, 0, 0).UTC(),
NotAfter: time.Now().AddDate(1, 0, 0).UTC(),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
SubjectKeyId: []byte{1, 2, 3, 4},
Version: 2,
}
if ip := net.ParseIP(host); ip != nil {
tpl.IPAddresses = []net.IP{ip}
}
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}
der, err := x509.CreateCertificate(rand.Reader, &tpl, caCert, &key.PublicKey, ca.PrivateKey)
if err != nil {
panic(err)
}
bcrt := &pem.Block{Type: "CERTIFICATE", Bytes: der}
bkey := &pem.Block{Type: "PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}
v, err := tls.X509KeyPair(pem.EncodeToMemory(bcrt), pem.EncodeToMemory(bkey))
if err != nil {
panic(err)
}
return v
}
func listenWithCert(hostname string, address string) {
listening.Add(1)
go func() {
log.Println("DEBUG - start mock server ..")
// Establish a dummy TLS server
var serverConfig tls.Config
kp := makeCert(hostname)
serverConfig.Certificates = []tls.Certificate{kp}
listener, err := tls.Listen("tcp", address, &serverConfig)
if err != nil {
panic(err)
}
// Listen and handshake for a single connection
defer listener.Close()
listening.Done()
conn, err := listener.Accept()
if err != nil {
panic(err)
}
defer conn.Close()
tlsconn, ok := conn.(*tls.Conn)
if !ok {
panic("conn should of *tls.Conn")
}
if err := tlsconn.Handshake(); err != nil {
return
}
}()
listening.Wait()
}
func tryConnect(addr string, strict bool) (errchan chan error) {
errchan = make(chan error)
go func() {
caCertFile, err := ioutil.TempFile("", "logstash-forwarder-cacert")
if err != nil {
panic(err)
}
defer func() { os.Remove(caCertFile.Name()) }()
ioutil.WriteFile(caCertFile.Name(), []byte(caCert), os.ModeTemporary)
// this can be messy because of localhost resolving to ipv6 addresses
// but there's no easy way to disable v6 resolution here
const wait = 5
const retryLimit = 3
tryAttempt := 0
exinfo := ""
config := &NetworkConfig{
SSLCA: caCertFile.Name(),
Servers: []string{addr},
Timeout: wait,
timeout: time.Second * wait,
}
var socket *tls.Conn
for socket == nil && tryAttempt < retryLimit {
select {
case socket = <-doConnect(config):
case <-time.After(time.Second * wait):
log.Printf("INFO: Connect timeout: attempt: %d\n", tryAttempt)
tryAttempt++
}
}
if socket == nil {
errchan <- errors.New("Client connect failed. " + exinfo)
return
}
defer socket.Close()
log.Printf("INFO: Connected to %s\n", socket.RemoteAddr())
if !socket.ConnectionState().HandshakeComplete {
errchan <- errors.New("handshake should be complete")
return
}
errchan <- nil
}()
return errchan
}
func doConnect(config *NetworkConfig) <-chan *tls.Conn {
sockchan := make(chan *tls.Conn)
go func() {
sockchan <- connect(config)
}()
return sockchan
}
// ----------------------------------------------------------------------
// Strict
// ----------------------------------------------------------------------
// CA certificate is CN=ca.logstash.test in test/ca.crt, test/ca.key
// Server certificate is CN=localhost, signed by above CA, in test/server.crt, test/server.key
func TestStrictConnectValidCertificate(t *testing.T) {
log.Println("\n-- TestStrictConnectValidCertificate -- ")
listenWithCert("localhost", "0.0.0.0:19876")
if err := <-tryConnect("localhost:19876", strict); err != nil {
t.Fatal("Should have succeeded", err)
}
}
func TestStrictConnectMismatchedCN(t *testing.T) {
log.Println("\n-- TestStrictConnectMismatchedCN -- ")
listenWithCert("localalt", "0.0.0.0:19876")
if err := <-tryConnect("localhost:19876", strict); err == nil {
t.Fatal("Should have failed but didn't!")
}
}
func TestStrictConnectToIpWithoutSAN(t *testing.T) {
log.Println("\n-- TestStrictConnectToIpWithoutSAN -- ")
listenWithCert("localhost", "0.0.0.0:19876")
if err := <-tryConnect("127.0.0.1:19876", strict); err == nil {
t.Fatal("Should have failed but didn't!")
}
}
func TestStrictConnectToIpWithSAN(t *testing.T) {
log.Println("\n-- TestStrictConnectToIpWithSAN -- ")
listenWithCert("127.0.0.1", "0.0.0.0:19876")
if err := <-tryConnect("127.0.0.1:19876", strict); err != nil {
t.Fatal("Should not have failed", err)
}
}