1 // Copyright 2009 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.
22 type clientHandshakeState struct {
24 serverHello *serverHelloMsg
27 finishedHash finishedHash
29 session *ClientSessionState
32 func makeClientHello(config *Config) (*clientHelloMsg, error) {
33 if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
34 return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
38 for _, proto := range config.NextProtos {
39 if l := len(proto); l == 0 || l > 255 {
40 return nil, errors.New("tls: invalid NextProtos value")
42 nextProtosLength += 1 + l
46 if nextProtosLength > 0xffff {
47 return nil, errors.New("tls: NextProtos values too large")
50 hello := &clientHelloMsg{
51 vers: config.maxVersion(),
52 compressionMethods: []uint8{compressionNone},
53 random: make([]byte, 32),
56 serverName: hostnameInSNI(config.ServerName),
57 supportedCurves: config.curvePreferences(),
58 supportedPoints: []uint8{pointFormatUncompressed},
59 nextProtoNeg: len(config.NextProtos) > 0,
60 secureRenegotiationSupported: true,
61 alpnProtocols: config.NextProtos,
63 possibleCipherSuites := config.cipherSuites()
64 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
67 for _, suiteId := range possibleCipherSuites {
68 for _, suite := range cipherSuites {
69 if suite.id != suiteId {
72 // Don't advertise TLS 1.2-only cipher suites unless
73 // we're attempting TLS 1.2.
74 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
77 hello.cipherSuites = append(hello.cipherSuites, suiteId)
78 continue NextCipherSuite
82 _, err := io.ReadFull(config.rand(), hello.random)
84 return nil, errors.New("tls: short read from Rand: " + err.Error())
87 if hello.vers >= VersionTLS12 {
88 hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
90 if testingOnlyForceClientHelloSignatureAlgorithms != nil {
91 hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms
97 func (c *Conn) clientHandshake() error {
99 c.config = defaultConfig()
102 // This may be a renegotiation handshake, in which case some fields
106 hello, err := makeClientHello(c.config)
111 if c.handshakes > 0 {
112 hello.secureRenegotiation = c.clientFinished[:]
115 var session *ClientSessionState
117 sessionCache := c.config.ClientSessionCache
118 if c.config.SessionTicketsDisabled {
122 if sessionCache != nil {
123 hello.ticketSupported = true
126 // Session resumption is not allowed if renegotiating because
127 // renegotiation is primarily used to allow a client to send a client
128 // certificate, which would be skipped if session resumption occurred.
129 if sessionCache != nil && c.handshakes == 0 {
130 // Try to resume a previously negotiated TLS session, if
132 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
133 candidateSession, ok := sessionCache.Get(cacheKey)
135 // Check that the ciphersuite/version used for the
136 // previous session are still valid.
137 cipherSuiteOk := false
138 for _, id := range hello.cipherSuites {
139 if id == candidateSession.cipherSuite {
145 versOk := candidateSession.vers >= c.config.minVersion() &&
146 candidateSession.vers <= c.config.maxVersion()
147 if versOk && cipherSuiteOk {
148 session = candidateSession
154 hello.sessionTicket = session.sessionTicket
155 // A random session ID is used to detect when the
156 // server accepted the ticket and is resuming a session
158 hello.sessionId = make([]byte, 16)
159 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
160 return errors.New("tls: short read from Rand: " + err.Error())
164 hs := &clientHandshakeState{
170 if err = hs.handshake(); err != nil {
174 // If we had a successful handshake and hs.session is different from
175 // the one already cached - cache a new one
176 if sessionCache != nil && hs.session != nil && session != hs.session {
177 sessionCache.Put(cacheKey, hs.session)
183 // Does the handshake, either a full one or resumes old session.
184 // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
185 func (hs *clientHandshakeState) handshake() error {
189 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
193 msg, err := c.readHandshake()
199 if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
200 c.sendAlert(alertUnexpectedMessage)
201 return unexpectedMessageError(hs.serverHello, msg)
204 if err = hs.pickTLSVersion(); err != nil {
208 if err = hs.pickCipherSuite(); err != nil {
212 isResume, err := hs.processServerHello()
217 hs.finishedHash = newFinishedHash(c.vers, hs.suite)
219 // No signatures of the handshake are needed in a resumption.
220 // Otherwise, in a full handshake, if we don't have any certificates
221 // configured then we will never send a CertificateVerify message and
222 // thus no signatures are needed in that case either.
223 if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
224 hs.finishedHash.discardHandshakeBuffer()
227 hs.finishedHash.Write(hs.hello.marshal())
228 hs.finishedHash.Write(hs.serverHello.marshal())
232 if err := hs.establishKeys(); err != nil {
235 if err := hs.readSessionTicket(); err != nil {
238 if err := hs.readFinished(c.serverFinished[:]); err != nil {
241 c.clientFinishedIsFirst = false
242 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
245 if _, err := c.flush(); err != nil {
249 if err := hs.doFullHandshake(); err != nil {
252 if err := hs.establishKeys(); err != nil {
255 if err := hs.sendFinished(c.clientFinished[:]); err != nil {
258 if _, err := c.flush(); err != nil {
261 c.clientFinishedIsFirst = true
262 if err := hs.readSessionTicket(); err != nil {
265 if err := hs.readFinished(c.serverFinished[:]); err != nil {
270 c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
271 c.didResume = isResume
272 c.handshakeComplete = true
277 func (hs *clientHandshakeState) pickTLSVersion() error {
278 vers, ok := hs.c.config.mutualVersion(hs.serverHello.vers)
279 if !ok || vers < VersionTLS10 {
280 // TLS 1.0 is the minimum version supported as a client.
281 hs.c.sendAlert(alertProtocolVersion)
282 return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
291 func (hs *clientHandshakeState) pickCipherSuite() error {
292 if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
293 hs.c.sendAlert(alertHandshakeFailure)
294 return errors.New("tls: server chose an unconfigured cipher suite")
297 hs.c.cipherSuite = hs.suite.id
301 func (hs *clientHandshakeState) doFullHandshake() error {
304 msg, err := c.readHandshake()
308 certMsg, ok := msg.(*certificateMsg)
309 if !ok || len(certMsg.certificates) == 0 {
310 c.sendAlert(alertUnexpectedMessage)
311 return unexpectedMessageError(certMsg, msg)
313 hs.finishedHash.Write(certMsg.marshal())
315 if c.handshakes == 0 {
316 // If this is the first handshake on a connection, process and
317 // (optionally) verify the server's certificates.
318 certs := make([]*x509.Certificate, len(certMsg.certificates))
319 for i, asn1Data := range certMsg.certificates {
320 cert, err := x509.ParseCertificate(asn1Data)
322 c.sendAlert(alertBadCertificate)
323 return errors.New("tls: failed to parse certificate from server: " + err.Error())
328 if !c.config.InsecureSkipVerify {
329 opts := x509.VerifyOptions{
330 IsBoring: isBoringCertificate,
332 Roots: c.config.RootCAs,
333 CurrentTime: c.config.time(),
334 DNSName: c.config.ServerName,
335 Intermediates: x509.NewCertPool(),
338 for i, cert := range certs {
342 opts.Intermediates.AddCert(cert)
344 c.verifiedChains, err = certs[0].Verify(opts)
346 c.sendAlert(alertBadCertificate)
351 if c.config.VerifyPeerCertificate != nil {
352 if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
353 c.sendAlert(alertBadCertificate)
358 switch certs[0].PublicKey.(type) {
359 case *rsa.PublicKey, *ecdsa.PublicKey:
362 c.sendAlert(alertUnsupportedCertificate)
363 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
366 c.peerCertificates = certs
368 // This is a renegotiation handshake. We require that the
369 // server's identity (i.e. leaf certificate) is unchanged and
370 // thus any previous trust decision is still valid.
372 // See https://mitls.org/pages/attacks/3SHAKE for the
373 // motivation behind this requirement.
374 if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
375 c.sendAlert(alertBadCertificate)
376 return errors.New("tls: server's identity changed during renegotiation")
380 msg, err = c.readHandshake()
385 cs, ok := msg.(*certificateStatusMsg)
387 // RFC4366 on Certificate Status Request:
388 // The server MAY return a "certificate_status" message.
390 if !hs.serverHello.ocspStapling {
391 // If a server returns a "CertificateStatus" message, then the
392 // server MUST have included an extension of type "status_request"
393 // with empty "extension_data" in the extended server hello.
395 c.sendAlert(alertUnexpectedMessage)
396 return errors.New("tls: received unexpected CertificateStatus message")
398 hs.finishedHash.Write(cs.marshal())
400 if cs.statusType == statusTypeOCSP {
401 c.ocspResponse = cs.response
404 msg, err = c.readHandshake()
410 keyAgreement := hs.suite.ka(c.vers)
412 skx, ok := msg.(*serverKeyExchangeMsg)
414 hs.finishedHash.Write(skx.marshal())
415 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
417 c.sendAlert(alertUnexpectedMessage)
421 msg, err = c.readHandshake()
427 var chainToSend *Certificate
428 var certRequested bool
429 certReq, ok := msg.(*certificateRequestMsg)
432 hs.finishedHash.Write(certReq.marshal())
434 if chainToSend, err = hs.getCertificate(certReq); err != nil {
435 c.sendAlert(alertInternalError)
439 msg, err = c.readHandshake()
445 shd, ok := msg.(*serverHelloDoneMsg)
447 c.sendAlert(alertUnexpectedMessage)
448 return unexpectedMessageError(shd, msg)
450 hs.finishedHash.Write(shd.marshal())
452 // If the server requested a certificate then we have to send a
453 // Certificate message, even if it's empty because we don't have a
454 // certificate to send.
456 certMsg = new(certificateMsg)
457 certMsg.certificates = chainToSend.Certificate
458 hs.finishedHash.Write(certMsg.marshal())
459 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
464 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
466 c.sendAlert(alertInternalError)
470 hs.finishedHash.Write(ckx.marshal())
471 if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
476 if chainToSend != nil && len(chainToSend.Certificate) > 0 {
477 certVerify := &certificateVerifyMsg{
478 hasSignatureAndHash: c.vers >= VersionTLS12,
481 key, ok := chainToSend.PrivateKey.(crypto.Signer)
483 c.sendAlert(alertInternalError)
484 return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
487 signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
489 c.sendAlert(alertInternalError)
492 // SignatureAndHashAlgorithm was introduced in TLS 1.2.
493 if certVerify.hasSignatureAndHash {
494 certVerify.signatureAlgorithm = signatureAlgorithm
496 digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
498 c.sendAlert(alertInternalError)
501 signOpts := crypto.SignerOpts(hashFunc)
502 if sigType == signatureRSAPSS {
503 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
505 certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
507 c.sendAlert(alertInternalError)
511 hs.finishedHash.Write(certVerify.marshal())
512 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
517 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
518 if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
519 c.sendAlert(alertInternalError)
520 return errors.New("tls: failed to write to key log: " + err.Error())
523 hs.finishedHash.discardHandshakeBuffer()
528 func (hs *clientHandshakeState) establishKeys() error {
531 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
532 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
533 var clientCipher, serverCipher interface{}
534 var clientHash, serverHash macFunction
535 if hs.suite.cipher != nil {
536 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
537 clientHash = hs.suite.mac(c.vers, clientMAC)
538 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
539 serverHash = hs.suite.mac(c.vers, serverMAC)
541 clientCipher = hs.suite.aead(clientKey, clientIV)
542 serverCipher = hs.suite.aead(serverKey, serverIV)
545 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
546 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
550 func (hs *clientHandshakeState) serverResumedSession() bool {
551 // If the server responded with the same sessionId then it means the
552 // sessionTicket is being used to resume a TLS session.
553 return hs.session != nil && hs.hello.sessionId != nil &&
554 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
557 func (hs *clientHandshakeState) processServerHello() (bool, error) {
560 if hs.serverHello.compressionMethod != compressionNone {
561 c.sendAlert(alertUnexpectedMessage)
562 return false, errors.New("tls: server selected unsupported compression format")
565 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
566 c.secureRenegotiation = true
567 if len(hs.serverHello.secureRenegotiation) != 0 {
568 c.sendAlert(alertHandshakeFailure)
569 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
573 if c.handshakes > 0 && c.secureRenegotiation {
574 var expectedSecureRenegotiation [24]byte
575 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
576 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
577 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
578 c.sendAlert(alertHandshakeFailure)
579 return false, errors.New("tls: incorrect renegotiation extension contents")
583 clientDidNPN := hs.hello.nextProtoNeg
584 clientDidALPN := len(hs.hello.alpnProtocols) > 0
585 serverHasNPN := hs.serverHello.nextProtoNeg
586 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
588 if !clientDidNPN && serverHasNPN {
589 c.sendAlert(alertHandshakeFailure)
590 return false, errors.New("tls: server advertised unrequested NPN extension")
593 if !clientDidALPN && serverHasALPN {
594 c.sendAlert(alertHandshakeFailure)
595 return false, errors.New("tls: server advertised unrequested ALPN extension")
598 if serverHasNPN && serverHasALPN {
599 c.sendAlert(alertHandshakeFailure)
600 return false, errors.New("tls: server advertised both NPN and ALPN extensions")
604 c.clientProtocol = hs.serverHello.alpnProtocol
605 c.clientProtocolFallback = false
607 c.scts = hs.serverHello.scts
609 if !hs.serverResumedSession() {
613 if hs.session.vers != c.vers {
614 c.sendAlert(alertHandshakeFailure)
615 return false, errors.New("tls: server resumed a session with a different version")
618 if hs.session.cipherSuite != hs.suite.id {
619 c.sendAlert(alertHandshakeFailure)
620 return false, errors.New("tls: server resumed a session with a different cipher suite")
623 // Restore masterSecret and peerCerts from previous state
624 hs.masterSecret = hs.session.masterSecret
625 c.peerCertificates = hs.session.serverCertificates
626 c.verifiedChains = hs.session.verifiedChains
630 func (hs *clientHandshakeState) readFinished(out []byte) error {
633 c.readRecord(recordTypeChangeCipherSpec)
638 msg, err := c.readHandshake()
642 serverFinished, ok := msg.(*finishedMsg)
644 c.sendAlert(alertUnexpectedMessage)
645 return unexpectedMessageError(serverFinished, msg)
648 verify := hs.finishedHash.serverSum(hs.masterSecret)
649 if len(verify) != len(serverFinished.verifyData) ||
650 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
651 c.sendAlert(alertHandshakeFailure)
652 return errors.New("tls: server's Finished message was incorrect")
654 hs.finishedHash.Write(serverFinished.marshal())
659 func (hs *clientHandshakeState) readSessionTicket() error {
660 if !hs.serverHello.ticketSupported {
665 msg, err := c.readHandshake()
669 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
671 c.sendAlert(alertUnexpectedMessage)
672 return unexpectedMessageError(sessionTicketMsg, msg)
674 hs.finishedHash.Write(sessionTicketMsg.marshal())
676 hs.session = &ClientSessionState{
677 sessionTicket: sessionTicketMsg.ticket,
679 cipherSuite: hs.suite.id,
680 masterSecret: hs.masterSecret,
681 serverCertificates: c.peerCertificates,
682 verifiedChains: c.verifiedChains,
688 func (hs *clientHandshakeState) sendFinished(out []byte) error {
691 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
694 if hs.serverHello.nextProtoNeg {
695 nextProto := new(nextProtoMsg)
696 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
697 nextProto.proto = proto
698 c.clientProtocol = proto
699 c.clientProtocolFallback = fallback
701 hs.finishedHash.Write(nextProto.marshal())
702 if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
707 finished := new(finishedMsg)
708 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
709 hs.finishedHash.Write(finished.marshal())
710 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
713 copy(out, finished.verifyData)
717 // tls11SignatureSchemes contains the signature schemes that we synthesise for
718 // a TLS <= 1.1 connection, based on the supported certificate types.
719 var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
722 // tls11SignatureSchemesNumECDSA is the number of initial elements of
723 // tls11SignatureSchemes that use ECDSA.
724 tls11SignatureSchemesNumECDSA = 3
725 // tls11SignatureSchemesNumRSA is the number of trailing elements of
726 // tls11SignatureSchemes that use RSA.
727 tls11SignatureSchemesNumRSA = 4
730 func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
733 var rsaAvail, ecdsaAvail bool
734 for _, certType := range certReq.certificateTypes {
736 case certTypeRSASign:
738 case certTypeECDSASign:
743 if c.config.GetClientCertificate != nil {
744 var signatureSchemes []SignatureScheme
746 if !certReq.hasSignatureAndHash {
747 // Prior to TLS 1.2, the signature schemes were not
748 // included in the certificate request message. In this
749 // case we use a plausible list based on the acceptable
750 // certificate types.
751 signatureSchemes = tls11SignatureSchemes
753 signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
756 signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
759 signatureSchemes = certReq.supportedSignatureAlgorithms
762 return c.config.GetClientCertificate(&CertificateRequestInfo{
763 AcceptableCAs: certReq.certificateAuthorities,
764 SignatureSchemes: signatureSchemes,
768 // RFC 4346 on the certificateAuthorities field: A list of the
769 // distinguished names of acceptable certificate authorities.
770 // These distinguished names may specify a desired
771 // distinguished name for a root CA or for a subordinate CA;
772 // thus, this message can be used to describe both known roots
773 // and a desired authorization space. If the
774 // certificate_authorities list is empty then the client MAY
775 // send any certificate of the appropriate
776 // ClientCertificateType, unless there is some external
777 // arrangement to the contrary.
779 // We need to search our list of client certs for one
780 // where SignatureAlgorithm is acceptable to the server and the
781 // Issuer is in certReq.certificateAuthorities
783 for i, chain := range c.config.Certificates {
784 if !rsaAvail && !ecdsaAvail {
788 for j, cert := range chain.Certificate {
789 x509Cert := chain.Leaf
790 // parse the certificate if this isn't the leaf
791 // node, or if chain.Leaf was nil
792 if j != 0 || x509Cert == nil {
794 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
795 c.sendAlert(alertInternalError)
796 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
801 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
802 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
807 if len(certReq.certificateAuthorities) == 0 {
808 // they gave us an empty list, so just take the
809 // first cert from c.config.Certificates
813 for _, ca := range certReq.certificateAuthorities {
814 if bytes.Equal(x509Cert.RawIssuer, ca) {
821 // No acceptable certificate found. Don't send a certificate.
822 return new(Certificate), nil
825 // clientSessionCacheKey returns a key used to cache sessionTickets that could
826 // be used to resume previously negotiated TLS sessions with a server.
827 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
828 if len(config.ServerName) > 0 {
829 return config.ServerName
831 return serverAddr.String()
834 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
835 // given list of possible protocols and a list of the preference order. The
836 // first list must not be empty. It returns the resulting protocol and flag
837 // indicating if the fallback case was reached.
838 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
839 for _, s := range preferenceProtos {
840 for _, c := range protos {
847 return protos[0], true
850 // hostnameInSNI converts name into an approriate hostname for SNI.
851 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
852 // See https://tools.ietf.org/html/rfc6066#section-3.
853 func hostnameInSNI(name string) string {
855 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
856 host = host[1 : len(host)-1]
858 if i := strings.LastIndex(host, "%"); i > 0 {
861 if net.ParseIP(host) != nil {
864 for len(name) > 0 && name[len(name)-1] == '.' {
865 name = name[:len(name)-1]