github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/conn_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
     9  
    10  import (
    11  	"bytes"
    12  	"io"
    13  	"net"
    14  	"testing"
    15  )
    16  
    17  func TestRoundUp(t *testing.T) {
    18  	if roundUp(0, 16) != 0 ||
    19  		roundUp(1, 16) != 16 ||
    20  		roundUp(15, 16) != 16 ||
    21  		roundUp(16, 16) != 16 ||
    22  		roundUp(17, 16) != 32 {
    23  		t.Error("roundUp broken")
    24  	}
    25  }
    26  
    27  // will be initialized with {0, 255, 255, ..., 255}
    28  var padding255Bad = [256]byte{}
    29  
    30  // will be initialized with {255, 255, 255, ..., 255}
    31  var padding255Good = [256]byte{255}
    32  
    33  var paddingTests = []struct {
    34  	in          []byte
    35  	good        bool
    36  	expectedLen int
    37  }{
    38  	{[]byte{1, 2, 3, 4, 0}, true, 4},
    39  	{[]byte{1, 2, 3, 4, 0, 1}, false, 0},
    40  	{[]byte{1, 2, 3, 4, 99, 99}, false, 0},
    41  	{[]byte{1, 2, 3, 4, 1, 1}, true, 4},
    42  	{[]byte{1, 2, 3, 2, 2, 2}, true, 3},
    43  	{[]byte{1, 2, 3, 3, 3, 3}, true, 2},
    44  	{[]byte{1, 2, 3, 4, 3, 3}, false, 0},
    45  	{[]byte{1, 4, 4, 4, 4, 4}, true, 1},
    46  	{[]byte{5, 5, 5, 5, 5, 5}, true, 0},
    47  	{[]byte{6, 6, 6, 6, 6, 6}, false, 0},
    48  	{padding255Bad[:], false, 0},
    49  	{padding255Good[:], true, 0},
    50  }
    51  
    52  func TestRemovePadding(t *testing.T) {
    53  	for i := 1; i < len(padding255Bad); i++ {
    54  		padding255Bad[i] = 255
    55  		padding255Good[i] = 255
    56  	}
    57  	for i, test := range paddingTests {
    58  		paddingLen, good := extractPadding(test.in)
    59  		expectedGood := byte(255)
    60  		if !test.good {
    61  			expectedGood = 0
    62  		}
    63  		if good != expectedGood {
    64  			t.Errorf("#%d: wrong validity, want:%d got:%d", i, expectedGood, good)
    65  		}
    66  		if good == 255 && len(test.in)-paddingLen != test.expectedLen {
    67  			t.Errorf("#%d: got %d, want %d", i, len(test.in)-paddingLen, test.expectedLen)
    68  		}
    69  	}
    70  }
    71  
    72  var certExampleCom = `308201713082011ba003020102021005a75ddf21014d5f417083b7a010ba2e300d06092a864886f70d01010b050030123110300e060355040a130741636d6520436f301e170d3136303831373231343135335a170d3137303831373231343135335a30123110300e060355040a130741636d6520436f305c300d06092a864886f70d0101010500034b003048024100b37f0fdd67e715bf532046ac34acbd8fdc4dabe2b598588f3f58b1f12e6219a16cbfe54d2b4b665396013589262360b6721efa27d546854f17cc9aeec6751db10203010001a34d304b300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff0402300030160603551d11040f300d820b6578616d706c652e636f6d300d06092a864886f70d01010b050003410059fc487866d3d855503c8e064ca32aac5e9babcece89ec597f8b2b24c17867f4a5d3b4ece06e795bfc5448ccbd2ffca1b3433171ebf3557a4737b020565350a0`
    73  
    74  var certWildcardExampleCom = `308201743082011ea003020102021100a7aa6297c9416a4633af8bec2958c607300d06092a864886f70d01010b050030123110300e060355040a130741636d6520436f301e170d3136303831373231343231395a170d3137303831373231343231395a30123110300e060355040a130741636d6520436f305c300d06092a864886f70d0101010500034b003048024100b105afc859a711ee864114e7d2d46c2dcbe392d3506249f6c2285b0eb342cc4bf2d803677c61c0abde443f084745c1a6d62080e5664ef2cc8f50ad8a0ab8870b0203010001a34f304d300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff0402300030180603551d110411300f820d2a2e6578616d706c652e636f6d300d06092a864886f70d01010b0500034100af26088584d266e3f6566360cf862c7fecc441484b098b107439543144a2b93f20781988281e108c6d7656934e56950e1e5f2bcf38796b814ccb729445856c34`
    75  
    76  var certFooExampleCom = `308201753082011fa00302010202101bbdb6070b0aeffc49008cde74deef29300d06092a864886f70d01010b050030123110300e060355040a130741636d6520436f301e170d3136303831373231343234345a170d3137303831373231343234345a30123110300e060355040a130741636d6520436f305c300d06092a864886f70d0101010500034b003048024100f00ac69d8ca2829f26216c7b50f1d4bbabad58d447706476cd89a2f3e1859943748aa42c15eedc93ac7c49e40d3b05ed645cb6b81c4efba60d961f44211a54eb0203010001a351304f300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff04023000301a0603551d1104133011820f666f6f2e6578616d706c652e636f6d300d06092a864886f70d01010b0500034100a0957fca6d1e0f1ef4b247348c7a8ca092c29c9c0ecc1898ea6b8065d23af6d922a410dd2335a0ea15edd1394cef9f62c9e876a21e35250a0b4fe1ddceba0f36`
    77  
    78  func TestCertificateSelection(t *testing.T) {
    79  	config := Config{
    80  		Certificates: []Certificate{
    81  			{
    82  				Certificate: [][]byte{fromHex(certExampleCom)},
    83  			},
    84  			{
    85  				Certificate: [][]byte{fromHex(certWildcardExampleCom)},
    86  			},
    87  			{
    88  				Certificate: [][]byte{fromHex(certFooExampleCom)},
    89  			},
    90  		},
    91  	}
    92  
    93  	config.BuildNameToCertificate()
    94  
    95  	pointerToIndex := func(c *Certificate) int {
    96  		for i := range config.Certificates {
    97  			if c == &config.Certificates[i] {
    98  				return i
    99  			}
   100  		}
   101  		return -1
   102  	}
   103  
   104  	certificateForName := func(name string) *Certificate {
   105  		clientHello := &ClientHelloInfo{
   106  			ServerName: name,
   107  		}
   108  		if cert, err := config.getCertificate(clientHello); err != nil {
   109  			t.Errorf("unable to get certificate for name '%s': %s", name, err)
   110  			return nil
   111  		} else {
   112  			return cert
   113  		}
   114  	}
   115  
   116  	if n := pointerToIndex(certificateForName("example.com")); n != 0 {
   117  		t.Errorf("example.com returned certificate %d, not 0", n)
   118  	}
   119  	if n := pointerToIndex(certificateForName("bar.example.com")); n != 1 {
   120  		t.Errorf("bar.example.com returned certificate %d, not 1", n)
   121  	}
   122  	if n := pointerToIndex(certificateForName("foo.example.com")); n != 2 {
   123  		t.Errorf("foo.example.com returned certificate %d, not 2", n)
   124  	}
   125  	if n := pointerToIndex(certificateForName("foo.bar.example.com")); n != 0 {
   126  		t.Errorf("foo.bar.example.com returned certificate %d, not 0", n)
   127  	}
   128  }
   129  
   130  // Run with multiple crypto configs to test the logic for computing TLS record overheads.
   131  func runDynamicRecordSizingTest(t *testing.T, config *Config) {
   132  	clientConn, serverConn := localPipe(t)
   133  
   134  	serverConfig := config.Clone()
   135  	serverConfig.DynamicRecordSizingDisabled = false
   136  	tlsConn := Server(serverConn, serverConfig)
   137  
   138  	handshakeDone := make(chan struct{})
   139  	recordSizesChan := make(chan []int, 1)
   140  	defer func() { <-recordSizesChan }() // wait for the goroutine to exit
   141  	go func() {
   142  		// This goroutine performs a TLS handshake over clientConn and
   143  		// then reads TLS records until EOF. It writes a slice that
   144  		// contains all the record sizes to recordSizesChan.
   145  		defer close(recordSizesChan)
   146  		defer clientConn.Close()
   147  
   148  		tlsConn := Client(clientConn, config)
   149  		if err := tlsConn.Handshake(); err != nil {
   150  			t.Errorf("Error from client handshake: %v", err)
   151  			return
   152  		}
   153  		defer func(clientConn net.Conn) {
   154  			err := clientConn.Close()
   155  			if err != nil {
   156  				panic(err)
   157  			}
   158  		}(clientConn)
   159  
   160  		var recordHeader [recordHeaderLen]byte
   161  		var record []byte
   162  		var recordSizes []int
   163  
   164  		for {
   165  			n, err := io.ReadFull(clientConn, recordHeader[:])
   166  			if err == io.EOF {
   167  				break
   168  			}
   169  			if err != nil || n != len(recordHeader) {
   170  				t.Errorf("io.ReadFull = %d, %v", n, err)
   171  				return
   172  			}
   173  
   174  			length := int(recordHeader[3])<<8 | int(recordHeader[4])
   175  			if len(record) < length {
   176  				record = make([]byte, length)
   177  			}
   178  
   179  			n, err = io.ReadFull(clientConn, record[:length])
   180  			if err != nil || n != length {
   181  				t.Errorf("io.ReadFull = %d, %v", n, err)
   182  				return
   183  			}
   184  
   185  			recordSizes = append(recordSizes, recordHeaderLen+length)
   186  		}
   187  
   188  		recordSizesChan <- recordSizes
   189  	}()
   190  
   191  	if err := tlsConn.Handshake(); err != nil {
   192  		t.Fatalf("Error from server handshake: %s", err)
   193  	}
   194  	<-handshakeDone
   195  
   196  	// The server writes these plaintexts in order.
   197  	plaintext := bytes.Join([][]byte{
   198  		bytes.Repeat([]byte("x"), recordSizeBoostThreshold),
   199  		bytes.Repeat([]byte("y"), maxPlaintext*2),
   200  		bytes.Repeat([]byte("z"), maxPlaintext),
   201  	}, nil)
   202  
   203  	if _, err := tlsConn.Write(plaintext); err != nil {
   204  		t.Fatalf("Error from server write: %s", err)
   205  	}
   206  	if err := tlsConn.Close(); err != nil {
   207  		t.Fatalf("Error from server close: %s", err)
   208  	}
   209  
   210  	recordSizes := <-recordSizesChan
   211  	if recordSizes == nil {
   212  		t.Fatalf("Client encountered an error")
   213  	}
   214  
   215  	// Drop the size of the second to last record, which is likely to be
   216  	// truncated, and the last record, which is a close_notify alert.
   217  	recordSizes = recordSizes[:len(recordSizes)-2]
   218  
   219  	// recordSizes should contain a series of records smaller than
   220  	// tcpMSSEstimate followed by some larger than maxPlaintext.
   221  	seenLargeRecord := false
   222  	for i, size := range recordSizes {
   223  		if !seenLargeRecord {
   224  			if size > (i+1)*tcpMSSEstimate {
   225  				t.Fatalf("Record #%d has size %d, which is too large too soon", i, size)
   226  			}
   227  			if size >= maxPlaintext {
   228  				seenLargeRecord = true
   229  			}
   230  		} else if size <= maxPlaintext {
   231  			t.Fatalf("Record #%d has size %d but should be full sized", i, size)
   232  		}
   233  	}
   234  
   235  	if !seenLargeRecord {
   236  		t.Fatalf("No large records observed")
   237  	}
   238  }
   239  
   240  func TestDynamicRecordSizingWithStreamCipher(t *testing.T) {
   241  	config := testConfig.Clone()
   242  	config.MaxVersion = VersionTLS12
   243  	config.CipherSuites = []uint16{TLS_RSA_WITH_RC4_128_SHA}
   244  	runDynamicRecordSizingTest(t, config)
   245  }
   246  
   247  func TestDynamicRecordSizingWithCBC(t *testing.T) {
   248  	config := testConfig.Clone()
   249  	config.MaxVersion = VersionTLS12
   250  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_256_CBC_SHA}
   251  	runDynamicRecordSizingTest(t, config)
   252  }
   253  
   254  func TestDynamicRecordSizingWithAEAD(t *testing.T) {
   255  	config := testConfig.Clone()
   256  	config.MaxVersion = VersionTLS12
   257  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
   258  	runDynamicRecordSizingTest(t, config)
   259  }
   260  
   261  func TestDynamicRecordSizingWithTLSv13(t *testing.T) {
   262  	config := testConfig.Clone()
   263  	runDynamicRecordSizingTest(t, config)
   264  }
   265  
   266  // hairpinConn is a net.Conn that makes a “hairpin” call when closed, back into
   267  // the tls.Conn which is calling it.
   268  type hairpinConn struct {
   269  	net.Conn
   270  	tlsConn *Conn
   271  }
   272  
   273  func (conn *hairpinConn) Close() error {
   274  	conn.tlsConn.ConnectionState()
   275  	return nil
   276  }
   277  
   278  func TestHairpinInClose(t *testing.T) {
   279  	// This tests that the underlying net.Conn can call back into the
   280  	// tls.Conn when being closed without deadlocking.
   281  	client, server := localPipe(t)
   282  	defer func(server net.Conn) {
   283  		err := server.Close()
   284  		if err != nil {
   285  			panic(err)
   286  		}
   287  	}(server)
   288  	defer func(client net.Conn) {
   289  		err := client.Close()
   290  		if err != nil {
   291  			panic(err)
   292  		}
   293  	}(client)
   294  
   295  	conn := &hairpinConn{client, nil}
   296  	tlsConn := Server(conn, &Config{
   297  		GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
   298  			panic("unreachable")
   299  		},
   300  	})
   301  	conn.tlsConn = tlsConn
   302  
   303  	// This call should not deadlock.
   304  	err := tlsConn.Close()
   305  	if err != nil {
   306  		t.Fatal(err)
   307  	}
   308  }