handshake_server.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. "sync/atomic"
  17. "time"
  18. )
  19. // serverHandshakeState contains details of a server handshake in progress.
  20. // It's discarded once the handshake has completed.
  21. type serverHandshakeState struct {
  22. c *Conn
  23. suite *cipherSuite
  24. masterSecret []byte
  25. cachedClientHelloInfo *ClientHelloInfo
  26. clientHello *clientHelloMsg
  27. hello *serverHelloMsg
  28. cert *Certificate
  29. privateKey crypto.PrivateKey
  30. // A marshalled DelegatedCredential to be sent to the client in the
  31. // handshake.
  32. delegatedCredential []byte
  33. // TLS 1.0-1.2 fields
  34. ellipticOk bool
  35. ecdsaOk bool
  36. rsaDecryptOk bool
  37. rsaSignOk bool
  38. sessionState *sessionState
  39. finishedHash finishedHash
  40. certsFromClient [][]byte
  41. // TLS 1.3 fields
  42. hello13Enc *encryptedExtensionsMsg
  43. keySchedule *keySchedule13
  44. clientFinishedKey []byte
  45. hsClientCipher interface{}
  46. appClientCipher interface{}
  47. }
  48. // serverHandshake performs a TLS handshake as a server.
  49. // c.out.Mutex <= L; c.handshakeMutex <= L.
  50. func (c *Conn) serverHandshake() error {
  51. // If this is the first server handshake, we generate a random key to
  52. // encrypt the tickets with.
  53. c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
  54. hs := serverHandshakeState{
  55. c: c,
  56. }
  57. c.in.traceErr = hs.traceErr
  58. c.out.traceErr = hs.traceErr
  59. isResume, err := hs.readClientHello()
  60. // [Psiphon]
  61. // The ClientHello with the passthrough message is now available. Route the
  62. // client to passthrough based on message inspection. This code assumes the
  63. // client TCP conn has been wrapped with recordingConn, which has recorded
  64. // all bytes sent by the client, which will be replayed, byte-for-byte, to
  65. // the passthrough; as a result, passthrough clients will perform their TLS
  66. // handshake with the passthrough target, receive its certificate, and in the
  67. // case of HTTPS, receive the passthrough target's HTTP responses.
  68. //
  69. // Passthrough is also triggered if readClientHello fails. E.g., on other
  70. // invalid input cases including "tls: handshake message of length..." or if
  71. // the ClientHello is otherwise invalid. This ensures that clients sending
  72. // random data will be relayed to the passthrough and not receive a
  73. // distinguishing error response.
  74. //
  75. // The `tls` API performs handshakes on demand. E.g., the first call to
  76. // tls.Conn.Read will perform a handshake if it's not yet been performed.
  77. // Consumers such as `http` may call Read and then Close. To minimize code
  78. // changes, in the passthrough case the ownership of Conn.conn, the client
  79. // TCP conn, is transferred to the passthrough relay and a closedConn is
  80. // substituted for Conn.conn. This allows the remaining `tls` code paths to
  81. // continue reference a net.Conn, albeit one that is closed, so Reads and
  82. // Writes will fail.
  83. if c.config.PassthroughAddress != "" {
  84. doPassthrough := false
  85. if err != nil {
  86. doPassthrough = true
  87. err = fmt.Errorf("passthrough: %s", err)
  88. }
  89. clientAddr := c.conn.RemoteAddr().String()
  90. clientIP, _, _ := net.SplitHostPort(clientAddr)
  91. if !doPassthrough {
  92. if !c.config.PassthroughVerifyMessage(hs.clientHello.random) {
  93. c.config.PassthroughLogInvalidMessage(clientIP)
  94. doPassthrough = true
  95. err = errors.New("passthrough: invalid client random")
  96. }
  97. }
  98. if !doPassthrough {
  99. if !c.config.PassthroughHistoryAddNew(
  100. clientIP, hs.clientHello.random) {
  101. doPassthrough = true
  102. err = errors.New("passthrough: duplicate client random")
  103. }
  104. }
  105. // Call GetReadBuffer, in both passthrough and non-passthrough cases, to
  106. // stop buffering all read bytes.
  107. passthroughReadBuffer := c.conn.(*recorderConn).GetReadBuffer().Bytes()
  108. if doPassthrough {
  109. // When performing passthrough, we must exit at the "return err" below.
  110. // This is a failsafe to ensure err is always set.
  111. if err == nil {
  112. err = errors.New("passthrough: missing error")
  113. }
  114. // Modifying c.conn directly is safe only because Conn.Handshake, which
  115. // calls Conn.serverHandshake, is holding c.handshakeMutex and c.in locks,
  116. // and because of the serial nature of c.conn access during the handshake
  117. // sequence.
  118. conn := c.conn
  119. c.conn = newClosedConn(conn)
  120. go func() {
  121. // Perform the passthrough relay.
  122. //
  123. // Limitations:
  124. //
  125. // - The local TCP stack may differ from passthrough target in a
  126. // detectable way.
  127. //
  128. // - There may be detectable timing characteristics due to the network hop
  129. // to the passthrough target.
  130. //
  131. // - Application-level socket operations may produce detectable
  132. // differences (e.g., CloseWrite/FIN).
  133. //
  134. // - The dial to the passthrough, or other upstream network operations,
  135. // may fail. These errors are not logged.
  136. //
  137. // - There's no timeout on the passthrough dial and no time limit on the
  138. // passthrough relay so that the invalid client can't detect a timeout
  139. // shorter than the passthrough target; this may cause additional load.
  140. defer conn.Close()
  141. passthroughConn, err := net.Dial("tcp", c.config.PassthroughAddress)
  142. if err != nil {
  143. return
  144. }
  145. _, err = passthroughConn.Write(passthroughReadBuffer)
  146. if err != nil {
  147. return
  148. }
  149. // Allow garbage collection.
  150. passthroughReadBuffer = nil
  151. go func() {
  152. _, _ = io.Copy(passthroughConn, conn)
  153. passthroughConn.Close()
  154. }()
  155. _, _ = io.Copy(conn, passthroughConn)
  156. }()
  157. }
  158. }
  159. if err != nil {
  160. return err
  161. }
  162. // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
  163. // and https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2
  164. c.buffering = true
  165. if c.vers >= VersionTLS13 {
  166. if err := hs.doTLS13Handshake(); err != nil {
  167. return err
  168. }
  169. if _, err := c.flush(); err != nil {
  170. return err
  171. }
  172. c.hs = &hs
  173. // If the client is sending early data while the server expects
  174. // it, delay the Finished check until HandshakeConfirmed() is
  175. // called or until all early data is Read(). Otherwise, complete
  176. // authenticating the client now (there is no support for
  177. // sending 0.5-RTT data to a potential unauthenticated client).
  178. if c.phase != readingEarlyData {
  179. if err := hs.readClientFinished13(false); err != nil {
  180. return err
  181. }
  182. }
  183. atomic.StoreUint32(&c.handshakeStatus, 1)
  184. return nil
  185. } else if isResume {
  186. // The client has included a session ticket and so we do an abbreviated handshake.
  187. if err := hs.doResumeHandshake(); err != nil {
  188. return err
  189. }
  190. if err := hs.establishKeys(); err != nil {
  191. return err
  192. }
  193. // ticketSupported is set in a resumption handshake if the
  194. // ticket from the client was encrypted with an old session
  195. // ticket key and thus a refreshed ticket should be sent.
  196. if hs.hello.ticketSupported {
  197. if err := hs.sendSessionTicket(); err != nil {
  198. return err
  199. }
  200. }
  201. if err := hs.sendFinished(c.serverFinished[:]); err != nil {
  202. return err
  203. }
  204. if _, err := c.flush(); err != nil {
  205. return err
  206. }
  207. c.clientFinishedIsFirst = false
  208. if err := hs.readFinished(nil); err != nil {
  209. return err
  210. }
  211. c.didResume = true
  212. } else {
  213. // The client didn't include a session ticket, or it wasn't
  214. // valid so we do a full handshake.
  215. if err := hs.doFullHandshake(); err != nil {
  216. return err
  217. }
  218. if err := hs.establishKeys(); err != nil {
  219. return err
  220. }
  221. if err := hs.readFinished(c.clientFinished[:]); err != nil {
  222. return err
  223. }
  224. c.clientFinishedIsFirst = true
  225. c.buffering = true
  226. if err := hs.sendSessionTicket(); err != nil {
  227. return err
  228. }
  229. if err := hs.sendFinished(nil); err != nil {
  230. return err
  231. }
  232. if _, err := c.flush(); err != nil {
  233. return err
  234. }
  235. }
  236. if c.hand.Len() > 0 {
  237. return c.sendAlert(alertUnexpectedMessage)
  238. }
  239. c.phase = handshakeConfirmed
  240. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  241. // [Psiphon]
  242. // https://github.com/golang/go/commit/e5b13401c6b19f58a8439f1019a80fe540c0c687
  243. atomic.StoreUint32(&c.handshakeStatus, 1)
  244. return nil
  245. }
  246. // [Psiphon]
  247. // recorderConn is a net.Conn which records all bytes read from the wrapped
  248. // conn until GetReadBuffer is called, which returns the buffered bytes and
  249. // stops recording. This is used to replay, byte-for-byte, the bytes sent by a
  250. // client when switching to passthrough.
  251. //
  252. // recorderConn operations are not safe for concurrent use and intended only
  253. // to be used in the initial phase of the TLS handshake, where the order of
  254. // operations is deterministic.
  255. type recorderConn struct {
  256. net.Conn
  257. readBuffer *bytes.Buffer
  258. }
  259. func newRecorderConn(conn net.Conn) *recorderConn {
  260. return &recorderConn{
  261. Conn: conn,
  262. readBuffer: new(bytes.Buffer),
  263. }
  264. }
  265. func (c *recorderConn) Read(p []byte) (n int, err error) {
  266. n, err = c.Conn.Read(p)
  267. if n > 0 && c.readBuffer != nil {
  268. _, _ = c.readBuffer.Write(p[:n])
  269. }
  270. return n, err
  271. }
  272. func (c *recorderConn) GetReadBuffer() *bytes.Buffer {
  273. b := c.readBuffer
  274. c.readBuffer = nil
  275. return b
  276. }
  277. func (c *recorderConn) IsRecording() bool {
  278. return c.readBuffer != nil
  279. }
  280. // [Psiphon]
  281. // closedConn is a net.Conn which behaves as if it were closed: all reads and
  282. // writes fail. This is used when switching to passthrough mode: ownership of
  283. // the invalid client conn is taken by the passthrough relay and a closedConn
  284. // replaces the network conn used by the local TLS server code path.
  285. type closedConn struct {
  286. localAddr net.Addr
  287. remoteAddr net.Addr
  288. }
  289. var closedClosedError = errors.New("closed")
  290. func newClosedConn(conn net.Conn) *closedConn {
  291. return &closedConn{
  292. localAddr: conn.LocalAddr(),
  293. remoteAddr: conn.RemoteAddr(),
  294. }
  295. }
  296. func (c *closedConn) Read(_ []byte) (int, error) {
  297. return 0, closedClosedError
  298. }
  299. func (c *closedConn) Write(_ []byte) (int, error) {
  300. return 0, closedClosedError
  301. }
  302. func (c *closedConn) Close() error {
  303. return nil
  304. }
  305. func (c *closedConn) LocalAddr() net.Addr {
  306. return c.localAddr
  307. }
  308. func (c *closedConn) RemoteAddr() net.Addr {
  309. return c.remoteAddr
  310. }
  311. func (c *closedConn) SetDeadline(_ time.Time) error {
  312. return closedClosedError
  313. }
  314. func (c *closedConn) SetReadDeadline(_ time.Time) error {
  315. return closedClosedError
  316. }
  317. func (c *closedConn) SetWriteDeadline(_ time.Time) error {
  318. return closedClosedError
  319. }
  320. // readClientHello reads a ClientHello message from the client and decides
  321. // whether we will perform session resumption.
  322. func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
  323. c := hs.c
  324. msg, err := c.readHandshake()
  325. if err != nil {
  326. return false, err
  327. }
  328. var ok bool
  329. hs.clientHello, ok = msg.(*clientHelloMsg)
  330. if !ok {
  331. c.sendAlert(alertUnexpectedMessage)
  332. return false, unexpectedMessageError(hs.clientHello, msg)
  333. }
  334. if c.config.GetConfigForClient != nil {
  335. if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
  336. c.out.traceErr, c.in.traceErr = nil, nil // disable tracing
  337. c.sendAlert(alertInternalError)
  338. return false, err
  339. } else if newConfig != nil {
  340. newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
  341. c.config = newConfig
  342. }
  343. }
  344. var keyShares []CurveID
  345. for _, ks := range hs.clientHello.keyShares {
  346. keyShares = append(keyShares, ks.group)
  347. }
  348. if hs.clientHello.supportedVersions != nil {
  349. c.vers, ok = c.config.pickVersion(hs.clientHello.supportedVersions)
  350. if !ok {
  351. c.sendAlert(alertProtocolVersion)
  352. return false, fmt.Errorf("tls: none of the client versions (%x) are supported", hs.clientHello.supportedVersions)
  353. }
  354. } else {
  355. c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
  356. if !ok {
  357. c.sendAlert(alertProtocolVersion)
  358. return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
  359. }
  360. }
  361. c.haveVers = true
  362. preferredCurves := c.config.curvePreferences()
  363. Curves:
  364. for _, curve := range hs.clientHello.supportedCurves {
  365. for _, supported := range preferredCurves {
  366. if supported == curve {
  367. hs.ellipticOk = true
  368. break Curves
  369. }
  370. }
  371. }
  372. // [Psiphon]
  373. hasSupportedPoints := false
  374. // If present, the supported points extension must include uncompressed.
  375. // Can be absent. This behavior mirrors BoringSSL.
  376. if hs.clientHello.supportedPoints != nil {
  377. supportedPointFormat := false
  378. for _, pointFormat := range hs.clientHello.supportedPoints {
  379. if pointFormat == pointFormatUncompressed {
  380. supportedPointFormat = true
  381. break
  382. }
  383. }
  384. if !supportedPointFormat {
  385. c.sendAlert(alertHandshakeFailure)
  386. return false, errors.New("tls: client does not support uncompressed points")
  387. }
  388. hasSupportedPoints = true
  389. }
  390. foundCompression := false
  391. // We only support null compression, so check that the client offered it.
  392. for _, compression := range hs.clientHello.compressionMethods {
  393. if compression == compressionNone {
  394. foundCompression = true
  395. break
  396. }
  397. }
  398. if !foundCompression {
  399. c.sendAlert(alertIllegalParameter)
  400. return false, errors.New("tls: client does not support uncompressed connections")
  401. }
  402. if len(hs.clientHello.compressionMethods) != 1 && c.vers >= VersionTLS13 {
  403. c.sendAlert(alertIllegalParameter)
  404. return false, errors.New("tls: 1.3 client offered compression")
  405. }
  406. if len(hs.clientHello.secureRenegotiation) != 0 {
  407. c.sendAlert(alertHandshakeFailure)
  408. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  409. }
  410. if c.vers < VersionTLS13 {
  411. hs.hello = new(serverHelloMsg)
  412. hs.hello.vers = c.vers
  413. hs.hello.random = make([]byte, 32)
  414. _, err = io.ReadFull(c.config.rand(), hs.hello.random)
  415. if err != nil {
  416. c.sendAlert(alertInternalError)
  417. return false, err
  418. }
  419. hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
  420. hs.hello.compressionMethod = compressionNone
  421. } else {
  422. hs.hello = new(serverHelloMsg)
  423. hs.hello13Enc = new(encryptedExtensionsMsg)
  424. hs.hello.vers = c.vers
  425. hs.hello.random = make([]byte, 32)
  426. hs.hello.sessionId = hs.clientHello.sessionId
  427. _, err = io.ReadFull(c.config.rand(), hs.hello.random)
  428. if err != nil {
  429. c.sendAlert(alertInternalError)
  430. return false, err
  431. }
  432. }
  433. // [Psiphon]
  434. // https://github.com/golang/go/commit/02a5502ab8d862309aaec3c5ec293b57b913d01d
  435. if hasSupportedPoints && c.vers < VersionTLS13 {
  436. // Although omitting the ec_point_formats extension is permitted, some
  437. // old OpenSSL versions will refuse to handshake if not present.
  438. //
  439. // Per RFC 4492, section 5.1.2, implementations MUST support the
  440. // uncompressed point format. See golang.org/issue/31943.
  441. hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
  442. }
  443. if len(hs.clientHello.serverName) > 0 {
  444. c.serverName = hs.clientHello.serverName
  445. }
  446. if len(hs.clientHello.alpnProtocols) > 0 {
  447. if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
  448. if hs.hello13Enc != nil {
  449. hs.hello13Enc.alpnProtocol = selectedProto
  450. } else {
  451. hs.hello.alpnProtocol = selectedProto
  452. }
  453. c.clientProtocol = selectedProto
  454. }
  455. } else {
  456. // Although sending an empty NPN extension is reasonable, Firefox has
  457. // had a bug around this. Best to send nothing at all if
  458. // c.config.NextProtos is empty. See
  459. // https://golang.org/issue/5445.
  460. if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 && c.vers < VersionTLS13 {
  461. hs.hello.nextProtoNeg = true
  462. hs.hello.nextProtos = c.config.NextProtos
  463. }
  464. }
  465. hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
  466. if err != nil {
  467. c.sendAlert(alertInternalError)
  468. return false, err
  469. }
  470. // Set the private key for this handshake to the certificate's secret key.
  471. hs.privateKey = hs.cert.PrivateKey
  472. if hs.clientHello.scts {
  473. hs.hello.scts = hs.cert.SignedCertificateTimestamps
  474. }
  475. // Set the private key to the DC private key if the client and server are
  476. // willing to negotiate the delegated credential extension.
  477. //
  478. // Check to see if a DelegatedCredential is available and should be used.
  479. // If one is available, the session is using TLS >= 1.2, and the client
  480. // accepts the delegated credential extension, then set the handshake
  481. // private key to the DC private key.
  482. if c.config.GetDelegatedCredential != nil && hs.clientHello.delegatedCredential && c.vers >= VersionTLS12 {
  483. dc, sk, err := c.config.GetDelegatedCredential(hs.clientHelloInfo(), c.vers)
  484. if err != nil {
  485. c.sendAlert(alertInternalError)
  486. return false, err
  487. }
  488. // Set the handshake private key.
  489. if dc != nil {
  490. hs.privateKey = sk
  491. hs.delegatedCredential = dc
  492. }
  493. }
  494. if priv, ok := hs.privateKey.(crypto.Signer); ok {
  495. switch priv.Public().(type) {
  496. case *ecdsa.PublicKey:
  497. hs.ecdsaOk = true
  498. case *rsa.PublicKey:
  499. hs.rsaSignOk = true
  500. default:
  501. c.sendAlert(alertInternalError)
  502. return false, fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
  503. }
  504. }
  505. if priv, ok := hs.privateKey.(crypto.Decrypter); ok {
  506. switch priv.Public().(type) {
  507. case *rsa.PublicKey:
  508. hs.rsaDecryptOk = true
  509. default:
  510. c.sendAlert(alertInternalError)
  511. return false, fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
  512. }
  513. }
  514. if c.vers != VersionTLS13 && hs.checkForResumption() {
  515. return true, nil
  516. }
  517. var preferenceList, supportedList []uint16
  518. if c.config.PreferServerCipherSuites {
  519. preferenceList = c.config.cipherSuites()
  520. supportedList = hs.clientHello.cipherSuites
  521. } else {
  522. preferenceList = hs.clientHello.cipherSuites
  523. supportedList = c.config.cipherSuites()
  524. }
  525. for _, id := range preferenceList {
  526. if hs.setCipherSuite(id, supportedList, c.vers) {
  527. break
  528. }
  529. }
  530. if hs.suite == nil {
  531. c.sendAlert(alertHandshakeFailure)
  532. return false, errors.New("tls: no cipher suite supported by both client and server")
  533. }
  534. // See https://tools.ietf.org/html/rfc7507.
  535. for _, id := range hs.clientHello.cipherSuites {
  536. if id == TLS_FALLBACK_SCSV {
  537. // The client is doing a fallback connection.
  538. if c.vers < c.config.maxVersion() {
  539. c.sendAlert(alertInappropriateFallback)
  540. return false, errors.New("tls: client using inappropriate protocol fallback")
  541. }
  542. break
  543. }
  544. }
  545. return false, nil
  546. }
  547. // checkForResumption reports whether we should perform resumption on this connection.
  548. func (hs *serverHandshakeState) checkForResumption() bool {
  549. c := hs.c
  550. if c.config.SessionTicketsDisabled {
  551. return false
  552. }
  553. sessionTicket := append([]uint8{}, hs.clientHello.sessionTicket...)
  554. serializedState, usedOldKey := c.decryptTicket(sessionTicket)
  555. hs.sessionState = &sessionState{usedOldKey: usedOldKey}
  556. if hs.sessionState.unmarshal(serializedState) != alertSuccess {
  557. return false
  558. }
  559. // Never resume a session for a different TLS version.
  560. if c.vers != hs.sessionState.vers {
  561. return false
  562. }
  563. // [Psiphon]
  564. // When using obfuscated session tickets, the client-generated session ticket
  565. // state never uses EMS. ClientHellos vary in EMS support. So, in this mode,
  566. // skip this check to ensure the obfuscated session tickets are not
  567. // rejected.
  568. if !c.config.UseObfuscatedSessionTickets {
  569. // Do not resume connections where client support for EMS has changed
  570. if (hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret) != hs.sessionState.usedEMS {
  571. return false
  572. }
  573. }
  574. cipherSuiteOk := false
  575. // Check that the client is still offering the ciphersuite in the session.
  576. for _, id := range hs.clientHello.cipherSuites {
  577. if id == hs.sessionState.cipherSuite {
  578. cipherSuiteOk = true
  579. break
  580. }
  581. }
  582. if !cipherSuiteOk {
  583. return false
  584. }
  585. // Check that we also support the ciphersuite from the session.
  586. if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
  587. return false
  588. }
  589. sessionHasClientCerts := len(hs.sessionState.certificates) != 0
  590. needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
  591. if needClientCerts && !sessionHasClientCerts {
  592. return false
  593. }
  594. if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
  595. return false
  596. }
  597. return true
  598. }
  599. func (hs *serverHandshakeState) doResumeHandshake() error {
  600. c := hs.c
  601. hs.hello.cipherSuite = hs.suite.id
  602. // We echo the client's session ID in the ServerHello to let it know
  603. // that we're doing a resumption.
  604. hs.hello.sessionId = hs.clientHello.sessionId
  605. hs.hello.ticketSupported = hs.sessionState.usedOldKey
  606. hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
  607. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  608. hs.finishedHash.discardHandshakeBuffer()
  609. hs.finishedHash.Write(hs.clientHello.marshal())
  610. hs.finishedHash.Write(hs.hello.marshal())
  611. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  612. return err
  613. }
  614. if len(hs.sessionState.certificates) > 0 {
  615. if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
  616. return err
  617. }
  618. }
  619. hs.masterSecret = hs.sessionState.masterSecret
  620. c.useEMS = hs.sessionState.usedEMS
  621. return nil
  622. }
  623. func (hs *serverHandshakeState) doFullHandshake() error {
  624. c := hs.c
  625. if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
  626. hs.hello.ocspStapling = true
  627. }
  628. hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
  629. hs.hello.cipherSuite = hs.suite.id
  630. hs.hello.extendedMSSupported = hs.clientHello.extendedMSSupported && c.config.UseExtendedMasterSecret
  631. hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
  632. if c.config.ClientAuth == NoClientCert {
  633. // No need to keep a full record of the handshake if client
  634. // certificates won't be used.
  635. hs.finishedHash.discardHandshakeBuffer()
  636. }
  637. hs.finishedHash.Write(hs.clientHello.marshal())
  638. hs.finishedHash.Write(hs.hello.marshal())
  639. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  640. return err
  641. }
  642. certMsg := new(certificateMsg)
  643. certMsg.certificates = hs.cert.Certificate
  644. hs.finishedHash.Write(certMsg.marshal())
  645. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  646. return err
  647. }
  648. if hs.hello.ocspStapling {
  649. certStatus := new(certificateStatusMsg)
  650. certStatus.statusType = statusTypeOCSP
  651. certStatus.response = hs.cert.OCSPStaple
  652. hs.finishedHash.Write(certStatus.marshal())
  653. if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
  654. return err
  655. }
  656. }
  657. keyAgreement := hs.suite.ka(c.vers)
  658. skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.privateKey, hs.clientHello, hs.hello)
  659. if err != nil {
  660. c.sendAlert(alertHandshakeFailure)
  661. return err
  662. }
  663. if skx != nil {
  664. hs.finishedHash.Write(skx.marshal())
  665. if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
  666. return err
  667. }
  668. }
  669. if c.config.ClientAuth >= RequestClientCert {
  670. // Request a client certificate
  671. certReq := new(certificateRequestMsg)
  672. certReq.certificateTypes = []byte{
  673. byte(certTypeRSASign),
  674. byte(certTypeECDSASign),
  675. }
  676. if c.vers >= VersionTLS12 {
  677. certReq.hasSignatureAndHash = true
  678. certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
  679. }
  680. // An empty list of certificateAuthorities signals to
  681. // the client that it may send any certificate in response
  682. // to our request. When we know the CAs we trust, then
  683. // we can send them down, so that the client can choose
  684. // an appropriate certificate to give to us.
  685. if c.config.ClientCAs != nil {
  686. certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
  687. }
  688. hs.finishedHash.Write(certReq.marshal())
  689. if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
  690. return err
  691. }
  692. }
  693. helloDone := new(serverHelloDoneMsg)
  694. hs.finishedHash.Write(helloDone.marshal())
  695. if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
  696. return err
  697. }
  698. if _, err := c.flush(); err != nil {
  699. return err
  700. }
  701. var pub crypto.PublicKey // public key for client auth, if any
  702. msg, err := c.readHandshake()
  703. if err != nil {
  704. return err
  705. }
  706. var ok bool
  707. // If we requested a client certificate, then the client must send a
  708. // certificate message, even if it's empty.
  709. if c.config.ClientAuth >= RequestClientCert {
  710. if certMsg, ok = msg.(*certificateMsg); !ok {
  711. c.sendAlert(alertUnexpectedMessage)
  712. return unexpectedMessageError(certMsg, msg)
  713. }
  714. hs.finishedHash.Write(certMsg.marshal())
  715. if len(certMsg.certificates) == 0 {
  716. // The client didn't actually send a certificate
  717. switch c.config.ClientAuth {
  718. case RequireAnyClientCert, RequireAndVerifyClientCert:
  719. c.sendAlert(alertBadCertificate)
  720. return errors.New("tls: client didn't provide a certificate")
  721. }
  722. }
  723. pub, err = hs.processCertsFromClient(certMsg.certificates)
  724. if err != nil {
  725. return err
  726. }
  727. msg, err = c.readHandshake()
  728. if err != nil {
  729. return err
  730. }
  731. }
  732. // Get client key exchange
  733. ckx, ok := msg.(*clientKeyExchangeMsg)
  734. if !ok {
  735. c.sendAlert(alertUnexpectedMessage)
  736. return unexpectedMessageError(ckx, msg)
  737. }
  738. hs.finishedHash.Write(ckx.marshal())
  739. preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.privateKey, ckx, c.vers)
  740. if err != nil {
  741. if err == errClientKeyExchange {
  742. c.sendAlert(alertDecodeError)
  743. } else {
  744. c.sendAlert(alertInternalError)
  745. }
  746. return err
  747. }
  748. c.useEMS = hs.hello.extendedMSSupported
  749. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random, hs.finishedHash, c.useEMS)
  750. if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.clientHello.random, hs.masterSecret); err != nil {
  751. c.sendAlert(alertInternalError)
  752. return err
  753. }
  754. // If we received a client cert in response to our certificate request message,
  755. // the client will send us a certificateVerifyMsg immediately after the
  756. // clientKeyExchangeMsg. This message is a digest of all preceding
  757. // handshake-layer messages that is signed using the private key corresponding
  758. // to the client's certificate. This allows us to verify that the client is in
  759. // possession of the private key of the certificate.
  760. if len(c.peerCertificates) > 0 {
  761. msg, err = c.readHandshake()
  762. if err != nil {
  763. return err
  764. }
  765. certVerify, ok := msg.(*certificateVerifyMsg)
  766. if !ok {
  767. c.sendAlert(alertUnexpectedMessage)
  768. return unexpectedMessageError(certVerify, msg)
  769. }
  770. // Determine the signature type.
  771. _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
  772. if err != nil {
  773. c.sendAlert(alertIllegalParameter)
  774. return err
  775. }
  776. var digest []byte
  777. if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
  778. err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
  779. }
  780. if err != nil {
  781. c.sendAlert(alertBadCertificate)
  782. return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
  783. }
  784. hs.finishedHash.Write(certVerify.marshal())
  785. }
  786. hs.finishedHash.discardHandshakeBuffer()
  787. return nil
  788. }
  789. func (hs *serverHandshakeState) establishKeys() error {
  790. c := hs.c
  791. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  792. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  793. var clientCipher, serverCipher interface{}
  794. var clientHash, serverHash macFunction
  795. if hs.suite.aead == nil {
  796. clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
  797. clientHash = hs.suite.mac(c.vers, clientMAC)
  798. serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
  799. serverHash = hs.suite.mac(c.vers, serverMAC)
  800. } else {
  801. clientCipher = hs.suite.aead(clientKey, clientIV)
  802. serverCipher = hs.suite.aead(serverKey, serverIV)
  803. }
  804. c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
  805. c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
  806. return nil
  807. }
  808. func (hs *serverHandshakeState) readFinished(out []byte) error {
  809. c := hs.c
  810. c.readRecord(recordTypeChangeCipherSpec)
  811. if c.in.err != nil {
  812. return c.in.err
  813. }
  814. if hs.hello.nextProtoNeg {
  815. msg, err := c.readHandshake()
  816. if err != nil {
  817. return err
  818. }
  819. nextProto, ok := msg.(*nextProtoMsg)
  820. if !ok {
  821. c.sendAlert(alertUnexpectedMessage)
  822. return unexpectedMessageError(nextProto, msg)
  823. }
  824. hs.finishedHash.Write(nextProto.marshal())
  825. c.clientProtocol = nextProto.proto
  826. }
  827. msg, err := c.readHandshake()
  828. if err != nil {
  829. return err
  830. }
  831. clientFinished, ok := msg.(*finishedMsg)
  832. if !ok {
  833. c.sendAlert(alertUnexpectedMessage)
  834. return unexpectedMessageError(clientFinished, msg)
  835. }
  836. verify := hs.finishedHash.clientSum(hs.masterSecret)
  837. if len(verify) != len(clientFinished.verifyData) ||
  838. subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
  839. c.sendAlert(alertDecryptError)
  840. return errors.New("tls: client's Finished message is incorrect")
  841. }
  842. hs.finishedHash.Write(clientFinished.marshal())
  843. copy(out, verify)
  844. return nil
  845. }
  846. func (hs *serverHandshakeState) sendSessionTicket() error {
  847. if !hs.hello.ticketSupported {
  848. return nil
  849. }
  850. c := hs.c
  851. m := new(newSessionTicketMsg)
  852. var err error
  853. state := sessionState{
  854. vers: c.vers,
  855. cipherSuite: hs.suite.id,
  856. masterSecret: hs.masterSecret,
  857. certificates: hs.certsFromClient,
  858. usedEMS: c.useEMS,
  859. }
  860. m.ticket, err = c.encryptTicket(state.marshal())
  861. if err != nil {
  862. return err
  863. }
  864. hs.finishedHash.Write(m.marshal())
  865. if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
  866. return err
  867. }
  868. return nil
  869. }
  870. func (hs *serverHandshakeState) sendFinished(out []byte) error {
  871. c := hs.c
  872. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  873. return err
  874. }
  875. finished := new(finishedMsg)
  876. finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  877. hs.finishedHash.Write(finished.marshal())
  878. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  879. return err
  880. }
  881. c.cipherSuite = hs.suite.id
  882. copy(out, finished.verifyData)
  883. return nil
  884. }
  885. // processCertsFromClient takes a chain of client certificates either from a
  886. // Certificates message or from a sessionState and verifies them. It returns
  887. // the public key of the leaf certificate.
  888. func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
  889. c := hs.c
  890. hs.certsFromClient = certificates
  891. certs := make([]*x509.Certificate, len(certificates))
  892. var err error
  893. for i, asn1Data := range certificates {
  894. if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  895. c.sendAlert(alertBadCertificate)
  896. return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
  897. }
  898. }
  899. if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  900. opts := x509.VerifyOptions{
  901. Roots: c.config.ClientCAs,
  902. CurrentTime: c.config.time(),
  903. Intermediates: x509.NewCertPool(),
  904. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  905. }
  906. for _, cert := range certs[1:] {
  907. opts.Intermediates.AddCert(cert)
  908. }
  909. chains, err := certs[0].Verify(opts)
  910. if err != nil {
  911. c.sendAlert(alertBadCertificate)
  912. return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
  913. }
  914. c.verifiedChains = chains
  915. }
  916. if c.config.VerifyPeerCertificate != nil {
  917. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  918. c.sendAlert(alertBadCertificate)
  919. return nil, err
  920. }
  921. }
  922. if len(certs) == 0 {
  923. return nil, nil
  924. }
  925. var pub crypto.PublicKey
  926. switch key := certs[0].PublicKey.(type) {
  927. case *ecdsa.PublicKey, *rsa.PublicKey:
  928. pub = key
  929. default:
  930. c.sendAlert(alertUnsupportedCertificate)
  931. return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  932. }
  933. c.peerCertificates = certs
  934. return pub, nil
  935. }
  936. // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
  937. // suite if that cipher suite is acceptable to use.
  938. // It returns a bool indicating if the suite was set.
  939. func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
  940. for _, supported := range supportedCipherSuites {
  941. if id == supported {
  942. var candidate *cipherSuite
  943. for _, s := range cipherSuites {
  944. if s.id == id {
  945. candidate = s
  946. break
  947. }
  948. }
  949. if candidate == nil {
  950. continue
  951. }
  952. if version >= VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  953. hs.suite = candidate
  954. return true
  955. }
  956. if version < VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  957. continue
  958. }
  959. // Don't select a ciphersuite which we can't
  960. // support for this client.
  961. if candidate.flags&suiteECDHE != 0 {
  962. if !hs.ellipticOk {
  963. continue
  964. }
  965. if candidate.flags&suiteECDSA != 0 {
  966. if !hs.ecdsaOk {
  967. continue
  968. }
  969. } else if !hs.rsaSignOk {
  970. continue
  971. }
  972. } else if !hs.rsaDecryptOk {
  973. continue
  974. }
  975. if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
  976. continue
  977. }
  978. hs.suite = candidate
  979. return true
  980. }
  981. }
  982. return false
  983. }
  984. // suppVersArray is the backing array of ClientHelloInfo.SupportedVersions
  985. var suppVersArray = [...]uint16{VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  986. func (hs *serverHandshakeState) clientHelloInfo() *ClientHelloInfo {
  987. if hs.cachedClientHelloInfo != nil {
  988. return hs.cachedClientHelloInfo
  989. }
  990. var supportedVersions []uint16
  991. if hs.clientHello.supportedVersions != nil {
  992. supportedVersions = hs.clientHello.supportedVersions
  993. } else if hs.clientHello.vers > VersionTLS12 {
  994. supportedVersions = suppVersArray[:]
  995. } else if hs.clientHello.vers >= VersionSSL30 {
  996. supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
  997. }
  998. var pskBinder []byte
  999. if len(hs.clientHello.psks) > 0 {
  1000. pskBinder = hs.clientHello.psks[0].binder
  1001. }
  1002. hs.cachedClientHelloInfo = &ClientHelloInfo{
  1003. CipherSuites: hs.clientHello.cipherSuites,
  1004. ServerName: hs.clientHello.serverName,
  1005. SupportedCurves: hs.clientHello.supportedCurves,
  1006. SupportedPoints: hs.clientHello.supportedPoints,
  1007. SignatureSchemes: hs.clientHello.supportedSignatureAlgorithms,
  1008. SupportedProtos: hs.clientHello.alpnProtocols,
  1009. SupportedVersions: supportedVersions,
  1010. Conn: hs.c.conn,
  1011. Offered0RTTData: hs.clientHello.earlyData,
  1012. AcceptsDelegatedCredential: hs.clientHello.delegatedCredential,
  1013. Fingerprint: pskBinder,
  1014. }
  1015. return hs.cachedClientHelloInfo
  1016. }