handshake_client.go 30 KB

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