github.com/m10x/go/src@v0.0.0-20220112094212-ba61592315da/crypto/x509/hybrid_pool_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package x509_test 6 7 import ( 8 "crypto/ecdsa" 9 "crypto/elliptic" 10 "crypto/rand" 11 "crypto/tls" 12 "crypto/x509" 13 "crypto/x509/pkix" 14 "internal/testenv" 15 "math/big" 16 "runtime" 17 "testing" 18 "time" 19 ) 20 21 func TestHybridPool(t *testing.T) { 22 if !(runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios") { 23 t.Skipf("platform verifier not available on %s", runtime.GOOS) 24 } 25 if !testenv.HasExternalNetwork() { 26 t.Skip() 27 } 28 29 // Get the google.com chain, which should be valid on all platforms we 30 // are testing 31 c, err := tls.Dial("tcp", "google.com:443", &tls.Config{InsecureSkipVerify: true}) 32 if err != nil { 33 t.Fatalf("tls connection failed: %s", err) 34 } 35 googChain := c.ConnectionState().PeerCertificates 36 37 rootTmpl := &x509.Certificate{ 38 SerialNumber: big.NewInt(1), 39 Subject: pkix.Name{CommonName: "Go test root"}, 40 IsCA: true, 41 BasicConstraintsValid: true, 42 NotBefore: time.Now().Add(-time.Hour), 43 NotAfter: time.Now().Add(time.Hour * 10), 44 } 45 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 46 if err != nil { 47 t.Fatalf("failed to generate test key: %s", err) 48 } 49 rootDER, err := x509.CreateCertificate(rand.Reader, rootTmpl, rootTmpl, k.Public(), k) 50 if err != nil { 51 t.Fatalf("failed to create test cert: %s", err) 52 } 53 root, err := x509.ParseCertificate(rootDER) 54 if err != nil { 55 t.Fatalf("failed to parse test cert: %s", err) 56 } 57 58 pool, err := x509.SystemCertPool() 59 if err != nil { 60 t.Fatalf("SystemCertPool failed: %s", err) 61 } 62 opts := x509.VerifyOptions{Roots: pool} 63 64 _, err = googChain[0].Verify(opts) 65 if err != nil { 66 t.Fatalf("verification failed for google.com chain (empty pool): %s", err) 67 } 68 69 pool.AddCert(root) 70 71 _, err = googChain[0].Verify(opts) 72 if err != nil { 73 t.Fatalf("verification failed for google.com chain (hybrid pool): %s", err) 74 } 75 76 certTmpl := &x509.Certificate{ 77 SerialNumber: big.NewInt(1), 78 NotBefore: time.Now().Add(-time.Hour), 79 NotAfter: time.Now().Add(time.Hour * 10), 80 DNSNames: []string{"example.com"}, 81 } 82 certDER, err := x509.CreateCertificate(rand.Reader, certTmpl, rootTmpl, k.Public(), k) 83 if err != nil { 84 t.Fatalf("failed to create test cert: %s", err) 85 } 86 cert, err := x509.ParseCertificate(certDER) 87 if err != nil { 88 t.Fatalf("failed to parse test cert: %s", err) 89 } 90 91 _, err = cert.Verify(opts) 92 if err != nil { 93 t.Fatalf("verification failed for custom chain (hybrid pool): %s", err) 94 } 95 }