transport_test.go 13.5 KB
Newer Older
Marten Seemann's avatar
Marten Seemann committed
1 2 3 4
package libp2ptls

import (
	"context"
Marten Seemann's avatar
Marten Seemann committed
5
	"crypto"
Marten Seemann's avatar
Marten Seemann committed
6 7
	"crypto/ecdsa"
	"crypto/elliptic"
Marten Seemann's avatar
Marten Seemann committed
8 9
	"crypto/rand"
	"crypto/rsa"
10 11
	"crypto/tls"
	"crypto/x509"
Marten Seemann's avatar
Marten Seemann committed
12 13
	"crypto/x509/pkix"
	"encoding/asn1"
Marten Seemann's avatar
Marten Seemann committed
14
	"fmt"
15
	"math/big"
Marten Seemann's avatar
Marten Seemann committed
16
	mrand "math/rand"
Marten Seemann's avatar
Marten Seemann committed
17
	"net"
18 19 20
	"time"

	"github.com/onsi/gomega/gbytes"
Marten Seemann's avatar
Marten Seemann committed
21
	"github.com/onsi/gomega/types"
Marten Seemann's avatar
Marten Seemann committed
22 23

	cs "github.com/libp2p/go-conn-security"
Marten Seemann's avatar
Marten Seemann committed
24
	ci "github.com/libp2p/go-libp2p-crypto"
Marten Seemann's avatar
Marten Seemann committed
25 26 27 28 29
	peer "github.com/libp2p/go-libp2p-peer"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

30 31 32
type transform struct {
	name      string
	apply     func(*Identity)
Marten Seemann's avatar
Marten Seemann committed
33
	remoteErr types.GomegaMatcher // the error that the side validating the chain gets
34 35
}

Marten Seemann's avatar
Marten Seemann committed
36 37
var _ = Describe("Transport", func() {
	var (
Marten Seemann's avatar
Marten Seemann committed
38
		serverKey, clientKey ci.PrivKey
Marten Seemann's avatar
Marten Seemann committed
39 40 41
		serverID, clientID   peer.ID
	)

Marten Seemann's avatar
Marten Seemann committed
42 43
	createPeer := func() (peer.ID, ci.PrivKey) {
		var priv ci.PrivKey
Marten Seemann's avatar
Marten Seemann committed
44 45 46
		var err error
		switch mrand.Int() % 4 {
		case 0:
Marten Seemann's avatar
Marten Seemann committed
47
			fmt.Fprintf(GinkgoWriter, " using an ECDSA key: ")
Marten Seemann's avatar
Marten Seemann committed
48
			priv, _, err = ci.GenerateECDSAKeyPair(rand.Reader)
Marten Seemann's avatar
Marten Seemann committed
49
		case 1:
Marten Seemann's avatar
Marten Seemann committed
50
			fmt.Fprintf(GinkgoWriter, " using an RSA key: ")
Marten Seemann's avatar
Marten Seemann committed
51
			priv, _, err = ci.GenerateRSAKeyPair(1024, rand.Reader)
Marten Seemann's avatar
Marten Seemann committed
52 53 54 55 56 57
		case 2:
			fmt.Fprintf(GinkgoWriter, " using an Ed25519 key: ")
			priv, _, err = ci.GenerateEd25519Key(rand.Reader)
		case 3:
			fmt.Fprintf(GinkgoWriter, " using an Ed25519 key: ")
			priv, _, err = ci.GenerateSecp256k1Key(rand.Reader)
Marten Seemann's avatar
Marten Seemann committed
58
		}
Marten Seemann's avatar
Marten Seemann committed
59
		Expect(err).ToNot(HaveOccurred())
Marten Seemann's avatar
Marten Seemann committed
60 61
		id, err := peer.IDFromPrivateKey(priv)
		Expect(err).ToNot(HaveOccurred())
Marten Seemann's avatar
Marten Seemann committed
62
		fmt.Fprintln(GinkgoWriter, id.Pretty())
Marten Seemann's avatar
Marten Seemann committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
		return id, priv
	}

	connect := func() (net.Conn, net.Conn) {
		ln, err := net.Listen("tcp", "localhost:0")
		Expect(err).ToNot(HaveOccurred())
		defer ln.Close()
		serverConnChan := make(chan net.Conn)
		go func() {
			defer GinkgoRecover()
			conn, err := ln.Accept()
			Expect(err).ToNot(HaveOccurred())
			serverConnChan <- conn
		}()
		conn, err := net.Dial("tcp", ln.Addr().String())
		Expect(err).ToNot(HaveOccurred())
		return conn, <-serverConnChan
	}

	BeforeEach(func() {
Marten Seemann's avatar
Marten Seemann committed
83
		fmt.Fprintf(GinkgoWriter, "Initializing a server")
Marten Seemann's avatar
Marten Seemann committed
84
		serverID, serverKey = createPeer()
Marten Seemann's avatar
Marten Seemann committed
85
		fmt.Fprintf(GinkgoWriter, "Initializing a client")
Marten Seemann's avatar
Marten Seemann committed
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
		clientID, clientKey = createPeer()
	})

	It("handshakes", func() {
		clientTransport, err := New(clientKey)
		Expect(err).ToNot(HaveOccurred())
		serverTransport, err := New(serverKey)
		Expect(err).ToNot(HaveOccurred())

		clientInsecureConn, serverInsecureConn := connect()

		serverConnChan := make(chan cs.Conn)
		go func() {
			defer GinkgoRecover()
			serverConn, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
			Expect(err).ToNot(HaveOccurred())
			serverConnChan <- serverConn
		}()
		clientConn, err := clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
		Expect(err).ToNot(HaveOccurred())
		var serverConn cs.Conn
		Eventually(serverConnChan).Should(Receive(&serverConn))
		defer clientConn.Close()
		defer serverConn.Close()
		Expect(clientConn.LocalPeer()).To(Equal(clientID))
		Expect(serverConn.LocalPeer()).To(Equal(serverID))
		Expect(clientConn.LocalPrivateKey()).To(Equal(clientKey))
		Expect(serverConn.LocalPrivateKey()).To(Equal(serverKey))
		Expect(clientConn.RemotePeer()).To(Equal(serverID))
		Expect(serverConn.RemotePeer()).To(Equal(clientID))
		Expect(clientConn.RemotePublicKey()).To(Equal(serverKey.GetPublic()))
		Expect(serverConn.RemotePublicKey()).To(Equal(clientKey.GetPublic()))
		// exchange some data
		_, err = serverConn.Write([]byte("foobar"))
		Expect(err).ToNot(HaveOccurred())
		b := make([]byte, 6)
		_, err = clientConn.Read(b)
		Expect(err).ToNot(HaveOccurred())
		Expect(string(b)).To(Equal("foobar"))
	})

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
	It("fails when the context of the outgoing connection is canceled", func() {
		clientTransport, err := New(clientKey)
		Expect(err).ToNot(HaveOccurred())
		serverTransport, err := New(serverKey)
		Expect(err).ToNot(HaveOccurred())

		clientInsecureConn, serverInsecureConn := connect()

		go func() {
			defer GinkgoRecover()
			_, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
			Expect(err).To(HaveOccurred())
		}()
		ctx, cancel := context.WithCancel(context.Background())
		cancel()
		_, err = clientTransport.SecureOutbound(ctx, clientInsecureConn, serverID)
143
		Expect(err).To(MatchError(context.Canceled))
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
	})

	It("fails when the context of the incoming connection is canceled", func() {
		clientTransport, err := New(clientKey)
		Expect(err).ToNot(HaveOccurred())
		serverTransport, err := New(serverKey)
		Expect(err).ToNot(HaveOccurred())

		clientInsecureConn, serverInsecureConn := connect()

		go func() {
			defer GinkgoRecover()
			ctx, cancel := context.WithCancel(context.Background())
			cancel()
			_, err := serverTransport.SecureInbound(ctx, serverInsecureConn)
159
			Expect(err).To(MatchError(context.Canceled))
160 161 162 163 164
		}()
		_, err = clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
		Expect(err).To(HaveOccurred())
	})

Marten Seemann's avatar
Marten Seemann committed
165
	It("fails if the peer ID doesn't match", func() {
Marten Seemann's avatar
Marten Seemann committed
166
		fmt.Fprintf(GinkgoWriter, "Creating another peer")
Marten Seemann's avatar
Marten Seemann committed
167 168 169 170 171 172 173 174 175
		thirdPartyID, _ := createPeer()

		serverTransport, err := New(serverKey)
		Expect(err).ToNot(HaveOccurred())
		clientTransport, err := New(clientKey)
		Expect(err).ToNot(HaveOccurred())

		clientInsecureConn, serverInsecureConn := connect()

Marten Seemann's avatar
Marten Seemann committed
176
		done := make(chan struct{})
Marten Seemann's avatar
Marten Seemann committed
177 178 179 180 181
		go func() {
			defer GinkgoRecover()
			_, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("tls: bad certificate"))
Marten Seemann's avatar
Marten Seemann committed
182
			close(done)
Marten Seemann's avatar
Marten Seemann committed
183 184 185 186
		}()
		// dial, but expect the wrong peer ID
		_, err = clientTransport.SecureOutbound(context.Background(), clientInsecureConn, thirdPartyID)
		Expect(err).To(MatchError("peer IDs don't match"))
Marten Seemann's avatar
Marten Seemann committed
187
		Eventually(done).Should(BeClosed())
Marten Seemann's avatar
Marten Seemann committed
188 189
	})

190 191
	Context("invalid certificates", func() {
		invalidateCertChain := func(identity *Identity) {
192
			switch identity.config.Certificates[0].PrivateKey.(type) {
193 194 195
			case *rsa.PrivateKey:
				key, err := rsa.GenerateKey(rand.Reader, 1024)
				Expect(err).ToNot(HaveOccurred())
196
				identity.config.Certificates[0].PrivateKey = key
197 198 199
			case *ecdsa.PrivateKey:
				key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
				Expect(err).ToNot(HaveOccurred())
200
				identity.config.Certificates[0].PrivateKey = key
201 202 203 204
			default:
				Fail("unexpected private key type")
			}
		}
Marten Seemann's avatar
Marten Seemann committed
205

206 207 208 209 210 211 212 213 214 215 216 217
		twoCerts := func(identity *Identity) {
			tmpl := &x509.Certificate{SerialNumber: big.NewInt(1)}
			key1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
			Expect(err).ToNot(HaveOccurred())
			key2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
			Expect(err).ToNot(HaveOccurred())
			cert1DER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key1.Public(), key1)
			Expect(err).ToNot(HaveOccurred())
			cert1, err := x509.ParseCertificate(cert1DER)
			Expect(err).ToNot(HaveOccurred())
			cert2DER, err := x509.CreateCertificate(rand.Reader, tmpl, cert1, key2.Public(), key2)
			Expect(err).ToNot(HaveOccurred())
218
			identity.config.Certificates = []tls.Certificate{{
219 220 221 222
				Certificate: [][]byte{cert2DER, cert1DER},
				PrivateKey:  key2,
			}}
		}
Marten Seemann's avatar
Marten Seemann committed
223

Marten Seemann's avatar
Marten Seemann committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
		getCertWithKey := func(key crypto.Signer, tmpl *x509.Certificate) tls.Certificate {
			cert, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
			Expect(err).ToNot(HaveOccurred())
			return tls.Certificate{
				Certificate: [][]byte{cert},
				PrivateKey:  key,
			}
		}

		getCert := func(tmpl *x509.Certificate) tls.Certificate {
			key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
			Expect(err).ToNot(HaveOccurred())
			return getCertWithKey(key, tmpl)
		}

239
		expiredCert := func(identity *Identity) {
Marten Seemann's avatar
Marten Seemann committed
240
			cert := getCert(&x509.Certificate{
241 242 243
				SerialNumber: big.NewInt(1),
				NotBefore:    time.Now().Add(-time.Hour),
				NotAfter:     time.Now().Add(-time.Minute),
Marten Seemann's avatar
Marten Seemann committed
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
			})
			identity.config.Certificates = []tls.Certificate{cert}
		}

		noKeyExtension := func(identity *Identity) {
			cert := getCert(&x509.Certificate{
				SerialNumber: big.NewInt(1),
				NotBefore:    time.Now().Add(-time.Hour),
				NotAfter:     time.Now().Add(time.Hour),
			})
			identity.config.Certificates = []tls.Certificate{cert}
		}

		unparseableKeyExtension := func(identity *Identity) {
			cert := getCert(&x509.Certificate{
				SerialNumber: big.NewInt(1),
				NotBefore:    time.Now().Add(-time.Hour),
				NotAfter:     time.Now().Add(time.Hour),
				ExtraExtensions: []pkix.Extension{
					{Id: extensionID, Value: []byte("foobar")},
				},
			})
			identity.config.Certificates = []tls.Certificate{cert}
		}

		unparseableKey := func(identity *Identity) {
			data, err := asn1.Marshal(signedKey{PubKey: []byte("foobar")})
271
			Expect(err).ToNot(HaveOccurred())
Marten Seemann's avatar
Marten Seemann committed
272 273 274 275 276 277 278 279 280 281 282 283 284
			cert := getCert(&x509.Certificate{
				SerialNumber: big.NewInt(1),
				NotBefore:    time.Now().Add(-time.Hour),
				NotAfter:     time.Now().Add(time.Hour),
				ExtraExtensions: []pkix.Extension{
					{Id: extensionID, Value: data},
				},
			})
			identity.config.Certificates = []tls.Certificate{cert}
		}

		tooShortSignature := func(identity *Identity) {
			key, _, err := ci.GenerateSecp256k1Key(rand.Reader)
285
			Expect(err).ToNot(HaveOccurred())
Marten Seemann's avatar
Marten Seemann committed
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
			keyBytes, err := key.GetPublic().Bytes()
			Expect(err).ToNot(HaveOccurred())
			data, err := asn1.Marshal(signedKey{
				PubKey:    keyBytes,
				Signature: []byte("foobar"),
			})
			Expect(err).ToNot(HaveOccurred())
			cert := getCert(&x509.Certificate{
				SerialNumber: big.NewInt(1),
				NotBefore:    time.Now().Add(-time.Hour),
				NotAfter:     time.Now().Add(time.Hour),
				ExtraExtensions: []pkix.Extension{
					{Id: extensionID, Value: data},
				},
			})
			identity.config.Certificates = []tls.Certificate{cert}
		}

		invalidSignature := func(identity *Identity) {
			key, _, err := ci.GenerateSecp256k1Key(rand.Reader)
			Expect(err).ToNot(HaveOccurred())
			keyBytes, err := key.GetPublic().Bytes()
			Expect(err).ToNot(HaveOccurred())
			signature, err := key.Sign([]byte("foobar"))
			Expect(err).ToNot(HaveOccurred())
			data, err := asn1.Marshal(signedKey{
				PubKey:    keyBytes,
				Signature: signature,
			})
			Expect(err).ToNot(HaveOccurred())
			cert := getCert(&x509.Certificate{
				SerialNumber: big.NewInt(1),
				NotBefore:    time.Now().Add(-time.Hour),
				NotAfter:     time.Now().Add(time.Hour),
				ExtraExtensions: []pkix.Extension{
					{Id: extensionID, Value: data},
				},
			})
			identity.config.Certificates = []tls.Certificate{cert}
325
		}
Marten Seemann's avatar
Marten Seemann committed
326

327 328 329 330
		transforms := []transform{
			{
				name:      "private key used in the TLS handshake doesn't match the public key in the cert",
				apply:     invalidateCertChain,
Marten Seemann's avatar
Marten Seemann committed
331
				remoteErr: Equal("tls: invalid certificate signature"),
332 333 334 335
			},
			{
				name:      "certificate chain contains 2 certs",
				apply:     twoCerts,
Marten Seemann's avatar
Marten Seemann committed
336
				remoteErr: Equal("expected one certificates in the chain"),
337 338 339 340
			},
			{
				name:      "cert is expired",
				apply:     expiredCert,
Marten Seemann's avatar
Marten Seemann committed
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
				remoteErr: Equal("certificate verification failed: x509: certificate has expired or is not yet valid"),
			},
			{
				name:      "cert doesn't have the key extension",
				apply:     noKeyExtension,
				remoteErr: Equal("expected certificate to contain the key extension"),
			},
			{
				name:      "key extension not parseable",
				apply:     unparseableKeyExtension,
				remoteErr: ContainSubstring("asn1"),
			},
			{
				name:      "key protobuf not parseable",
				apply:     unparseableKey,
				remoteErr: ContainSubstring("unmarshalling public key failed: proto:"),
			},
			{
				name:      "signature is malformed",
				apply:     tooShortSignature,
				remoteErr: ContainSubstring("signature verification failed:"),
			},
			{
				name:      "signature is invalid",
				apply:     invalidSignature,
				remoteErr: Equal("signature invalid"),
367 368
			},
		}
Marten Seemann's avatar
Marten Seemann committed
369

370 371
		for i := range transforms {
			t := transforms[i]
Marten Seemann's avatar
Marten Seemann committed
372

373 374 375 376 377 378
			It(fmt.Sprintf("fails if the client presents an invalid cert: %s", t.name), func() {
				serverTransport, err := New(serverKey)
				Expect(err).ToNot(HaveOccurred())
				clientTransport, err := New(clientKey)
				Expect(err).ToNot(HaveOccurred())
				t.apply(clientTransport.identity)
Marten Seemann's avatar
Marten Seemann committed
379

380
				clientInsecureConn, serverInsecureConn := connect()
Marten Seemann's avatar
Marten Seemann committed
381

382 383 384 385
				done := make(chan struct{})
				go func() {
					defer GinkgoRecover()
					_, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
Marten Seemann's avatar
Marten Seemann committed
386 387
					Expect(err).To(HaveOccurred())
					Expect(err.Error()).To(t.remoteErr)
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
					close(done)
				}()

				conn, err := clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
				Expect(err).ToNot(HaveOccurred())
				_, err = gbytes.TimeoutReader(conn, time.Second).Read([]byte{0})
				Expect(err).To(Or(
					// if the certificate's public key doesn't match the private key used for signing
					MatchError("remote error: tls: error decrypting message"),
					// all other errors
					MatchError("remote error: tls: bad certificate"),
				))
				Eventually(done).Should(BeClosed())
			})

			It(fmt.Sprintf("fails if the server presents an invalid cert: %s", t.name), func() {
				serverTransport, err := New(serverKey)
				Expect(err).ToNot(HaveOccurred())
				t.apply(serverTransport.identity)
				clientTransport, err := New(clientKey)
				Expect(err).ToNot(HaveOccurred())

				clientInsecureConn, serverInsecureConn := connect()

				done := make(chan struct{})
				go func() {
					defer GinkgoRecover()
					_, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
					Expect(err).To(HaveOccurred())
					Expect(err.Error()).To(ContainSubstring("remote error: tls:"))
					close(done)
				}()

				_, err = clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
Marten Seemann's avatar
Marten Seemann committed
422 423
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(t.remoteErr)
424 425 426
				Eventually(done).Should(BeClosed())
			})
		}
Marten Seemann's avatar
Marten Seemann committed
427 428
	})
})