handshake_client.go 29 KB

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