Alternative TLS implementation in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1003 rivejä
29 KiB

  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.
  4. package th5
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/rsa"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "strconv"
  17. "strings"
  18. "sync/atomic"
  19. )
  20. type clientHandshakeState struct {
  21. c *Conn
  22. serverHello *serverHelloMsg
  23. hello *clientHelloMsg
  24. suite *cipherSuite
  25. masterSecret []byte
  26. session *ClientSessionState
  27. // TLS 1.0-1.2 fields
  28. finishedHash finishedHash
  29. // TLS 1.3 fields
  30. keySchedule *keySchedule13
  31. privateKey []byte
  32. }
  33. func makeClientHello(config *Config) (*clientHelloMsg, error) {
  34. if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
  35. return nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  36. }
  37. nextProtosLength := 0
  38. for _, proto := range config.NextProtos {
  39. if l := len(proto); l == 0 || l > 255 {
  40. return nil, errors.New("tls: invalid NextProtos value")
  41. } else {
  42. nextProtosLength += 1 + l
  43. }
  44. }
  45. if nextProtosLength > 0xffff {
  46. return nil, errors.New("tls: NextProtos values too large")
  47. }
  48. hello := &clientHelloMsg{
  49. vers: config.maxVersion(),
  50. compressionMethods: []uint8{compressionNone},
  51. random: make([]byte, 32),
  52. ocspStapling: true,
  53. scts: true,
  54. serverName: hostnameInSNI(config.ServerName),
  55. supportedCurves: config.curvePreferences(),
  56. supportedPoints: []uint8{pointFormatUncompressed},
  57. nextProtoNeg: len(config.NextProtos) > 0,
  58. secureRenegotiationSupported: true,
  59. delegatedCredential: config.AcceptDelegatedCredential,
  60. alpnProtocols: config.NextProtos,
  61. extendedMSSupported: config.UseExtendedMasterSecret,
  62. }
  63. possibleCipherSuites := config.cipherSuites()
  64. hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
  65. NextCipherSuite:
  66. for _, suiteId := range possibleCipherSuites {
  67. for _, suite := range cipherSuites {
  68. if suite.id != suiteId {
  69. continue
  70. }
  71. // Don't advertise TLS 1.2-only cipher suites unless
  72. // we're attempting TLS 1.2.
  73. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  74. continue NextCipherSuite
  75. }
  76. // Don't advertise TLS 1.3-only cipher suites unless
  77. // we're attempting TLS 1.3.
  78. if hello.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
  79. continue NextCipherSuite
  80. }
  81. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  82. continue NextCipherSuite
  83. }
  84. }
  85. _, err := io.ReadFull(config.rand(), hello.random)
  86. if err != nil {
  87. return nil, errors.New("tls: short read from Rand: " + err.Error())
  88. }
  89. if hello.vers >= VersionTLS12 {
  90. hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
  91. }
  92. if hello.vers >= VersionTLS13 {
  93. // Version preference is indicated via "supported_extensions",
  94. // set legacy_version to TLS 1.2 for backwards compatibility.
  95. hello.vers = VersionTLS12
  96. hello.supportedVersions = config.getSupportedVersions()
  97. hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms13
  98. hello.supportedSignatureAlgorithmsCert = supportedSigAlgorithmsCert(supportedSignatureAlgorithms13)
  99. }
  100. return hello, nil
  101. }
  102. // c.out.Mutex <= L; c.handshakeMutex <= L.
  103. func (c *Conn) clientHandshake() error {
  104. if c.config == nil {
  105. c.config = defaultConfig()
  106. }
  107. // This may be a renegotiation handshake, in which case some fields
  108. // need to be reset.
  109. c.didResume = false
  110. hello, err := makeClientHello(c.config)
  111. if err != nil {
  112. return err
  113. }
  114. if c.handshakes > 0 {
  115. hello.secureRenegotiation = c.clientFinished[:]
  116. }
  117. var session *ClientSessionState
  118. var cacheKey string
  119. sessionCache := c.config.ClientSessionCache
  120. // TLS 1.3 has no session resumption based on session tickets.
  121. if c.config.SessionTicketsDisabled || c.config.maxVersion() >= VersionTLS13 {
  122. sessionCache = nil
  123. }
  124. if sessionCache != nil {
  125. hello.ticketSupported = true
  126. }
  127. // Session resumption is not allowed if renegotiating because
  128. // renegotiation is primarily used to allow a client to send a client
  129. // certificate, which would be skipped if session resumption occurred.
  130. if sessionCache != nil && c.handshakes == 0 {
  131. // Try to resume a previously negotiated TLS session, if
  132. // available.
  133. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  134. candidateSession, ok := sessionCache.Get(cacheKey)
  135. if ok {
  136. // Check that the ciphersuite/version used for the
  137. // previous session are still valid.
  138. cipherSuiteOk := false
  139. for _, id := range hello.cipherSuites {
  140. if id == candidateSession.cipherSuite {
  141. cipherSuiteOk = true
  142. break
  143. }
  144. }
  145. versOk := candidateSession.vers >= c.config.minVersion() &&
  146. candidateSession.vers <= c.config.maxVersion()
  147. if versOk && cipherSuiteOk {
  148. session = candidateSession
  149. }
  150. }
  151. }
  152. if session != nil {
  153. hello.sessionTicket = session.sessionTicket
  154. // A random session ID is used to detect when the
  155. // server accepted the ticket and is resuming a session
  156. // (see RFC 5077).
  157. hello.sessionId = make([]byte, 16)
  158. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  159. return errors.New("tls: short read from Rand: " + err.Error())
  160. }
  161. }
  162. hs := &clientHandshakeState{
  163. c: c,
  164. hello: hello,
  165. session: session,
  166. }
  167. var clientKS keyShare
  168. if c.config.maxVersion() >= VersionTLS13 {
  169. // Create one keyshare for the first default curve. If it is not
  170. // appropriate, the server should raise a HRR.
  171. defaultGroup := c.config.curvePreferences()[0]
  172. hs.privateKey, clientKS, err = c.generateKeyShare(defaultGroup)
  173. if err != nil {
  174. c.sendAlert(alertInternalError)
  175. return err
  176. }
  177. hello.keyShares = []keyShare{clientKS}
  178. // middlebox compatibility mode, provide a non-empty session ID
  179. hello.sessionId = make([]byte, 16)
  180. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  181. return errors.New("tls: short read from Rand: " + err.Error())
  182. }
  183. }
  184. if err = hs.handshake(); err != nil {
  185. return err
  186. }
  187. // If we had a successful handshake and hs.session is different from
  188. // the one already cached - cache a new one
  189. if sessionCache != nil && hs.session != nil && session != hs.session && c.vers < VersionTLS13 {
  190. sessionCache.Put(cacheKey, hs.session)
  191. }
  192. return nil
  193. }
  194. // Does the handshake, either a full one or resumes old session.
  195. // Requires hs.c, hs.hello, and, optionally, hs.session to be set.
  196. func (hs *clientHandshakeState) handshake() error {
  197. c := hs.c
  198. // send ClientHello
  199. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  200. return err
  201. }
  202. msg, err := c.readHandshake()
  203. if err != nil {
  204. return err
  205. }
  206. var ok bool
  207. if hs.serverHello, ok = msg.(*serverHelloMsg); !ok {
  208. c.sendAlert(alertUnexpectedMessage)
  209. return unexpectedMessageError(hs.serverHello, msg)
  210. }
  211. if err = hs.pickTLSVersion(); err != nil {
  212. return err
  213. }
  214. if err = hs.pickCipherSuite(); err != nil {
  215. return err
  216. }
  217. var isResume bool
  218. if c.vers >= VersionTLS13 {
  219. hs.keySchedule = newKeySchedule13(hs.suite, c.config, hs.hello.random)
  220. hs.keySchedule.write(hs.hello.marshal())
  221. hs.keySchedule.write(hs.serverHello.marshal())
  222. } else {
  223. isResume, err = hs.processServerHello()
  224. if err != nil {
  225. return err
  226. }
  227. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  228. // No signatures of the handshake are needed in a resumption.
  229. // Otherwise, in a full handshake, if we don't have any certificates
  230. // configured then we will never send a CertificateVerify message and
  231. // thus no signatures are needed in that case either.
  232. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  233. hs.finishedHash.discardHandshakeBuffer()
  234. }
  235. hs.finishedHash.Write(hs.hello.marshal())
  236. hs.finishedHash.Write(hs.serverHello.marshal())
  237. }
  238. c.buffering = true
  239. if c.vers >= VersionTLS13 {
  240. if err := hs.doTLS13Handshake(); err != nil {
  241. return err
  242. }
  243. if _, err := c.flush(); err != nil {
  244. return err
  245. }
  246. } else if isResume {
  247. if err := hs.establishKeys(); err != nil {
  248. return err
  249. }
  250. if err := hs.readSessionTicket(); err != nil {
  251. return err
  252. }
  253. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  254. return err
  255. }
  256. c.clientFinishedIsFirst = false
  257. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  258. return err
  259. }
  260. if _, err := c.flush(); err != nil {
  261. return err
  262. }
  263. } else {
  264. if err := hs.doFullHandshake(); err != nil {
  265. return err
  266. }
  267. if err := hs.establishKeys(); err != nil {
  268. return err
  269. }
  270. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  271. return err
  272. }
  273. if _, err := c.flush(); err != nil {
  274. return err
  275. }
  276. c.clientFinishedIsFirst = true
  277. if err := hs.readSessionTicket(); err != nil {
  278. return err
  279. }
  280. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  281. return err
  282. }
  283. }
  284. c.didResume = isResume
  285. c.phase = handshakeConfirmed
  286. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  287. c.handshakeComplete = true
  288. return nil
  289. }
  290. func (hs *clientHandshakeState) pickTLSVersion() error {
  291. vers, ok := hs.c.config.pickVersion([]uint16{hs.serverHello.vers})
  292. if !ok || vers < VersionTLS10 {
  293. // TLS 1.0 is the minimum version supported as a client.
  294. hs.c.sendAlert(alertProtocolVersion)
  295. return fmt.Errorf("tls: server selected unsupported protocol version %x", hs.serverHello.vers)
  296. }
  297. hs.c.vers = vers
  298. hs.c.haveVers = true
  299. return nil
  300. }
  301. func (hs *clientHandshakeState) pickCipherSuite() error {
  302. if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
  303. hs.c.sendAlert(alertHandshakeFailure)
  304. return errors.New("tls: server chose an unconfigured cipher suite")
  305. }
  306. // Check that the chosen cipher suite matches the protocol version.
  307. if hs.c.vers >= VersionTLS13 && hs.suite.flags&suiteTLS13 == 0 ||
  308. hs.c.vers < VersionTLS13 && hs.suite.flags&suiteTLS13 != 0 {
  309. hs.c.sendAlert(alertHandshakeFailure)
  310. return errors.New("tls: server chose an inappropriate cipher suite")
  311. }
  312. hs.c.cipherSuite = hs.suite.id
  313. return nil
  314. }
  315. // processCertsFromServer takes a chain of server certificates from a
  316. // Certificate message and verifies them.
  317. func (hs *clientHandshakeState) processCertsFromServer(certificates [][]byte) error {
  318. c := hs.c
  319. certs := make([]*x509.Certificate, len(certificates))
  320. for i, asn1Data := range certificates {
  321. cert, err := x509.ParseCertificate(asn1Data)
  322. if err != nil {
  323. c.sendAlert(alertBadCertificate)
  324. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  325. }
  326. certs[i] = cert
  327. }
  328. if !c.config.InsecureSkipVerify {
  329. opts := x509.VerifyOptions{
  330. Roots: c.config.RootCAs,
  331. CurrentTime: c.config.time(),
  332. DNSName: c.config.ServerName,
  333. Intermediates: x509.NewCertPool(),
  334. }
  335. for i, cert := range certs {
  336. if i == 0 {
  337. continue
  338. }
  339. opts.Intermediates.AddCert(cert)
  340. }
  341. var err error
  342. c.verifiedChains, err = certs[0].Verify(opts)
  343. if err != nil {
  344. c.sendAlert(alertBadCertificate)
  345. return err
  346. }
  347. }
  348. if c.config.VerifyPeerCertificate != nil {
  349. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  350. c.sendAlert(alertBadCertificate)
  351. return err
  352. }
  353. }
  354. switch certs[0].PublicKey.(type) {
  355. case *rsa.PublicKey, *ecdsa.PublicKey:
  356. break
  357. default:
  358. c.sendAlert(alertUnsupportedCertificate)
  359. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  360. }
  361. c.peerCertificates = certs
  362. return nil
  363. }
  364. // processDelegatedCredentialFromServer unmarshals the delegated credential
  365. // offered by the server (if present) and validates it using the peer
  366. // certificate and the signature scheme (`scheme`) indicated by the server in
  367. // the "signature_scheme" extension.
  368. func (hs *clientHandshakeState) processDelegatedCredentialFromServer(serialized []byte, scheme SignatureScheme) error {
  369. c := hs.c
  370. var dc *delegatedCredential
  371. var err error
  372. if serialized != nil {
  373. // Assert that the DC extension was indicated by the client.
  374. if !hs.hello.delegatedCredential {
  375. c.sendAlert(alertUnexpectedMessage)
  376. return errors.New("tls: got delegated credential extension without indication")
  377. }
  378. // Parse the delegated credential.
  379. dc, err = unmarshalDelegatedCredential(serialized)
  380. if err != nil {
  381. c.sendAlert(alertDecodeError)
  382. return fmt.Errorf("tls: delegated credential: %s", err)
  383. }
  384. }
  385. if dc != nil && !c.config.InsecureSkipVerify {
  386. if v, err := dc.validate(c.peerCertificates[0], c.config.time()); err != nil {
  387. c.sendAlert(alertIllegalParameter)
  388. return fmt.Errorf("delegated credential: %s", err)
  389. } else if !v {
  390. c.sendAlert(alertIllegalParameter)
  391. return errors.New("delegated credential: signature invalid")
  392. } else if dc.cred.expectedVersion != hs.c.vers {
  393. c.sendAlert(alertIllegalParameter)
  394. return errors.New("delegated credential: protocol version mismatch")
  395. } else if dc.cred.expectedCertVerifyAlgorithm != scheme {
  396. c.sendAlert(alertIllegalParameter)
  397. return errors.New("delegated credential: signature scheme mismatch")
  398. }
  399. }
  400. c.verifiedDc = dc
  401. return nil
  402. }
  403. func (hs *clientHandshakeState) doFullHandshake() error {
  404. c := hs.c
  405. msg, err := c.readHandshake()
  406. if err != nil {
  407. return err
  408. }
  409. certMsg, ok := msg.(*certificateMsg)
  410. if !ok || len(certMsg.certificates) == 0 {
  411. c.sendAlert(alertUnexpectedMessage)
  412. return unexpectedMessageError(certMsg, msg)
  413. }
  414. hs.finishedHash.Write(certMsg.marshal())
  415. if c.handshakes == 0 {
  416. // If this is the first handshake on a connection, process and
  417. // (optionally) verify the server's certificates.
  418. if err := hs.processCertsFromServer(certMsg.certificates); err != nil {
  419. return err
  420. }
  421. } else {
  422. // This is a renegotiation handshake. We require that the
  423. // server's identity (i.e. leaf certificate) is unchanged and
  424. // thus any previous trust decision is still valid.
  425. //
  426. // See https://mitls.org/pages/attacks/3SHAKE for the
  427. // motivation behind this requirement.
  428. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  429. c.sendAlert(alertBadCertificate)
  430. return errors.New("tls: server's identity changed during renegotiation")
  431. }
  432. }
  433. msg, err = c.readHandshake()
  434. if err != nil {
  435. return err
  436. }
  437. cs, ok := msg.(*certificateStatusMsg)
  438. if ok {
  439. // RFC4366 on Certificate Status Request:
  440. // The server MAY return a "certificate_status" message.
  441. if !hs.serverHello.ocspStapling {
  442. // If a server returns a "CertificateStatus" message, then the
  443. // server MUST have included an extension of type "status_request"
  444. // with empty "extension_data" in the extended server hello.
  445. c.sendAlert(alertUnexpectedMessage)
  446. return errors.New("tls: received unexpected CertificateStatus message")
  447. }
  448. hs.finishedHash.Write(cs.marshal())
  449. if cs.statusType == statusTypeOCSP {
  450. c.ocspResponse = cs.response
  451. }
  452. msg, err = c.readHandshake()
  453. if err != nil {
  454. return err
  455. }
  456. }
  457. keyAgreement := hs.suite.ka(c.vers)
  458. // Set the public key used to verify the handshake.
  459. pk := c.peerCertificates[0].PublicKey
  460. skx, ok := msg.(*serverKeyExchangeMsg)
  461. if ok {
  462. hs.finishedHash.Write(skx.marshal())
  463. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, pk, skx)
  464. if err != nil {
  465. c.sendAlert(alertUnexpectedMessage)
  466. return err
  467. }
  468. msg, err = c.readHandshake()
  469. if err != nil {
  470. return err
  471. }
  472. }
  473. var chainToSend *Certificate
  474. var certRequested bool
  475. certReq, ok := msg.(*certificateRequestMsg)
  476. if ok {
  477. certRequested = true
  478. hs.finishedHash.Write(certReq.marshal())
  479. if chainToSend, err = hs.getCertificate(certReq); err != nil {
  480. c.sendAlert(alertInternalError)
  481. return err
  482. }
  483. msg, err = c.readHandshake()
  484. if err != nil {
  485. return err
  486. }
  487. }
  488. shd, ok := msg.(*serverHelloDoneMsg)
  489. if !ok {
  490. c.sendAlert(alertUnexpectedMessage)
  491. return unexpectedMessageError(shd, msg)
  492. }
  493. hs.finishedHash.Write(shd.marshal())
  494. // If the server requested a certificate then we have to send a
  495. // Certificate message, even if it's empty because we don't have a
  496. // certificate to send.
  497. if certRequested {
  498. certMsg = new(certificateMsg)
  499. certMsg.certificates = chainToSend.Certificate
  500. hs.finishedHash.Write(certMsg.marshal())
  501. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  502. return err
  503. }
  504. }
  505. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, pk)
  506. if err != nil {
  507. c.sendAlert(alertInternalError)
  508. return err
  509. }
  510. if ckx != nil {
  511. hs.finishedHash.Write(ckx.marshal())
  512. if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
  513. return err
  514. }
  515. }
  516. c.useEMS = hs.serverHello.extendedMSSupported
  517. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random, hs.finishedHash, c.useEMS)
  518. if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.hello.random, hs.masterSecret); err != nil {
  519. c.sendAlert(alertInternalError)
  520. return errors.New("tls: failed to write to key log: " + err.Error())
  521. }
  522. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  523. certVerify := &certificateVerifyMsg{
  524. hasSignatureAndHash: c.vers >= VersionTLS12,
  525. }
  526. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  527. if !ok {
  528. c.sendAlert(alertInternalError)
  529. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  530. }
  531. signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
  532. if err != nil {
  533. c.sendAlert(alertInternalError)
  534. return err
  535. }
  536. // SignatureAndHashAlgorithm was introduced in TLS 1.2.
  537. if certVerify.hasSignatureAndHash {
  538. certVerify.signatureAlgorithm = signatureAlgorithm
  539. }
  540. digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
  541. if err != nil {
  542. c.sendAlert(alertInternalError)
  543. return err
  544. }
  545. signOpts := crypto.SignerOpts(hashFunc)
  546. if sigType == signatureRSAPSS {
  547. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
  548. }
  549. certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
  550. if err != nil {
  551. c.sendAlert(alertInternalError)
  552. return err
  553. }
  554. hs.finishedHash.Write(certVerify.marshal())
  555. if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
  556. return err
  557. }
  558. }
  559. c.Group = keyAgreement.NegotiatedGroup()
  560. hs.finishedHash.discardHandshakeBuffer()
  561. return nil
  562. }
  563. func (hs *clientHandshakeState) establishKeys() error {
  564. c := hs.c
  565. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  566. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  567. var clientCipher, serverCipher interface{}
  568. var clientHash, serverHash macFunction
  569. if hs.suite.cipher != nil {
  570. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  571. clientHash = hs.suite.mac(c.vers, clientMAC)
  572. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  573. serverHash = hs.suite.mac(c.vers, serverMAC)
  574. } else {
  575. clientCipher = hs.suite.aead(clientKey, clientIV)
  576. serverCipher = hs.suite.aead(serverKey, serverIV)
  577. }
  578. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  579. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  580. return nil
  581. }
  582. func (hs *clientHandshakeState) serverResumedSession() bool {
  583. // If the server responded with the same sessionId then it means the
  584. // sessionTicket is being used to resume a TLS session.
  585. return hs.session != nil && hs.hello.sessionId != nil &&
  586. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  587. }
  588. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  589. c := hs.c
  590. if hs.serverHello.compressionMethod != compressionNone {
  591. c.sendAlert(alertUnexpectedMessage)
  592. return false, errors.New("tls: server selected unsupported compression format")
  593. }
  594. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  595. c.secureRenegotiation = true
  596. if len(hs.serverHello.secureRenegotiation) != 0 {
  597. c.sendAlert(alertHandshakeFailure)
  598. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  599. }
  600. }
  601. if c.handshakes > 0 && c.secureRenegotiation {
  602. var expectedSecureRenegotiation [24]byte
  603. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  604. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  605. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  606. c.sendAlert(alertHandshakeFailure)
  607. return false, errors.New("tls: incorrect renegotiation extension contents")
  608. }
  609. }
  610. if hs.serverHello.extendedMSSupported {
  611. if hs.hello.extendedMSSupported {
  612. c.useEMS = true
  613. } else {
  614. // server wants to calculate master secret in a different way than client
  615. c.sendAlert(alertUnsupportedExtension)
  616. return false, errors.New("tls: unexpected extension (EMS) received in SH")
  617. }
  618. }
  619. clientDidNPN := hs.hello.nextProtoNeg
  620. clientDidALPN := len(hs.hello.alpnProtocols) > 0
  621. serverHasNPN := hs.serverHello.nextProtoNeg
  622. serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
  623. if !clientDidNPN && serverHasNPN {
  624. c.sendAlert(alertHandshakeFailure)
  625. return false, errors.New("tls: server advertised unrequested NPN extension")
  626. }
  627. if !clientDidALPN && serverHasALPN {
  628. c.sendAlert(alertHandshakeFailure)
  629. return false, errors.New("tls: server advertised unrequested ALPN extension")
  630. }
  631. if serverHasNPN && serverHasALPN {
  632. c.sendAlert(alertHandshakeFailure)
  633. return false, errors.New("tls: server advertised both NPN and ALPN extensions")
  634. }
  635. if serverHasALPN {
  636. c.clientProtocol = hs.serverHello.alpnProtocol
  637. c.clientProtocolFallback = false
  638. }
  639. c.scts = hs.serverHello.scts
  640. if !hs.serverResumedSession() {
  641. return false, nil
  642. }
  643. if hs.session.useEMS != c.useEMS {
  644. return false, errors.New("differing EMS state")
  645. }
  646. if hs.session.vers != c.vers {
  647. c.sendAlert(alertHandshakeFailure)
  648. return false, errors.New("tls: server resumed a session with a different version")
  649. }
  650. if hs.session.cipherSuite != hs.suite.id {
  651. c.sendAlert(alertHandshakeFailure)
  652. return false, errors.New("tls: server resumed a session with a different cipher suite")
  653. }
  654. // Restore masterSecret and peerCerts from previous state
  655. hs.masterSecret = hs.session.masterSecret
  656. c.peerCertificates = hs.session.serverCertificates
  657. c.verifiedChains = hs.session.verifiedChains
  658. return true, nil
  659. }
  660. func (hs *clientHandshakeState) readFinished(out []byte) error {
  661. c := hs.c
  662. c.readRecord(recordTypeChangeCipherSpec)
  663. if c.in.err != nil {
  664. return c.in.err
  665. }
  666. msg, err := c.readHandshake()
  667. if err != nil {
  668. return err
  669. }
  670. serverFinished, ok := msg.(*finishedMsg)
  671. if !ok {
  672. c.sendAlert(alertUnexpectedMessage)
  673. return unexpectedMessageError(serverFinished, msg)
  674. }
  675. verify := hs.finishedHash.serverSum(hs.masterSecret)
  676. if len(verify) != len(serverFinished.verifyData) ||
  677. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  678. c.sendAlert(alertDecryptError)
  679. return errors.New("tls: server's Finished message was incorrect")
  680. }
  681. hs.finishedHash.Write(serverFinished.marshal())
  682. copy(out, verify)
  683. return nil
  684. }
  685. func (hs *clientHandshakeState) readSessionTicket() error {
  686. if !hs.serverHello.ticketSupported {
  687. return nil
  688. }
  689. c := hs.c
  690. msg, err := c.readHandshake()
  691. if err != nil {
  692. return err
  693. }
  694. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  695. if !ok {
  696. c.sendAlert(alertUnexpectedMessage)
  697. return unexpectedMessageError(sessionTicketMsg, msg)
  698. }
  699. hs.finishedHash.Write(sessionTicketMsg.marshal())
  700. hs.session = &ClientSessionState{
  701. sessionTicket: sessionTicketMsg.ticket,
  702. vers: c.vers,
  703. cipherSuite: hs.suite.id,
  704. masterSecret: hs.masterSecret,
  705. serverCertificates: c.peerCertificates,
  706. verifiedChains: c.verifiedChains,
  707. useEMS: c.useEMS,
  708. }
  709. return nil
  710. }
  711. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  712. c := hs.c
  713. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  714. return err
  715. }
  716. if hs.serverHello.nextProtoNeg {
  717. nextProto := new(nextProtoMsg)
  718. proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
  719. nextProto.proto = proto
  720. c.clientProtocol = proto
  721. c.clientProtocolFallback = fallback
  722. hs.finishedHash.Write(nextProto.marshal())
  723. if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
  724. return err
  725. }
  726. }
  727. finished := new(finishedMsg)
  728. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  729. hs.finishedHash.Write(finished.marshal())
  730. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  731. return err
  732. }
  733. copy(out, finished.verifyData)
  734. return nil
  735. }
  736. // tls11SignatureSchemes contains the signature schemes that we synthesise for
  737. // a TLS <= 1.1 connection, based on the supported certificate types.
  738. var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
  739. const (
  740. // tls11SignatureSchemesNumECDSA is the number of initial elements of
  741. // tls11SignatureSchemes that use ECDSA.
  742. tls11SignatureSchemesNumECDSA = 3
  743. // tls11SignatureSchemesNumRSA is the number of trailing elements of
  744. // tls11SignatureSchemes that use RSA.
  745. tls11SignatureSchemesNumRSA = 4
  746. )
  747. func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
  748. c := hs.c
  749. var rsaAvail, ecdsaAvail bool
  750. for _, certType := range certReq.certificateTypes {
  751. switch certType {
  752. case certTypeRSASign:
  753. rsaAvail = true
  754. case certTypeECDSASign:
  755. ecdsaAvail = true
  756. }
  757. }
  758. if c.config.GetClientCertificate != nil {
  759. var signatureSchemes []SignatureScheme
  760. if !certReq.hasSignatureAndHash {
  761. // Prior to TLS 1.2, the signature schemes were not
  762. // included in the certificate request message. In this
  763. // case we use a plausible list based on the acceptable
  764. // certificate types.
  765. signatureSchemes = tls11SignatureSchemes
  766. if !ecdsaAvail {
  767. signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
  768. }
  769. if !rsaAvail {
  770. signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
  771. }
  772. } else {
  773. signatureSchemes = certReq.supportedSignatureAlgorithms
  774. }
  775. return c.config.GetClientCertificate(&CertificateRequestInfo{
  776. AcceptableCAs: certReq.certificateAuthorities,
  777. SignatureSchemes: signatureSchemes,
  778. })
  779. }
  780. // RFC 4346 on the certificateAuthorities field: A list of the
  781. // distinguished names of acceptable certificate authorities.
  782. // These distinguished names may specify a desired
  783. // distinguished name for a root CA or for a subordinate CA;
  784. // thus, this message can be used to describe both known roots
  785. // and a desired authorization space. If the
  786. // certificate_authorities list is empty then the client MAY
  787. // send any certificate of the appropriate
  788. // ClientCertificateType, unless there is some external
  789. // arrangement to the contrary.
  790. // We need to search our list of client certs for one
  791. // where SignatureAlgorithm is acceptable to the server and the
  792. // Issuer is in certReq.certificateAuthorities
  793. findCert:
  794. for i, chain := range c.config.Certificates {
  795. if !rsaAvail && !ecdsaAvail {
  796. continue
  797. }
  798. for j, cert := range chain.Certificate {
  799. x509Cert := chain.Leaf
  800. // parse the certificate if this isn't the leaf
  801. // node, or if chain.Leaf was nil
  802. if j != 0 || x509Cert == nil {
  803. var err error
  804. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  805. c.sendAlert(alertInternalError)
  806. return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
  807. }
  808. }
  809. switch {
  810. case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
  811. case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
  812. default:
  813. continue findCert
  814. }
  815. if len(certReq.certificateAuthorities) == 0 {
  816. // they gave us an empty list, so just take the
  817. // first cert from c.config.Certificates
  818. return &chain, nil
  819. }
  820. for _, ca := range certReq.certificateAuthorities {
  821. if bytes.Equal(x509Cert.RawIssuer, ca) {
  822. return &chain, nil
  823. }
  824. }
  825. }
  826. }
  827. // No acceptable certificate found. Don't send a certificate.
  828. return new(Certificate), nil
  829. }
  830. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  831. // be used to resume previously negotiated TLS sessions with a server.
  832. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
  833. if len(config.ServerName) > 0 {
  834. return config.ServerName
  835. }
  836. return serverAddr.String()
  837. }
  838. // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
  839. // given list of possible protocols and a list of the preference order. The
  840. // first list must not be empty. It returns the resulting protocol and flag
  841. // indicating if the fallback case was reached.
  842. func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  843. for _, s := range preferenceProtos {
  844. for _, c := range protos {
  845. if s == c {
  846. return s, false
  847. }
  848. }
  849. }
  850. return protos[0], true
  851. }
  852. // hostnameInSNI converts name into an appropriate hostname for SNI.
  853. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  854. // See https://tools.ietf.org/html/rfc6066#section-3.
  855. func hostnameInSNI(name string) string {
  856. host := name
  857. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  858. host = host[1 : len(host)-1]
  859. }
  860. if i := strings.LastIndex(host, "%"); i > 0 {
  861. host = host[:i]
  862. }
  863. if net.ParseIP(host) != nil {
  864. return ""
  865. }
  866. for len(name) > 0 && name[len(name)-1] == '.' {
  867. name = name[:len(name)-1]
  868. }
  869. return name
  870. }