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 var signatureType uint8
488 switch key.Public().(type) {
489 case *ecdsa.PublicKey:
490 signatureType = signatureECDSA
492 signatureType = signatureRSA
494 c.sendAlert(alertInternalError)
495 return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
498 // SignatureAndHashAlgorithm was introduced in TLS 1.2.
499 if certVerify.hasSignatureAndHash {
500 certVerify.signatureAlgorithm, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.supportedSignatureAlgorithms, signatureType)
502 c.sendAlert(alertInternalError)
506 digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(signatureType, certVerify.signatureAlgorithm, hs.masterSecret)
508 c.sendAlert(alertInternalError)
511 certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
513 c.sendAlert(alertInternalError)
517 hs.finishedHash.Write(certVerify.marshal())
518 if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
523 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
524 if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
525 c.sendAlert(alertInternalError)
526 return errors.New("tls: failed to write to key log: " + err.Error())
529 hs.finishedHash.discardHandshakeBuffer()
534 func (hs *clientHandshakeState) establishKeys() error {
537 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
538 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
539 var clientCipher, serverCipher interface{}
540 var clientHash, serverHash macFunction
541 if hs.suite.cipher != nil {
542 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
543 clientHash = hs.suite.mac(c.vers, clientMAC)
544 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
545 serverHash = hs.suite.mac(c.vers, serverMAC)
547 clientCipher = hs.suite.aead(clientKey, clientIV)
548 serverCipher = hs.suite.aead(serverKey, serverIV)
551 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
552 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
556 func (hs *clientHandshakeState) serverResumedSession() bool {
557 // If the server responded with the same sessionId then it means the
558 // sessionTicket is being used to resume a TLS session.
559 return hs.session != nil && hs.hello.sessionId != nil &&
560 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
563 func (hs *clientHandshakeState) processServerHello() (bool, error) {
566 if hs.serverHello.compressionMethod != compressionNone {
567 c.sendAlert(alertUnexpectedMessage)
568 return false, errors.New("tls: server selected unsupported compression format")
571 if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
572 c.secureRenegotiation = true
573 if len(hs.serverHello.secureRenegotiation) != 0 {
574 c.sendAlert(alertHandshakeFailure)
575 return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
579 if c.handshakes > 0 && c.secureRenegotiation {
580 var expectedSecureRenegotiation [24]byte
581 copy(expectedSecureRenegotiation[:], c.clientFinished[:])
582 copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
583 if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
584 c.sendAlert(alertHandshakeFailure)
585 return false, errors.New("tls: incorrect renegotiation extension contents")
589 clientDidNPN := hs.hello.nextProtoNeg
590 clientDidALPN := len(hs.hello.alpnProtocols) > 0
591 serverHasNPN := hs.serverHello.nextProtoNeg
592 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
594 if !clientDidNPN && serverHasNPN {
595 c.sendAlert(alertHandshakeFailure)
596 return false, errors.New("tls: server advertised unrequested NPN extension")
599 if !clientDidALPN && serverHasALPN {
600 c.sendAlert(alertHandshakeFailure)
601 return false, errors.New("tls: server advertised unrequested ALPN extension")
604 if serverHasNPN && serverHasALPN {
605 c.sendAlert(alertHandshakeFailure)
606 return false, errors.New("tls: server advertised both NPN and ALPN extensions")
610 c.clientProtocol = hs.serverHello.alpnProtocol
611 c.clientProtocolFallback = false
613 c.scts = hs.serverHello.scts
615 if !hs.serverResumedSession() {
619 if hs.session.vers != c.vers {
620 c.sendAlert(alertHandshakeFailure)
621 return false, errors.New("tls: server resumed a session with a different version")
624 if hs.session.cipherSuite != hs.suite.id {
625 c.sendAlert(alertHandshakeFailure)
626 return false, errors.New("tls: server resumed a session with a different cipher suite")
629 // Restore masterSecret and peerCerts from previous state
630 hs.masterSecret = hs.session.masterSecret
631 c.peerCertificates = hs.session.serverCertificates
632 c.verifiedChains = hs.session.verifiedChains
636 func (hs *clientHandshakeState) readFinished(out []byte) error {
639 c.readRecord(recordTypeChangeCipherSpec)
644 msg, err := c.readHandshake()
648 serverFinished, ok := msg.(*finishedMsg)
650 c.sendAlert(alertUnexpectedMessage)
651 return unexpectedMessageError(serverFinished, msg)
654 verify := hs.finishedHash.serverSum(hs.masterSecret)
655 if len(verify) != len(serverFinished.verifyData) ||
656 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
657 c.sendAlert(alertHandshakeFailure)
658 return errors.New("tls: server's Finished message was incorrect")
660 hs.finishedHash.Write(serverFinished.marshal())
665 func (hs *clientHandshakeState) readSessionTicket() error {
666 if !hs.serverHello.ticketSupported {
671 msg, err := c.readHandshake()
675 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
677 c.sendAlert(alertUnexpectedMessage)
678 return unexpectedMessageError(sessionTicketMsg, msg)
680 hs.finishedHash.Write(sessionTicketMsg.marshal())
682 hs.session = &ClientSessionState{
683 sessionTicket: sessionTicketMsg.ticket,
685 cipherSuite: hs.suite.id,
686 masterSecret: hs.masterSecret,
687 serverCertificates: c.peerCertificates,
688 verifiedChains: c.verifiedChains,
694 func (hs *clientHandshakeState) sendFinished(out []byte) error {
697 if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
700 if hs.serverHello.nextProtoNeg {
701 nextProto := new(nextProtoMsg)
702 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
703 nextProto.proto = proto
704 c.clientProtocol = proto
705 c.clientProtocolFallback = fallback
707 hs.finishedHash.Write(nextProto.marshal())
708 if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
713 finished := new(finishedMsg)
714 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
715 hs.finishedHash.Write(finished.marshal())
716 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
719 copy(out, finished.verifyData)
723 // tls11SignatureSchemes contains the signature schemes that we synthesise for
724 // a TLS <= 1.1 connection, based on the supported certificate types.
725 var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
728 // tls11SignatureSchemesNumECDSA is the number of initial elements of
729 // tls11SignatureSchemes that use ECDSA.
730 tls11SignatureSchemesNumECDSA = 3
731 // tls11SignatureSchemesNumRSA is the number of trailing elements of
732 // tls11SignatureSchemes that use RSA.
733 tls11SignatureSchemesNumRSA = 4
736 func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
739 var rsaAvail, ecdsaAvail bool
740 for _, certType := range certReq.certificateTypes {
742 case certTypeRSASign:
744 case certTypeECDSASign:
749 if c.config.GetClientCertificate != nil {
750 var signatureSchemes []SignatureScheme
752 if !certReq.hasSignatureAndHash {
753 // Prior to TLS 1.2, the signature schemes were not
754 // included in the certificate request message. In this
755 // case we use a plausible list based on the acceptable
756 // certificate types.
757 signatureSchemes = tls11SignatureSchemes
759 signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
762 signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
765 signatureSchemes = certReq.supportedSignatureAlgorithms
768 return c.config.GetClientCertificate(&CertificateRequestInfo{
769 AcceptableCAs: certReq.certificateAuthorities,
770 SignatureSchemes: signatureSchemes,
774 // RFC 4346 on the certificateAuthorities field: A list of the
775 // distinguished names of acceptable certificate authorities.
776 // These distinguished names may specify a desired
777 // distinguished name for a root CA or for a subordinate CA;
778 // thus, this message can be used to describe both known roots
779 // and a desired authorization space. If the
780 // certificate_authorities list is empty then the client MAY
781 // send any certificate of the appropriate
782 // ClientCertificateType, unless there is some external
783 // arrangement to the contrary.
785 // We need to search our list of client certs for one
786 // where SignatureAlgorithm is acceptable to the server and the
787 // Issuer is in certReq.certificateAuthorities
789 for i, chain := range c.config.Certificates {
790 if !rsaAvail && !ecdsaAvail {
794 for j, cert := range chain.Certificate {
795 x509Cert := chain.Leaf
796 // parse the certificate if this isn't the leaf
797 // node, or if chain.Leaf was nil
798 if j != 0 || x509Cert == nil {
800 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
801 c.sendAlert(alertInternalError)
802 return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
807 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
808 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
813 if len(certReq.certificateAuthorities) == 0 {
814 // they gave us an empty list, so just take the
815 // first cert from c.config.Certificates
819 for _, ca := range certReq.certificateAuthorities {
820 if bytes.Equal(x509Cert.RawIssuer, ca) {
827 // No acceptable certificate found. Don't send a certificate.
828 return new(Certificate), nil
831 // clientSessionCacheKey returns a key used to cache sessionTickets that could
832 // be used to resume previously negotiated TLS sessions with a server.
833 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
834 if len(config.ServerName) > 0 {
835 return config.ServerName
837 return serverAddr.String()
840 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
841 // given list of possible protocols and a list of the preference order. The
842 // first list must not be empty. It returns the resulting protocol and flag
843 // indicating if the fallback case was reached.
844 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
845 for _, s := range preferenceProtos {
846 for _, c := range protos {
853 return protos[0], true
856 // hostnameInSNI converts name into an approriate hostname for SNI.
857 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
858 // See https://tools.ietf.org/html/rfc6066#section-3.
859 func hostnameInSNI(name string) string {
861 if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
862 host = host[1 : len(host)-1]
864 if i := strings.LastIndex(host, "%"); i > 0 {
867 if net.ParseIP(host) != nil {
870 for len(name) > 0 && name[len(name)-1] == '.' {
871 name = name[:len(name)-1]