gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmtls/example_test.go (about)

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