github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/example_test.go (about)

     1  // Copyright 2022 s1ren@github.com/hxx258456.
     2  
     3  /*
     4  gmtls是基于`golang/go`的`tls`包实现的国密改造版本。
     5  对应版权声明: thrid_licenses/github.com/golang/go/LICENSE
     6  */
     7  
     8  package gmtls_test
     9  
    10  import (
    11  	"crypto/tls"
    12  	"crypto/x509"
    13  	"log"
    14  	"net/http"
    15  	"net/http/httptest"
    16  	"os"
    17  	"time"
    18  )
    19  
    20  // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
    21  type zeroSource struct{}
    22  
    23  func (zeroSource) Read(b []byte) (n int, err error) {
    24  	for i := range b {
    25  		b[i] = 0
    26  	}
    27  
    28  	return len(b), nil
    29  }
    30  
    31  func ExampleDial() {
    32  	// Connecting with a custom root-certificate set.
    33  
    34  	const rootPEM = `
    35  -- GlobalSign Root R2, valid until Dec 15, 2021
    36  -----BEGIN CERTIFICATE-----
    37  MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G
    38  A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp
    39  Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1
    40  MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG
    41  A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI
    42  hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL
    43  v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8
    44  eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq
    45  tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd
    46  C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa
    47  zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB
    48  mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH
    49  V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n
    50  bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG
    51  3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs
    52  J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO
    53  291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS
    54  ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd
    55  AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7
    56  TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==
    57  -----END CERTIFICATE-----`
    58  
    59  	// First, create the set of root certificates. For this example we only
    60  	// have one. It's also possible to omit this in order to use the
    61  	// default root set of the current operating system.
    62  	roots := x509.NewCertPool()
    63  	ok := roots.AppendCertsFromPEM([]byte(rootPEM))
    64  	if !ok {
    65  		panic("failed to parse root certificate")
    66  	}
    67  
    68  	conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
    69  		RootCAs: roots,
    70  	})
    71  	if err != nil {
    72  		panic("failed to connect: " + err.Error())
    73  	}
    74  	err = conn.Close()
    75  	if err != nil {
    76  		panic(err)
    77  	}
    78  }
    79  
    80  func ExampleConfig_keyLogWriter() {
    81  	// Debugging TLS applications by decrypting a network traffic capture.
    82  
    83  	// WARNING: Use of KeyLogWriter compromises security and should only be
    84  	// used for debugging.
    85  
    86  	// Dummy test HTTP server for the example with insecure random so output is
    87  	// reproducible.
    88  	server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
    89  	server.TLS = &tls.Config{
    90  		Rand: zeroSource{}, // for example only; don't do this.
    91  	}
    92  	server.StartTLS()
    93  	defer server.Close()
    94  
    95  	// Typically the log would go to an open file:
    96  	// w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    97  	w := os.Stdout
    98  
    99  	client := &http.Client{
   100  		Transport: &http.Transport{
   101  			TLSClientConfig: &tls.Config{
   102  				KeyLogWriter: w,
   103  
   104  				Rand:               zeroSource{}, // for reproducible output; don't do this.
   105  				InsecureSkipVerify: true,         // test server certificate is not trusted.
   106  			},
   107  		},
   108  	}
   109  	resp, err := client.Get(server.URL)
   110  	if err != nil {
   111  		log.Fatalf("Failed to get URL: %v", err)
   112  	}
   113  	err = resp.Body.Close()
   114  	if err != nil {
   115  		panic(err)
   116  	}
   117  
   118  	// The resulting file can be used with Wireshark to decrypt the TLS
   119  	// connection by setting (Pre)-Master-Secret log filename in SSL Protocol
   120  	// preferences.
   121  }
   122  
   123  func ExampleLoadX509KeyPair() {
   124  	cert, err := tls.LoadX509KeyPair("testdata/example-cert.pem", "testdata/example-key.pem")
   125  	if err != nil {
   126  		log.Fatal(err)
   127  	}
   128  	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
   129  	listener, err := tls.Listen("tcp", ":2000", cfg)
   130  	if err != nil {
   131  		log.Fatal(err)
   132  	}
   133  	_ = listener
   134  }
   135  
   136  func ExampleX509KeyPair() {
   137  	certPem := []byte(`-----BEGIN CERTIFICATE-----
   138  MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
   139  DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
   140  EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
   141  7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
   142  5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
   143  BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
   144  NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
   145  Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
   146  6MF9+Yw1Yy0t
   147  -----END CERTIFICATE-----`)
   148  	keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
   149  MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
   150  AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
   151  EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
   152  -----END EC PRIVATE KEY-----`)
   153  	cert, err := tls.X509KeyPair(certPem, keyPem)
   154  	if err != nil {
   155  		log.Fatal(err)
   156  	}
   157  	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
   158  	listener, err := tls.Listen("tcp", ":2000", cfg)
   159  	if err != nil {
   160  		log.Fatal(err)
   161  	}
   162  	_ = listener
   163  }
   164  
   165  func ExampleX509KeyPair_httpServer() {
   166  	certPem := []byte(`-----BEGIN CERTIFICATE-----
   167  MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
   168  DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
   169  EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
   170  7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
   171  5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
   172  BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
   173  NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
   174  Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
   175  6MF9+Yw1Yy0t
   176  -----END CERTIFICATE-----`)
   177  	keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
   178  MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
   179  AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
   180  EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
   181  -----END EC PRIVATE KEY-----`)
   182  	cert, err := tls.X509KeyPair(certPem, keyPem)
   183  	if err != nil {
   184  		log.Fatal(err)
   185  	}
   186  	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
   187  	srv := &http.Server{
   188  		TLSConfig:    cfg,
   189  		ReadTimeout:  time.Minute,
   190  		WriteTimeout: time.Minute,
   191  	}
   192  	log.Fatal(srv.ListenAndServeTLS("", ""))
   193  }
   194  
   195  func ExampleConfig_verifyConnection() {
   196  	// VerifyConnection can be used to replace and customize connection
   197  	// verification. This example shows a VerifyConnection implementation that
   198  	// will be approximately equivalent to what crypto/tls does normally to
   199  	// verify the peer's certificate.
   200  
   201  	// Client side configuration.
   202  	_ = &tls.Config{
   203  		// Set InsecureSkipVerify to skip the default validation we are
   204  		// replacing. This will not disable VerifyConnection.
   205  		InsecureSkipVerify: true,
   206  		VerifyConnection: func(cs tls.ConnectionState) error {
   207  			opts := x509.VerifyOptions{
   208  				DNSName:       cs.ServerName,
   209  				Intermediates: x509.NewCertPool(),
   210  			}
   211  			for _, cert := range cs.PeerCertificates[1:] {
   212  				opts.Intermediates.AddCert(cert)
   213  			}
   214  			_, err := cs.PeerCertificates[0].Verify(opts)
   215  			return err
   216  		},
   217  	}
   218  
   219  	// Server side configuration.
   220  	_ = &tls.Config{
   221  		// Require client certificates (or VerifyConnection will run anyway and
   222  		// panic accessing cs.PeerCertificates[0]) but don't verify them with the
   223  		// default verifier. This will not disable VerifyConnection.
   224  		ClientAuth: tls.RequireAnyClientCert,
   225  		VerifyConnection: func(cs tls.ConnectionState) error {
   226  			opts := x509.VerifyOptions{
   227  				DNSName:       cs.ServerName,
   228  				Intermediates: x509.NewCertPool(),
   229  				KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
   230  			}
   231  			for _, cert := range cs.PeerCertificates[1:] {
   232  				opts.Intermediates.AddCert(cert)
   233  			}
   234  			_, err := cs.PeerCertificates[0].Verify(opts)
   235  			return err
   236  		},
   237  	}
   238  
   239  	// Note that when certificates are not handled by the default verifier
   240  	// ConnectionState.VerifiedChains will be nil.
   241  }