ktls_read.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. //go:build linux && go1.25 && badlinkname
  5. package ktls
  6. import (
  7. "bytes"
  8. "crypto/tls"
  9. "fmt"
  10. "io"
  11. "net"
  12. )
  13. func (c *Conn) Read(b []byte) (int, error) {
  14. if !c.kernelRx {
  15. return c.Conn.Read(b)
  16. }
  17. if len(b) == 0 {
  18. // Put this after Handshake, in case people were calling
  19. // Read(nil) for the side effect of the Handshake.
  20. return 0, nil
  21. }
  22. c.rawConn.In.Lock()
  23. defer c.rawConn.In.Unlock()
  24. for c.rawConn.Input.Len() == 0 {
  25. if err := c.readRecord(); err != nil {
  26. return 0, err
  27. }
  28. for c.rawConn.Hand.Len() > 0 {
  29. if err := c.handlePostHandshakeMessage(); err != nil {
  30. return 0, err
  31. }
  32. }
  33. }
  34. n, _ := c.rawConn.Input.Read(b)
  35. // If a close-notify alert is waiting, read it so that we can return (n,
  36. // EOF) instead of (n, nil), to signal to the HTTP response reading
  37. // goroutine that the connection is now closed. This eliminates a race
  38. // where the HTTP response reading goroutine would otherwise not observe
  39. // the EOF until its next read, by which time a client goroutine might
  40. // have already tried to reuse the HTTP connection for a new request.
  41. // See https://golang.org/cl/76400046 and https://golang.org/issue/3514
  42. if n != 0 && c.rawConn.Input.Len() == 0 && c.rawConn.RawInput.Len() > 0 &&
  43. c.rawConn.RawInput.Bytes()[0] == recordTypeAlert {
  44. if err := c.readRecord(); err != nil {
  45. return n, err // will be io.EOF on closeNotify
  46. }
  47. }
  48. return n, nil
  49. }
  50. func (c *Conn) readRecord() error {
  51. if *c.rawConn.In.Err != nil {
  52. return *c.rawConn.In.Err
  53. }
  54. typ, data, err := c.readRawRecord()
  55. if err != nil {
  56. return err
  57. }
  58. if len(data) > maxPlaintext {
  59. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertRecordOverflow))
  60. }
  61. // Application Data messages are always protected.
  62. if c.rawConn.In.Cipher == nil && typ == recordTypeApplicationData {
  63. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  64. }
  65. //if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 {
  66. // This is a state-advancing message: reset the retry count.
  67. // c.retryCount = 0
  68. //}
  69. // Handshake messages MUST NOT be interleaved with other record types in TLS 1.3.
  70. if *c.rawConn.Vers == tls.VersionTLS13 && typ != recordTypeHandshake && c.rawConn.Hand.Len() > 0 {
  71. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  72. }
  73. switch typ {
  74. default:
  75. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  76. case recordTypeAlert:
  77. //if c.quic != nil {
  78. // return c.rawConn.In.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  79. //}
  80. if len(data) != 2 {
  81. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  82. }
  83. if data[1] == alertCloseNotify {
  84. return c.rawConn.In.SetErrorLocked(io.EOF)
  85. }
  86. if *c.rawConn.Vers == tls.VersionTLS13 {
  87. // TLS 1.3 removed warning-level alerts except for alertUserCanceled
  88. // (RFC 8446, § 6.1). Since at least one major implementation
  89. // (https://bugs.openjdk.org/browse/JDK-8323517) misuses this alert,
  90. // many TLS stacks now ignore it outright when seen in a TLS 1.3
  91. // handshake (e.g. BoringSSL, NSS, Rustls).
  92. if data[1] == alertUserCanceled {
  93. // Like TLS 1.2 alertLevelWarning alerts, we drop the record and retry.
  94. return c.retryReadRecord( /*expectChangeCipherSpec*/ )
  95. }
  96. return c.rawConn.In.SetErrorLocked(&net.OpError{Op: "remote error", Err: tls.AlertError(data[1])})
  97. }
  98. switch data[0] {
  99. case alertLevelWarning:
  100. // Drop the record on the floor and retry.
  101. return c.retryReadRecord( /*expectChangeCipherSpec*/ )
  102. case alertLevelError:
  103. return c.rawConn.In.SetErrorLocked(&net.OpError{Op: "remote error", Err: tls.AlertError(data[1])})
  104. default:
  105. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  106. }
  107. case recordTypeChangeCipherSpec:
  108. if len(data) != 1 || data[0] != 1 {
  109. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertDecodeError))
  110. }
  111. // Handshake messages are not allowed to fragment across the CCS.
  112. if c.rawConn.Hand.Len() > 0 {
  113. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  114. }
  115. // In TLS 1.3, change_cipher_spec records are ignored until the
  116. // Finished. See RFC 8446, Appendix D.4. Note that according to Section
  117. // 5, a server can send a ChangeCipherSpec before its ServerHello, when
  118. // c.vers is still unset. That's not useful though and suspicious if the
  119. // server then selects a lower protocol version, so don't allow that.
  120. if *c.rawConn.Vers == tls.VersionTLS13 {
  121. return c.retryReadRecord( /*expectChangeCipherSpec*/ )
  122. }
  123. // if !expectChangeCipherSpec {
  124. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  125. //}
  126. //if err := c.rawConn.In.changeCipherSpec(); err != nil {
  127. // return c.rawConn.In.setErrorLocked(c.sendAlert(err.(alert)))
  128. //}
  129. case recordTypeApplicationData:
  130. // Some OpenSSL servers send empty records in order to randomize the
  131. // CBC RawIV. Ignore a limited number of empty records.
  132. if len(data) == 0 {
  133. return c.retryReadRecord( /*expectChangeCipherSpec*/ )
  134. }
  135. // Note that data is owned by c.rawInput, following the Next call above,
  136. // to avoid copying the plaintext. This is safe because c.rawInput is
  137. // not read from or written to until c.input is drained.
  138. c.rawConn.Input.Reset(data)
  139. case recordTypeHandshake:
  140. if len(data) == 0 {
  141. return c.rawConn.In.SetErrorLocked(c.sendAlert(alertUnexpectedMessage))
  142. }
  143. c.rawConn.Hand.Write(data)
  144. }
  145. return nil
  146. }
  147. //nolint:staticcheck
  148. func (c *Conn) readRawRecord() (typ uint8, data []byte, err error) {
  149. // Read from kernel.
  150. if c.kernelRx {
  151. return c.readKernelRecord()
  152. }
  153. // Read header, payload.
  154. if err = c.readFromUntil(c.conn, recordHeaderLen); err != nil {
  155. // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify
  156. // is an error, but popular web sites seem to do this, so we accept it
  157. // if and only if at the record boundary.
  158. if err == io.ErrUnexpectedEOF && c.rawConn.RawInput.Len() == 0 {
  159. err = io.EOF
  160. }
  161. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  162. c.rawConn.In.SetErrorLocked(err)
  163. }
  164. return
  165. }
  166. hdr := c.rawConn.RawInput.Bytes()[:recordHeaderLen]
  167. typ = hdr[0]
  168. vers := uint16(hdr[1])<<8 | uint16(hdr[2])
  169. expectedVers := *c.rawConn.Vers
  170. if expectedVers == tls.VersionTLS13 {
  171. // All TLS 1.3 records are expected to have 0x0303 (1.2) after
  172. // the initial hello (RFC 8446 Section 5.1).
  173. expectedVers = tls.VersionTLS12
  174. }
  175. n := int(hdr[3])<<8 | int(hdr[4])
  176. if /*c.haveVers && */ vers != expectedVers {
  177. c.sendAlert(alertProtocolVersion)
  178. msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, expectedVers)
  179. err = c.rawConn.In.SetErrorLocked(c.newRecordHeaderError(nil, msg))
  180. return
  181. }
  182. //if !c.haveVers {
  183. // // First message, be extra suspicious: this might not be a TLS
  184. // // client. Bail out before reading a full 'body', if possible.
  185. // // The current max version is 3.3 so if the version is >= 16.0,
  186. // // it's probably not real.
  187. // if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 {
  188. // err = c.rawConn.In.SetErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake"))
  189. // return
  190. // }
  191. //}
  192. if *c.rawConn.Vers == tls.VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext {
  193. c.sendAlert(alertRecordOverflow)
  194. msg := fmt.Sprintf("oversized record received with length %d", n)
  195. err = c.rawConn.In.SetErrorLocked(c.newRecordHeaderError(nil, msg))
  196. return
  197. }
  198. if err = c.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  199. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  200. c.rawConn.In.SetErrorLocked(err)
  201. }
  202. return
  203. }
  204. // Process message.
  205. record := c.rawConn.RawInput.Next(recordHeaderLen + n)
  206. data, typ, err = c.rawConn.In.Decrypt(record)
  207. if err != nil {
  208. err = c.rawConn.In.SetErrorLocked(c.sendAlert(uint8(err.(tls.AlertError))))
  209. return
  210. }
  211. return
  212. }
  213. // retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record, like
  214. // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.
  215. func (c *Conn) retryReadRecord( /*expectChangeCipherSpec bool*/ ) error {
  216. //c.retryCount++
  217. //if c.retryCount > maxUselessRecords {
  218. // c.sendAlert(alertUnexpectedMessage)
  219. // return c.in.setErrorLocked(errors.New("tls: too many ignored records"))
  220. //}
  221. return c.readRecord( /*expectChangeCipherSpec*/ )
  222. }
  223. // atLeastReader reads from R, stopping with EOF once at least N bytes have been
  224. // read. It is different from an io.LimitedReader in that it doesn't cut short
  225. // the last Read call, and in that it considers an early EOF an error.
  226. type atLeastReader struct {
  227. R io.Reader
  228. N int64
  229. }
  230. func (r *atLeastReader) Read(p []byte) (int, error) {
  231. if r.N <= 0 {
  232. return 0, io.EOF
  233. }
  234. n, err := r.R.Read(p)
  235. r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809
  236. if r.N > 0 && err == io.EOF {
  237. return n, io.ErrUnexpectedEOF
  238. }
  239. if r.N <= 0 && err == nil {
  240. return n, io.EOF
  241. }
  242. return n, err
  243. }
  244. // readFromUntil reads from r into c.rawConn.RawInput until c.rawConn.RawInput contains
  245. // at least n bytes or else returns an error.
  246. func (c *Conn) readFromUntil(r io.Reader, n int) error {
  247. if c.rawConn.RawInput.Len() >= n {
  248. return nil
  249. }
  250. needs := n - c.rawConn.RawInput.Len()
  251. // There might be extra input waiting on the wire. Make a best effort
  252. // attempt to fetch it so that it can be used in (*Conn).Read to
  253. // "predict" closeNotify alerts.
  254. c.rawConn.RawInput.Grow(needs + bytes.MinRead)
  255. _, err := c.rawConn.RawInput.ReadFrom(&atLeastReader{r, int64(needs)})
  256. return err
  257. }
  258. func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err tls.RecordHeaderError) {
  259. err.Msg = msg
  260. err.Conn = conn
  261. copy(err.RecordHeader[:], c.rawConn.RawInput.Bytes())
  262. return err
  263. }