Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

crypto/tls: adjust dynamic record sizes to grow arithmetically The current code, introduced after Go 1.6 to improve latency on low-bandwidth connections, sends 1 kB packets until 1 MB has been sent, and then sends 16 kB packets (the maximum record size). Unfortunately this decreases throughput for 1-16 MB responses by 20% or so. Following discussion on #15713, change cutoff to 128 kB sent and also grow the size allowed for successive packets: 1 kB, 2 kB, 3 kB, ..., 15 kB, 16 kB. This fixes the throughput problems: the overhead is now closer to 2%. I hope this still helps with latency but I don't have a great way to test it. At the least, it's not worse than Go 1.6. Comparing MaxPacket vs DynamicPacket benchmarks: name maxpkt time/op dyn. time/op delta Throughput/1MB-8 5.07ms ± 7% 5.21ms ± 7% +2.73% (p=0.023 n=16+16) Throughput/2MB-8 15.7ms ±201% 8.4ms ± 5% ~ (p=0.604 n=20+16) Throughput/4MB-8 14.3ms ± 1% 14.5ms ± 1% +1.53% (p=0.000 n=16+16) Throughput/8MB-8 26.6ms ± 1% 26.8ms ± 1% +0.47% (p=0.003 n=19+18) Throughput/16MB-8 51.0ms ± 1% 51.3ms ± 1% +0.47% (p=0.000 n=20+20) Throughput/32MB-8 100ms ± 1% 100ms ± 1% +0.24% (p=0.033 n=20+20) Throughput/64MB-8 197ms ± 0% 198ms ± 0% +0.56% (p=0.000 n=18+7) The small MB runs are bimodal in both cases, probably GC pauses. But there's clearly no general slowdown anymore. Fixes #15713. Change-Id: I5fc44680ba71812d24baac142bceee0e23f2e382 Reviewed-on: https://go-review.googlesource.com/23487 Reviewed-by: Ian Lance Taylor <iant@golang.org>
před 8 roky
crypto/tls: adjust dynamic record sizes to grow arithmetically The current code, introduced after Go 1.6 to improve latency on low-bandwidth connections, sends 1 kB packets until 1 MB has been sent, and then sends 16 kB packets (the maximum record size). Unfortunately this decreases throughput for 1-16 MB responses by 20% or so. Following discussion on #15713, change cutoff to 128 kB sent and also grow the size allowed for successive packets: 1 kB, 2 kB, 3 kB, ..., 15 kB, 16 kB. This fixes the throughput problems: the overhead is now closer to 2%. I hope this still helps with latency but I don't have a great way to test it. At the least, it's not worse than Go 1.6. Comparing MaxPacket vs DynamicPacket benchmarks: name maxpkt time/op dyn. time/op delta Throughput/1MB-8 5.07ms ± 7% 5.21ms ± 7% +2.73% (p=0.023 n=16+16) Throughput/2MB-8 15.7ms ±201% 8.4ms ± 5% ~ (p=0.604 n=20+16) Throughput/4MB-8 14.3ms ± 1% 14.5ms ± 1% +1.53% (p=0.000 n=16+16) Throughput/8MB-8 26.6ms ± 1% 26.8ms ± 1% +0.47% (p=0.003 n=19+18) Throughput/16MB-8 51.0ms ± 1% 51.3ms ± 1% +0.47% (p=0.000 n=20+20) Throughput/32MB-8 100ms ± 1% 100ms ± 1% +0.24% (p=0.033 n=20+20) Throughput/64MB-8 197ms ± 0% 198ms ± 0% +0.56% (p=0.000 n=18+7) The small MB runs are bimodal in both cases, probably GC pauses. But there's clearly no general slowdown anymore. Fixes #15713. Change-Id: I5fc44680ba71812d24baac142bceee0e23f2e382 Reviewed-on: https://go-review.googlesource.com/23487 Reviewed-by: Ian Lance Taylor <iant@golang.org>
před 8 roky
crypto/tls: make Conn.Read return (n, io.EOF) when EOF is next in buffer Update #3514 An io.Reader is permitted to return either (n, nil) or (n, io.EOF) on EOF or other error. The tls package previously always returned (n, nil) for a read of size n if n bytes were available, not surfacing errors at the same time. Amazon's HTTPS frontends like to hang up on clients without sending the appropriate HTTP headers. (In their defense, they're allowed to hang up any time, but generally a server hangs up after a bit of inactivity, not immediately.) In any case, the Go HTTP client tries to re-use connections by looking at whether the response headers say to keep the connection open, and because the connection looks okay, under heavy load it's possible we'll reuse it immediately, writing the next request, just as the Transport's always-reading goroutine returns from tls.Conn.Read and sees (0, io.EOF). But because Amazon does send an AlertCloseNotify record before it hangs up on us, and the tls package does its own internal buffering (up to 1024 bytes) of pending data, we have the AlertCloseNotify in an unread buffer when our Conn.Read (to the HTTP Transport code) reads its final bit of data in the HTTP response body. This change makes that final Read return (n, io.EOF) when an AlertCloseNotify record is buffered right after, if we'd otherwise return (n, nil). A dependent change in the HTTP code then notes whether a client connection has seen an io.EOF and uses that as an additional signal to not reuse a HTTPS connection. With both changes, the majority of Amazon request failures go away. Without either one, 10-20 goroutines hitting the S3 API leads to such an error rate that empirically up to 5 retries are needed to complete an API call. LGTM=agl, rsc R=agl, rsc CC=golang-codereviews https://golang.org/cl/76400046
před 10 roky
crypto/tls: adjust dynamic record sizes to grow arithmetically The current code, introduced after Go 1.6 to improve latency on low-bandwidth connections, sends 1 kB packets until 1 MB has been sent, and then sends 16 kB packets (the maximum record size). Unfortunately this decreases throughput for 1-16 MB responses by 20% or so. Following discussion on #15713, change cutoff to 128 kB sent and also grow the size allowed for successive packets: 1 kB, 2 kB, 3 kB, ..., 15 kB, 16 kB. This fixes the throughput problems: the overhead is now closer to 2%. I hope this still helps with latency but I don't have a great way to test it. At the least, it's not worse than Go 1.6. Comparing MaxPacket vs DynamicPacket benchmarks: name maxpkt time/op dyn. time/op delta Throughput/1MB-8 5.07ms ± 7% 5.21ms ± 7% +2.73% (p=0.023 n=16+16) Throughput/2MB-8 15.7ms ±201% 8.4ms ± 5% ~ (p=0.604 n=20+16) Throughput/4MB-8 14.3ms ± 1% 14.5ms ± 1% +1.53% (p=0.000 n=16+16) Throughput/8MB-8 26.6ms ± 1% 26.8ms ± 1% +0.47% (p=0.003 n=19+18) Throughput/16MB-8 51.0ms ± 1% 51.3ms ± 1% +0.47% (p=0.000 n=20+20) Throughput/32MB-8 100ms ± 1% 100ms ± 1% +0.24% (p=0.033 n=20+20) Throughput/64MB-8 197ms ± 0% 198ms ± 0% +0.56% (p=0.000 n=18+7) The small MB runs are bimodal in both cases, probably GC pauses. But there's clearly no general slowdown anymore. Fixes #15713. Change-Id: I5fc44680ba71812d24baac142bceee0e23f2e382 Reviewed-on: https://go-review.googlesource.com/23487 Reviewed-by: Ian Lance Taylor <iant@golang.org>
před 8 roky
crypto/tls: adjust dynamic record sizes to grow arithmetically The current code, introduced after Go 1.6 to improve latency on low-bandwidth connections, sends 1 kB packets until 1 MB has been sent, and then sends 16 kB packets (the maximum record size). Unfortunately this decreases throughput for 1-16 MB responses by 20% or so. Following discussion on #15713, change cutoff to 128 kB sent and also grow the size allowed for successive packets: 1 kB, 2 kB, 3 kB, ..., 15 kB, 16 kB. This fixes the throughput problems: the overhead is now closer to 2%. I hope this still helps with latency but I don't have a great way to test it. At the least, it's not worse than Go 1.6. Comparing MaxPacket vs DynamicPacket benchmarks: name maxpkt time/op dyn. time/op delta Throughput/1MB-8 5.07ms ± 7% 5.21ms ± 7% +2.73% (p=0.023 n=16+16) Throughput/2MB-8 15.7ms ±201% 8.4ms ± 5% ~ (p=0.604 n=20+16) Throughput/4MB-8 14.3ms ± 1% 14.5ms ± 1% +1.53% (p=0.000 n=16+16) Throughput/8MB-8 26.6ms ± 1% 26.8ms ± 1% +0.47% (p=0.003 n=19+18) Throughput/16MB-8 51.0ms ± 1% 51.3ms ± 1% +0.47% (p=0.000 n=20+20) Throughput/32MB-8 100ms ± 1% 100ms ± 1% +0.24% (p=0.033 n=20+20) Throughput/64MB-8 197ms ± 0% 198ms ± 0% +0.56% (p=0.000 n=18+7) The small MB runs are bimodal in both cases, probably GC pauses. But there's clearly no general slowdown anymore. Fixes #15713. Change-Id: I5fc44680ba71812d24baac142bceee0e23f2e382 Reviewed-on: https://go-review.googlesource.com/23487 Reviewed-by: Ian Lance Taylor <iant@golang.org>
před 8 roky
crypto/tls: adjust dynamic record sizes to grow arithmetically The current code, introduced after Go 1.6 to improve latency on low-bandwidth connections, sends 1 kB packets until 1 MB has been sent, and then sends 16 kB packets (the maximum record size). Unfortunately this decreases throughput for 1-16 MB responses by 20% or so. Following discussion on #15713, change cutoff to 128 kB sent and also grow the size allowed for successive packets: 1 kB, 2 kB, 3 kB, ..., 15 kB, 16 kB. This fixes the throughput problems: the overhead is now closer to 2%. I hope this still helps with latency but I don't have a great way to test it. At the least, it's not worse than Go 1.6. Comparing MaxPacket vs DynamicPacket benchmarks: name maxpkt time/op dyn. time/op delta Throughput/1MB-8 5.07ms ± 7% 5.21ms ± 7% +2.73% (p=0.023 n=16+16) Throughput/2MB-8 15.7ms ±201% 8.4ms ± 5% ~ (p=0.604 n=20+16) Throughput/4MB-8 14.3ms ± 1% 14.5ms ± 1% +1.53% (p=0.000 n=16+16) Throughput/8MB-8 26.6ms ± 1% 26.8ms ± 1% +0.47% (p=0.003 n=19+18) Throughput/16MB-8 51.0ms ± 1% 51.3ms ± 1% +0.47% (p=0.000 n=20+20) Throughput/32MB-8 100ms ± 1% 100ms ± 1% +0.24% (p=0.033 n=20+20) Throughput/64MB-8 197ms ± 0% 198ms ± 0% +0.56% (p=0.000 n=18+7) The small MB runs are bimodal in both cases, probably GC pauses. But there's clearly no general slowdown anymore. Fixes #15713. Change-Id: I5fc44680ba71812d24baac142bceee0e23f2e382 Reviewed-on: https://go-review.googlesource.com/23487 Reviewed-by: Ian Lance Taylor <iant@golang.org>
před 8 roky
crypto/tls: make Conn.Read return (n, io.EOF) when EOF is next in buffer Update #3514 An io.Reader is permitted to return either (n, nil) or (n, io.EOF) on EOF or other error. The tls package previously always returned (n, nil) for a read of size n if n bytes were available, not surfacing errors at the same time. Amazon's HTTPS frontends like to hang up on clients without sending the appropriate HTTP headers. (In their defense, they're allowed to hang up any time, but generally a server hangs up after a bit of inactivity, not immediately.) In any case, the Go HTTP client tries to re-use connections by looking at whether the response headers say to keep the connection open, and because the connection looks okay, under heavy load it's possible we'll reuse it immediately, writing the next request, just as the Transport's always-reading goroutine returns from tls.Conn.Read and sees (0, io.EOF). But because Amazon does send an AlertCloseNotify record before it hangs up on us, and the tls package does its own internal buffering (up to 1024 bytes) of pending data, we have the AlertCloseNotify in an unread buffer when our Conn.Read (to the HTTP Transport code) reads its final bit of data in the HTTP response body. This change makes that final Read return (n, io.EOF) when an AlertCloseNotify record is buffered right after, if we'd otherwise return (n, nil). A dependent change in the HTTP code then notes whether a client connection has seen an io.EOF and uses that as an additional signal to not reuse a HTTPS connection. With both changes, the majority of Amazon request failures go away. Without either one, 10-20 goroutines hitting the S3 API leads to such an error rate that empirically up to 5 retries are needed to complete an API call. LGTM=agl, rsc R=agl, rsc CC=golang-codereviews https://golang.org/cl/76400046
před 10 roky
crypto/tls: make Conn.Read return (n, io.EOF) when EOF is next in buffer Update #3514 An io.Reader is permitted to return either (n, nil) or (n, io.EOF) on EOF or other error. The tls package previously always returned (n, nil) for a read of size n if n bytes were available, not surfacing errors at the same time. Amazon's HTTPS frontends like to hang up on clients without sending the appropriate HTTP headers. (In their defense, they're allowed to hang up any time, but generally a server hangs up after a bit of inactivity, not immediately.) In any case, the Go HTTP client tries to re-use connections by looking at whether the response headers say to keep the connection open, and because the connection looks okay, under heavy load it's possible we'll reuse it immediately, writing the next request, just as the Transport's always-reading goroutine returns from tls.Conn.Read and sees (0, io.EOF). But because Amazon does send an AlertCloseNotify record before it hangs up on us, and the tls package does its own internal buffering (up to 1024 bytes) of pending data, we have the AlertCloseNotify in an unread buffer when our Conn.Read (to the HTTP Transport code) reads its final bit of data in the HTTP response body. This change makes that final Read return (n, io.EOF) when an AlertCloseNotify record is buffered right after, if we'd otherwise return (n, nil). A dependent change in the HTTP code then notes whether a client connection has seen an io.EOF and uses that as an additional signal to not reuse a HTTPS connection. With both changes, the majority of Amazon request failures go away. Without either one, 10-20 goroutines hitting the S3 API leads to such an error rate that empirically up to 5 retries are needed to complete an API call. LGTM=agl, rsc R=agl, rsc CC=golang-codereviews https://golang.org/cl/76400046
před 10 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  1. // Copyright 2010 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. // TLS low level connection and record layer
  5. package tls
  6. import (
  7. "bytes"
  8. "crypto/cipher"
  9. "crypto/subtle"
  10. "crypto/x509"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net"
  15. "sync"
  16. "sync/atomic"
  17. "time"
  18. )
  19. // A Conn represents a secured connection.
  20. // It implements the net.Conn interface.
  21. type Conn struct {
  22. // constant
  23. conn net.Conn
  24. isClient bool
  25. phase handshakeStatus // protected by in.Mutex
  26. // handshakeConfirmed is an atomic bool for phase == handshakeConfirmed
  27. handshakeConfirmed int32
  28. // confirmMutex is held by any read operation before handshakeConfirmed
  29. confirmMutex sync.Mutex
  30. // constant after handshake; protected by handshakeMutex
  31. handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
  32. handshakeErr error // error resulting from handshake
  33. connID []byte // Random connection id
  34. clientHello []byte // ClientHello packet contents
  35. vers uint16 // TLS version
  36. haveVers bool // version has been negotiated
  37. config *Config // configuration passed to constructor
  38. // handshakeComplete is true if the connection reached application data
  39. // and it's equivalent to phase > handshakeRunning
  40. handshakeComplete bool
  41. // handshakes counts the number of handshakes performed on the
  42. // connection so far. If renegotiation is disabled then this is either
  43. // zero or one.
  44. handshakes int
  45. didResume bool // whether this connection was a session resumption
  46. cipherSuite uint16
  47. ocspResponse []byte // stapled OCSP response
  48. scts [][]byte // signed certificate timestamps from server
  49. peerCertificates []*x509.Certificate
  50. // verifiedChains contains the certificate chains that we built, as
  51. // opposed to the ones presented by the server.
  52. verifiedChains [][]*x509.Certificate
  53. // serverName contains the server name indicated by the client, if any.
  54. serverName string
  55. // secureRenegotiation is true if the server echoed the secure
  56. // renegotiation extension. (This is meaningless as a server because
  57. // renegotiation is not supported in that case.)
  58. secureRenegotiation bool
  59. // clientFinishedIsFirst is true if the client sent the first Finished
  60. // message during the most recent handshake. This is recorded because
  61. // the first transmitted Finished message is the tls-unique
  62. // channel-binding value.
  63. clientFinishedIsFirst bool
  64. // closeNotifyErr is any error from sending the alertCloseNotify record.
  65. closeNotifyErr error
  66. // closeNotifySent is true if the Conn attempted to send an
  67. // alertCloseNotify record.
  68. closeNotifySent bool
  69. // clientFinished and serverFinished contain the Finished message sent
  70. // by the client or server in the most recent handshake. This is
  71. // retained to support the renegotiation extension and tls-unique
  72. // channel-binding.
  73. clientFinished [12]byte
  74. serverFinished [12]byte
  75. clientProtocol string
  76. clientProtocolFallback bool
  77. // ticketMaxEarlyData is the maximum bytes of 0-RTT application data
  78. // that the client is allowed to send on the ticket it used.
  79. ticketMaxEarlyData int64
  80. // input/output
  81. in, out halfConn // in.Mutex < out.Mutex
  82. rawInput *block // raw input, right off the wire
  83. input *block // application data waiting to be read
  84. hand bytes.Buffer // handshake data waiting to be read
  85. buffering bool // whether records are buffered in sendBuf
  86. sendBuf []byte // a buffer of records waiting to be sent
  87. // bytesSent counts the bytes of application data sent.
  88. // packetsSent counts packets.
  89. bytesSent int64
  90. packetsSent int64
  91. // warnCount counts the number of consecutive warning alerts received
  92. // by Conn.readRecord. Protected by in.Mutex.
  93. warnCount int
  94. // activeCall is an atomic int32; the low bit is whether Close has
  95. // been called. the rest of the bits are the number of goroutines
  96. // in Conn.Write.
  97. activeCall int32
  98. // TLS 1.3 needs the server state until it reaches the Client Finished
  99. hs *serverHandshakeState
  100. // earlyDataBytes is the number of bytes of early data received so
  101. // far. Tracked to enforce max_early_data_size.
  102. // We don't keep track of rejected 0-RTT data since there's no need
  103. // to ever buffer it. in.Mutex.
  104. earlyDataBytes int64
  105. // binder is the value of the PSK binder that was validated to
  106. // accept the 0-RTT data. Exposed as ConnectionState.Unique0RTTToken.
  107. binder []byte
  108. tmp [16]byte
  109. }
  110. type handshakeStatus int
  111. const (
  112. handshakeRunning handshakeStatus = iota
  113. discardingEarlyData
  114. readingEarlyData
  115. waitingClientFinished
  116. readingClientFinished
  117. handshakeConfirmed
  118. )
  119. // Access to net.Conn methods.
  120. // Cannot just embed net.Conn because that would
  121. // export the struct field too.
  122. // LocalAddr returns the local network address.
  123. func (c *Conn) LocalAddr() net.Addr {
  124. return c.conn.LocalAddr()
  125. }
  126. // RemoteAddr returns the remote network address.
  127. func (c *Conn) RemoteAddr() net.Addr {
  128. return c.conn.RemoteAddr()
  129. }
  130. // SetDeadline sets the read and write deadlines associated with the connection.
  131. // A zero value for t means Read and Write will not time out.
  132. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  133. func (c *Conn) SetDeadline(t time.Time) error {
  134. return c.conn.SetDeadline(t)
  135. }
  136. // SetReadDeadline sets the read deadline on the underlying connection.
  137. // A zero value for t means Read will not time out.
  138. func (c *Conn) SetReadDeadline(t time.Time) error {
  139. return c.conn.SetReadDeadline(t)
  140. }
  141. // SetWriteDeadline sets the write deadline on the underlying connection.
  142. // A zero value for t means Write will not time out.
  143. // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
  144. func (c *Conn) SetWriteDeadline(t time.Time) error {
  145. return c.conn.SetWriteDeadline(t)
  146. }
  147. // A halfConn represents one direction of the record layer
  148. // connection, either sending or receiving.
  149. type halfConn struct {
  150. sync.Mutex
  151. err error // first permanent error
  152. version uint16 // protocol version
  153. cipher interface{} // cipher algorithm
  154. mac macFunction
  155. seq [8]byte // 64-bit sequence number
  156. bfree *block // list of free blocks
  157. additionalData [13]byte // to avoid allocs; interface method args escape
  158. nextCipher interface{} // next encryption state
  159. nextMac macFunction // next MAC algorithm
  160. // used to save allocating a new buffer for each MAC.
  161. inDigestBuf, outDigestBuf []byte
  162. traceErr func(error)
  163. }
  164. func (hc *halfConn) setErrorLocked(err error) error {
  165. hc.err = err
  166. if hc.traceErr != nil {
  167. hc.traceErr(err)
  168. }
  169. return err
  170. }
  171. // prepareCipherSpec sets the encryption and MAC states
  172. // that a subsequent changeCipherSpec will use.
  173. func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
  174. hc.version = version
  175. hc.nextCipher = cipher
  176. hc.nextMac = mac
  177. }
  178. // changeCipherSpec changes the encryption and MAC states
  179. // to the ones previously passed to prepareCipherSpec.
  180. func (hc *halfConn) changeCipherSpec() error {
  181. if hc.nextCipher == nil {
  182. return alertInternalError
  183. }
  184. hc.cipher = hc.nextCipher
  185. hc.mac = hc.nextMac
  186. hc.nextCipher = nil
  187. hc.nextMac = nil
  188. for i := range hc.seq {
  189. hc.seq[i] = 0
  190. }
  191. return nil
  192. }
  193. func (hc *halfConn) setCipher(version uint16, cipher interface{}) {
  194. hc.version = version
  195. hc.cipher = cipher
  196. for i := range hc.seq {
  197. hc.seq[i] = 0
  198. }
  199. }
  200. // incSeq increments the sequence number.
  201. func (hc *halfConn) incSeq() {
  202. for i := 7; i >= 0; i-- {
  203. hc.seq[i]++
  204. if hc.seq[i] != 0 {
  205. return
  206. }
  207. }
  208. // Not allowed to let sequence number wrap.
  209. // Instead, must renegotiate before it does.
  210. // Not likely enough to bother.
  211. panic("TLS: sequence number wraparound")
  212. }
  213. // extractPadding returns, in constant time, the length of the padding to remove
  214. // from the end of payload. It also returns a byte which is equal to 255 if the
  215. // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
  216. func extractPadding(payload []byte) (toRemove int, good byte) {
  217. if len(payload) < 1 {
  218. return 0, 0
  219. }
  220. paddingLen := payload[len(payload)-1]
  221. t := uint(len(payload)-1) - uint(paddingLen)
  222. // if len(payload) >= (paddingLen - 1) then the MSB of t is zero
  223. good = byte(int32(^t) >> 31)
  224. // The maximum possible padding length plus the actual length field
  225. toCheck := 256
  226. // The length of the padded data is public, so we can use an if here
  227. if toCheck > len(payload) {
  228. toCheck = len(payload)
  229. }
  230. for i := 0; i < toCheck; i++ {
  231. t := uint(paddingLen) - uint(i)
  232. // if i <= paddingLen then the MSB of t is zero
  233. mask := byte(int32(^t) >> 31)
  234. b := payload[len(payload)-1-i]
  235. good &^= mask&paddingLen ^ mask&b
  236. }
  237. // We AND together the bits of good and replicate the result across
  238. // all the bits.
  239. good &= good << 4
  240. good &= good << 2
  241. good &= good << 1
  242. good = uint8(int8(good) >> 7)
  243. toRemove = int(paddingLen) + 1
  244. return
  245. }
  246. // extractPaddingSSL30 is a replacement for extractPadding in the case that the
  247. // protocol version is SSLv3. In this version, the contents of the padding
  248. // are random and cannot be checked.
  249. func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
  250. if len(payload) < 1 {
  251. return 0, 0
  252. }
  253. paddingLen := int(payload[len(payload)-1]) + 1
  254. if paddingLen > len(payload) {
  255. return 0, 0
  256. }
  257. return paddingLen, 255
  258. }
  259. func roundUp(a, b int) int {
  260. return a + (b-a%b)%b
  261. }
  262. // cbcMode is an interface for block ciphers using cipher block chaining.
  263. type cbcMode interface {
  264. cipher.BlockMode
  265. SetIV([]byte)
  266. }
  267. // decrypt checks and strips the mac and decrypts the data in b. Returns a
  268. // success boolean, the number of bytes to skip from the start of the record in
  269. // order to get the application payload, and an optional alert value.
  270. func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
  271. // pull out payload
  272. payload := b.data[recordHeaderLen:]
  273. macSize := 0
  274. if hc.mac != nil {
  275. macSize = hc.mac.Size()
  276. }
  277. paddingGood := byte(255)
  278. paddingLen := 0
  279. explicitIVLen := 0
  280. // decrypt
  281. if hc.cipher != nil {
  282. switch c := hc.cipher.(type) {
  283. case cipher.Stream:
  284. c.XORKeyStream(payload, payload)
  285. case aead:
  286. explicitIVLen = c.explicitNonceLen()
  287. if len(payload) < explicitIVLen {
  288. return false, 0, alertBadRecordMAC
  289. }
  290. nonce := payload[:explicitIVLen]
  291. payload = payload[explicitIVLen:]
  292. if len(nonce) == 0 {
  293. nonce = hc.seq[:]
  294. }
  295. var additionalData []byte
  296. if hc.version < VersionTLS13 {
  297. copy(hc.additionalData[:], hc.seq[:])
  298. copy(hc.additionalData[8:], b.data[:3])
  299. n := len(payload) - c.Overhead()
  300. hc.additionalData[11] = byte(n >> 8)
  301. hc.additionalData[12] = byte(n)
  302. additionalData = hc.additionalData[:]
  303. }
  304. var err error
  305. payload, err = c.Open(payload[:0], nonce, payload, additionalData)
  306. if err != nil {
  307. return false, 0, alertBadRecordMAC
  308. }
  309. b.resize(recordHeaderLen + explicitIVLen + len(payload))
  310. case cbcMode:
  311. blockSize := c.BlockSize()
  312. if hc.version >= VersionTLS11 {
  313. explicitIVLen = blockSize
  314. }
  315. if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
  316. return false, 0, alertBadRecordMAC
  317. }
  318. if explicitIVLen > 0 {
  319. c.SetIV(payload[:explicitIVLen])
  320. payload = payload[explicitIVLen:]
  321. }
  322. c.CryptBlocks(payload, payload)
  323. if hc.version == VersionSSL30 {
  324. paddingLen, paddingGood = extractPaddingSSL30(payload)
  325. } else {
  326. paddingLen, paddingGood = extractPadding(payload)
  327. // To protect against CBC padding oracles like Lucky13, the data
  328. // past paddingLen (which is secret) is passed to the MAC
  329. // function as extra data, to be fed into the HMAC after
  330. // computing the digest. This makes the MAC constant time as
  331. // long as the digest computation is constant time and does not
  332. // affect the subsequent write.
  333. }
  334. default:
  335. panic("unknown cipher type")
  336. }
  337. }
  338. // check, strip mac
  339. if hc.mac != nil {
  340. if len(payload) < macSize {
  341. return false, 0, alertBadRecordMAC
  342. }
  343. // strip mac off payload, b.data
  344. n := len(payload) - macSize - paddingLen
  345. n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
  346. b.data[3] = byte(n >> 8)
  347. b.data[4] = byte(n)
  348. remoteMAC := payload[n : n+macSize]
  349. localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n], payload[n+macSize:])
  350. if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
  351. return false, 0, alertBadRecordMAC
  352. }
  353. hc.inDigestBuf = localMAC
  354. b.resize(recordHeaderLen + explicitIVLen + n)
  355. }
  356. hc.incSeq()
  357. return true, recordHeaderLen + explicitIVLen, 0
  358. }
  359. // padToBlockSize calculates the needed padding block, if any, for a payload.
  360. // On exit, prefix aliases payload and extends to the end of the last full
  361. // block of payload. finalBlock is a fresh slice which contains the contents of
  362. // any suffix of payload as well as the needed padding to make finalBlock a
  363. // full block.
  364. func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
  365. overrun := len(payload) % blockSize
  366. paddingLen := blockSize - overrun
  367. prefix = payload[:len(payload)-overrun]
  368. finalBlock = make([]byte, blockSize)
  369. copy(finalBlock, payload[len(payload)-overrun:])
  370. for i := overrun; i < blockSize; i++ {
  371. finalBlock[i] = byte(paddingLen - 1)
  372. }
  373. return
  374. }
  375. // encrypt encrypts and macs the data in b.
  376. func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
  377. // mac
  378. if hc.mac != nil {
  379. mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:], nil)
  380. n := len(b.data)
  381. b.resize(n + len(mac))
  382. copy(b.data[n:], mac)
  383. hc.outDigestBuf = mac
  384. }
  385. payload := b.data[recordHeaderLen:]
  386. // encrypt
  387. if hc.cipher != nil {
  388. switch c := hc.cipher.(type) {
  389. case cipher.Stream:
  390. c.XORKeyStream(payload, payload)
  391. case aead:
  392. payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
  393. overhead := c.Overhead()
  394. if hc.version >= VersionTLS13 {
  395. overhead++
  396. }
  397. b.resize(len(b.data) + overhead)
  398. nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  399. if len(nonce) == 0 {
  400. nonce = hc.seq[:]
  401. }
  402. payload = b.data[recordHeaderLen+explicitIVLen:]
  403. payload = payload[:payloadLen]
  404. var additionalData []byte
  405. if hc.version < VersionTLS13 {
  406. copy(hc.additionalData[:], hc.seq[:])
  407. copy(hc.additionalData[8:], b.data[:3])
  408. hc.additionalData[11] = byte(payloadLen >> 8)
  409. hc.additionalData[12] = byte(payloadLen)
  410. additionalData = hc.additionalData[:]
  411. }
  412. if hc.version >= VersionTLS13 {
  413. // opaque type
  414. payload = payload[:len(payload)+1]
  415. payload[len(payload)-1] = b.data[0]
  416. b.data[0] = byte(recordTypeApplicationData)
  417. }
  418. c.Seal(payload[:0], nonce, payload, additionalData)
  419. case cbcMode:
  420. blockSize := c.BlockSize()
  421. if explicitIVLen > 0 {
  422. c.SetIV(payload[:explicitIVLen])
  423. payload = payload[explicitIVLen:]
  424. }
  425. prefix, finalBlock := padToBlockSize(payload, blockSize)
  426. b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
  427. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
  428. c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
  429. default:
  430. panic("unknown cipher type")
  431. }
  432. }
  433. // update length to include MAC and any block padding needed.
  434. n := len(b.data) - recordHeaderLen
  435. b.data[3] = byte(n >> 8)
  436. b.data[4] = byte(n)
  437. hc.incSeq()
  438. return true, 0
  439. }
  440. // A block is a simple data buffer.
  441. type block struct {
  442. data []byte
  443. off int // index for Read
  444. link *block
  445. }
  446. // resize resizes block to be n bytes, growing if necessary.
  447. func (b *block) resize(n int) {
  448. if n > cap(b.data) {
  449. b.reserve(n)
  450. }
  451. b.data = b.data[0:n]
  452. }
  453. // reserve makes sure that block contains a capacity of at least n bytes.
  454. func (b *block) reserve(n int) {
  455. if cap(b.data) >= n {
  456. return
  457. }
  458. m := cap(b.data)
  459. if m == 0 {
  460. m = 1024
  461. }
  462. for m < n {
  463. m *= 2
  464. }
  465. data := make([]byte, len(b.data), m)
  466. copy(data, b.data)
  467. b.data = data
  468. }
  469. // readFromUntil reads from r into b until b contains at least n bytes
  470. // or else returns an error.
  471. func (b *block) readFromUntil(r io.Reader, n int) error {
  472. // quick case
  473. if len(b.data) >= n {
  474. return nil
  475. }
  476. // read until have enough.
  477. b.reserve(n)
  478. for {
  479. m, err := r.Read(b.data[len(b.data):cap(b.data)])
  480. b.data = b.data[0 : len(b.data)+m]
  481. if len(b.data) >= n {
  482. // TODO(bradfitz,agl): slightly suspicious
  483. // that we're throwing away r.Read's err here.
  484. break
  485. }
  486. if err != nil {
  487. return err
  488. }
  489. }
  490. return nil
  491. }
  492. func (b *block) Read(p []byte) (n int, err error) {
  493. n = copy(p, b.data[b.off:])
  494. b.off += n
  495. if b.off >= len(b.data) {
  496. err = io.EOF
  497. }
  498. return
  499. }
  500. // newBlock allocates a new block, from hc's free list if possible.
  501. func (hc *halfConn) newBlock() *block {
  502. b := hc.bfree
  503. if b == nil {
  504. return new(block)
  505. }
  506. hc.bfree = b.link
  507. b.link = nil
  508. b.resize(0)
  509. return b
  510. }
  511. // freeBlock returns a block to hc's free list.
  512. // The protocol is such that each side only has a block or two on
  513. // its free list at a time, so there's no need to worry about
  514. // trimming the list, etc.
  515. func (hc *halfConn) freeBlock(b *block) {
  516. b.link = hc.bfree
  517. hc.bfree = b
  518. }
  519. // splitBlock splits a block after the first n bytes,
  520. // returning a block with those n bytes and a
  521. // block with the remainder. the latter may be nil.
  522. func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
  523. if len(b.data) <= n {
  524. return b, nil
  525. }
  526. bb := hc.newBlock()
  527. bb.resize(len(b.data) - n)
  528. copy(bb.data, b.data[n:])
  529. b.data = b.data[0:n]
  530. return b, bb
  531. }
  532. // RecordHeaderError results when a TLS record header is invalid.
  533. type RecordHeaderError struct {
  534. // Msg contains a human readable string that describes the error.
  535. Msg string
  536. // RecordHeader contains the five bytes of TLS record header that
  537. // triggered the error.
  538. RecordHeader [5]byte
  539. }
  540. func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
  541. func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
  542. err.Msg = msg
  543. copy(err.RecordHeader[:], c.rawInput.data)
  544. return err
  545. }
  546. // readRecord reads the next TLS record from the connection
  547. // and updates the record layer state.
  548. // c.in.Mutex <= L; c.input == nil.
  549. // c.input can still be nil after a call, retry if so.
  550. func (c *Conn) readRecord(want recordType) error {
  551. // Caller must be in sync with connection:
  552. // handshake data if handshake not yet completed,
  553. // else application data.
  554. switch want {
  555. default:
  556. c.sendAlert(alertInternalError)
  557. return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
  558. case recordTypeHandshake, recordTypeChangeCipherSpec:
  559. if c.phase != handshakeRunning && c.phase != readingClientFinished {
  560. c.sendAlert(alertInternalError)
  561. return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
  562. }
  563. case recordTypeApplicationData:
  564. if c.phase == handshakeRunning || c.phase == readingClientFinished {
  565. c.sendAlert(alertInternalError)
  566. return c.in.setErrorLocked(errors.New("tls: application data record requested while in handshake"))
  567. }
  568. }
  569. Again:
  570. if c.rawInput == nil {
  571. c.rawInput = c.in.newBlock()
  572. }
  573. b := c.rawInput
  574. // Read header, payload.
  575. if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
  576. // RFC suggests that EOF without an alertCloseNotify is
  577. // an error, but popular web sites seem to do this,
  578. // so we can't make it an error.
  579. // if err == io.EOF {
  580. // err = io.ErrUnexpectedEOF
  581. // }
  582. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  583. c.in.setErrorLocked(err)
  584. }
  585. return err
  586. }
  587. typ := recordType(b.data[0])
  588. // No valid TLS record has a type of 0x80, however SSLv2 handshakes
  589. // start with a uint16 length where the MSB is set and the first record
  590. // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
  591. // an SSLv2 client.
  592. if want == recordTypeHandshake && typ == 0x80 {
  593. c.sendAlert(alertProtocolVersion)
  594. return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
  595. }
  596. vers := uint16(b.data[1])<<8 | uint16(b.data[2])
  597. n := int(b.data[3])<<8 | int(b.data[4])
  598. if n > maxCiphertext {
  599. c.sendAlert(alertRecordOverflow)
  600. msg := fmt.Sprintf("oversized record received with length %d", n)
  601. return c.in.setErrorLocked(c.newRecordHeaderError(msg))
  602. }
  603. if !c.haveVers {
  604. // First message, be extra suspicious: this might not be a TLS
  605. // client. Bail out before reading a full 'body', if possible.
  606. // The current max version is 3.3 so if the version is >= 16.0,
  607. // it's probably not real.
  608. if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
  609. c.sendAlert(alertUnexpectedMessage)
  610. return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
  611. }
  612. }
  613. if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
  614. if err == io.EOF {
  615. err = io.ErrUnexpectedEOF
  616. }
  617. if e, ok := err.(net.Error); !ok || !e.Temporary() {
  618. c.in.setErrorLocked(err)
  619. }
  620. return err
  621. }
  622. // Process message.
  623. b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
  624. // TLS 1.3 middlebox compatibility: skip over unencrypted CCS.
  625. if c.vers >= VersionTLS13 && typ == recordTypeChangeCipherSpec && c.phase != handshakeConfirmed {
  626. if len(b.data) != 6 || b.data[5] != 1 {
  627. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  628. }
  629. c.in.freeBlock(b)
  630. return c.in.err
  631. }
  632. peekedAlert := peekAlert(b) // peek at a possible alert before decryption
  633. ok, off, alertValue := c.in.decrypt(b)
  634. switch {
  635. case !ok && c.phase == discardingEarlyData:
  636. // If the client said that it's sending early data and we did not
  637. // accept it, we are expected to fail decryption.
  638. c.in.freeBlock(b)
  639. return nil
  640. case ok && c.phase == discardingEarlyData:
  641. c.phase = waitingClientFinished
  642. case !ok:
  643. c.in.traceErr, c.out.traceErr = nil, nil // not that interesting
  644. c.in.freeBlock(b)
  645. err := c.sendAlert(alertValue)
  646. // If decryption failed because the message is an unencrypted
  647. // alert, return a more meaningful error message
  648. if alertValue == alertBadRecordMAC && peekedAlert != nil {
  649. err = peekedAlert
  650. }
  651. return c.in.setErrorLocked(err)
  652. }
  653. b.off = off
  654. data := b.data[b.off:]
  655. if (c.vers < VersionTLS13 && len(data) > maxPlaintext) || len(data) > maxPlaintext+1 {
  656. c.in.freeBlock(b)
  657. return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow))
  658. }
  659. // After checking the plaintext length, remove 1.3 padding and
  660. // extract the real content type.
  661. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.4.
  662. if c.vers >= VersionTLS13 {
  663. i := len(data) - 1
  664. for i >= 0 {
  665. if data[i] != 0 {
  666. break
  667. }
  668. i--
  669. }
  670. if i < 0 {
  671. c.in.freeBlock(b)
  672. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  673. }
  674. typ = recordType(data[i])
  675. data = data[:i]
  676. b.resize(b.off + i) // shrinks, guaranteed not to reallocate
  677. }
  678. if typ != recordTypeAlert && len(data) > 0 {
  679. // this is a valid non-alert message: reset the count of alerts
  680. c.warnCount = 0
  681. }
  682. switch typ {
  683. default:
  684. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  685. case recordTypeAlert:
  686. if len(data) != 2 {
  687. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  688. break
  689. }
  690. if alert(data[1]) == alertCloseNotify {
  691. c.in.setErrorLocked(io.EOF)
  692. break
  693. }
  694. switch data[0] {
  695. case alertLevelWarning:
  696. // drop on the floor
  697. c.in.freeBlock(b)
  698. c.warnCount++
  699. if c.warnCount > maxWarnAlertCount {
  700. c.sendAlert(alertUnexpectedMessage)
  701. return c.in.setErrorLocked(errors.New("tls: too many warn alerts"))
  702. }
  703. goto Again
  704. case alertLevelError:
  705. c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
  706. default:
  707. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  708. }
  709. case recordTypeChangeCipherSpec:
  710. if typ != want || len(data) != 1 || data[0] != 1 || c.vers >= VersionTLS13 {
  711. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  712. break
  713. }
  714. // Handshake messages are not allowed to fragment across the CCS
  715. if c.hand.Len() > 0 {
  716. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  717. break
  718. }
  719. // Handshake messages are not allowed to fragment across the CCS
  720. if c.hand.Len() > 0 {
  721. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  722. break
  723. }
  724. err := c.in.changeCipherSpec()
  725. if err != nil {
  726. c.in.setErrorLocked(c.sendAlert(err.(alert)))
  727. }
  728. case recordTypeApplicationData:
  729. if typ != want || c.phase == waitingClientFinished {
  730. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  731. break
  732. }
  733. if c.phase == readingEarlyData {
  734. c.earlyDataBytes += int64(len(b.data) - b.off)
  735. if c.earlyDataBytes > c.ticketMaxEarlyData {
  736. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  737. }
  738. }
  739. c.input = b
  740. b = nil
  741. case recordTypeHandshake:
  742. // TODO(rsc): Should at least pick off connection close.
  743. // If early data was being read, a Finished message is expected
  744. // instead of (early) application data. Other post-handshake
  745. // messages include HelloRequest and NewSessionTicket.
  746. if typ != want && want != recordTypeApplicationData {
  747. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  748. }
  749. c.hand.Write(data)
  750. }
  751. if b != nil {
  752. c.in.freeBlock(b)
  753. }
  754. return c.in.err
  755. }
  756. // peekAlert looks at a message to spot an unencrypted alert. It must be
  757. // called before decryption to avoid a side channel, and its result must
  758. // only be used if decryption fails, to avoid false positives.
  759. func peekAlert(b *block) error {
  760. if len(b.data) < 7 {
  761. return nil
  762. }
  763. if recordType(b.data[0]) != recordTypeAlert {
  764. return nil
  765. }
  766. return &net.OpError{Op: "remote error", Err: alert(b.data[6])}
  767. }
  768. // sendAlert sends a TLS alert message.
  769. // c.out.Mutex <= L.
  770. func (c *Conn) sendAlertLocked(err alert) error {
  771. switch err {
  772. case alertNoRenegotiation, alertCloseNotify:
  773. c.tmp[0] = alertLevelWarning
  774. default:
  775. c.tmp[0] = alertLevelError
  776. }
  777. c.tmp[1] = byte(err)
  778. _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
  779. if err == alertCloseNotify {
  780. // closeNotify is a special case in that it isn't an error.
  781. return writeErr
  782. }
  783. return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
  784. }
  785. // sendAlert sends a TLS alert message.
  786. // L < c.out.Mutex.
  787. func (c *Conn) sendAlert(err alert) error {
  788. c.out.Lock()
  789. defer c.out.Unlock()
  790. return c.sendAlertLocked(err)
  791. }
  792. const (
  793. // tcpMSSEstimate is a conservative estimate of the TCP maximum segment
  794. // size (MSS). A constant is used, rather than querying the kernel for
  795. // the actual MSS, to avoid complexity. The value here is the IPv6
  796. // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
  797. // bytes) and a TCP header with timestamps (32 bytes).
  798. tcpMSSEstimate = 1208
  799. // recordSizeBoostThreshold is the number of bytes of application data
  800. // sent after which the TLS record size will be increased to the
  801. // maximum.
  802. recordSizeBoostThreshold = 128 * 1024
  803. )
  804. // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
  805. // next application data record. There is the following trade-off:
  806. //
  807. // - For latency-sensitive applications, such as web browsing, each TLS
  808. // record should fit in one TCP segment.
  809. // - For throughput-sensitive applications, such as large file transfers,
  810. // larger TLS records better amortize framing and encryption overheads.
  811. //
  812. // A simple heuristic that works well in practice is to use small records for
  813. // the first 1MB of data, then use larger records for subsequent data, and
  814. // reset back to smaller records after the connection becomes idle. See "High
  815. // Performance Web Networking", Chapter 4, or:
  816. // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
  817. //
  818. // In the interests of simplicity and determinism, this code does not attempt
  819. // to reset the record size once the connection is idle, however.
  820. //
  821. // c.out.Mutex <= L.
  822. func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
  823. if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
  824. return maxPlaintext
  825. }
  826. if c.bytesSent >= recordSizeBoostThreshold {
  827. return maxPlaintext
  828. }
  829. // Subtract TLS overheads to get the maximum payload size.
  830. macSize := 0
  831. if c.out.mac != nil {
  832. macSize = c.out.mac.Size()
  833. }
  834. payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
  835. if c.out.cipher != nil {
  836. switch ciph := c.out.cipher.(type) {
  837. case cipher.Stream:
  838. payloadBytes -= macSize
  839. case cipher.AEAD:
  840. payloadBytes -= ciph.Overhead()
  841. if c.vers >= VersionTLS13 {
  842. payloadBytes -= 1 // ContentType
  843. }
  844. case cbcMode:
  845. blockSize := ciph.BlockSize()
  846. // The payload must fit in a multiple of blockSize, with
  847. // room for at least one padding byte.
  848. payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
  849. // The MAC is appended before padding so affects the
  850. // payload size directly.
  851. payloadBytes -= macSize
  852. default:
  853. panic("unknown cipher type")
  854. }
  855. }
  856. // Allow packet growth in arithmetic progression up to max.
  857. pkt := c.packetsSent
  858. c.packetsSent++
  859. if pkt > 1000 {
  860. return maxPlaintext // avoid overflow in multiply below
  861. }
  862. n := payloadBytes * int(pkt+1)
  863. if n > maxPlaintext {
  864. n = maxPlaintext
  865. }
  866. return n
  867. }
  868. // c.out.Mutex <= L.
  869. func (c *Conn) write(data []byte) (int, error) {
  870. if c.buffering {
  871. c.sendBuf = append(c.sendBuf, data...)
  872. return len(data), nil
  873. }
  874. n, err := c.conn.Write(data)
  875. c.bytesSent += int64(n)
  876. return n, err
  877. }
  878. func (c *Conn) flush() (int, error) {
  879. if len(c.sendBuf) == 0 {
  880. return 0, nil
  881. }
  882. n, err := c.conn.Write(c.sendBuf)
  883. c.bytesSent += int64(n)
  884. c.sendBuf = nil
  885. c.buffering = false
  886. return n, err
  887. }
  888. // writeRecordLocked writes a TLS record with the given type and payload to the
  889. // connection and updates the record layer state.
  890. // c.out.Mutex <= L.
  891. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
  892. b := c.out.newBlock()
  893. defer c.out.freeBlock(b)
  894. var n int
  895. for len(data) > 0 {
  896. explicitIVLen := 0
  897. explicitIVIsSeq := false
  898. var cbc cbcMode
  899. if c.out.version >= VersionTLS11 {
  900. var ok bool
  901. if cbc, ok = c.out.cipher.(cbcMode); ok {
  902. explicitIVLen = cbc.BlockSize()
  903. }
  904. }
  905. if explicitIVLen == 0 {
  906. if c, ok := c.out.cipher.(aead); ok {
  907. explicitIVLen = c.explicitNonceLen()
  908. // The AES-GCM construction in TLS has an
  909. // explicit nonce so that the nonce can be
  910. // random. However, the nonce is only 8 bytes
  911. // which is too small for a secure, random
  912. // nonce. Therefore we use the sequence number
  913. // as the nonce.
  914. explicitIVIsSeq = explicitIVLen > 0
  915. }
  916. }
  917. m := len(data)
  918. if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
  919. m = maxPayload
  920. }
  921. b.resize(recordHeaderLen + explicitIVLen + m)
  922. b.data[0] = byte(typ)
  923. vers := c.vers
  924. if vers == 0 {
  925. // Some TLS servers fail if the record version is
  926. // greater than TLS 1.0 for the initial ClientHello.
  927. vers = VersionTLS10
  928. }
  929. if c.vers >= VersionTLS13 {
  930. // TLS 1.3 froze the record layer version at { 3, 1 }.
  931. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-5.1.
  932. // But for draft 22, this was changed to { 3, 3 }.
  933. vers = VersionTLS12
  934. }
  935. b.data[1] = byte(vers >> 8)
  936. b.data[2] = byte(vers)
  937. b.data[3] = byte(m >> 8)
  938. b.data[4] = byte(m)
  939. if explicitIVLen > 0 {
  940. explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
  941. if explicitIVIsSeq {
  942. copy(explicitIV, c.out.seq[:])
  943. } else {
  944. if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
  945. return n, err
  946. }
  947. }
  948. }
  949. copy(b.data[recordHeaderLen+explicitIVLen:], data)
  950. c.out.encrypt(b, explicitIVLen)
  951. if _, err := c.write(b.data); err != nil {
  952. return n, err
  953. }
  954. n += m
  955. data = data[m:]
  956. }
  957. if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 {
  958. if err := c.out.changeCipherSpec(); err != nil {
  959. return n, c.sendAlertLocked(err.(alert))
  960. }
  961. }
  962. return n, nil
  963. }
  964. // writeRecord writes a TLS record with the given type and payload to the
  965. // connection and updates the record layer state.
  966. // L < c.out.Mutex.
  967. func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
  968. c.out.Lock()
  969. defer c.out.Unlock()
  970. return c.writeRecordLocked(typ, data)
  971. }
  972. // readHandshake reads the next handshake message from
  973. // the record layer.
  974. // c.in.Mutex < L; c.out.Mutex < L.
  975. func (c *Conn) readHandshake() (interface{}, error) {
  976. for c.hand.Len() < 4 {
  977. if err := c.in.err; err != nil {
  978. return nil, err
  979. }
  980. if err := c.readRecord(recordTypeHandshake); err != nil {
  981. return nil, err
  982. }
  983. }
  984. data := c.hand.Bytes()
  985. n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  986. if n > maxHandshake {
  987. c.sendAlertLocked(alertInternalError)
  988. return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
  989. }
  990. for c.hand.Len() < 4+n {
  991. if err := c.in.err; err != nil {
  992. return nil, err
  993. }
  994. if err := c.readRecord(recordTypeHandshake); err != nil {
  995. return nil, err
  996. }
  997. }
  998. data = c.hand.Next(4 + n)
  999. var m handshakeMessage
  1000. switch data[0] {
  1001. case typeHelloRequest:
  1002. m = new(helloRequestMsg)
  1003. case typeClientHello:
  1004. m = new(clientHelloMsg)
  1005. case typeServerHello:
  1006. m = new(serverHelloMsg)
  1007. case typeEncryptedExtensions:
  1008. m = new(encryptedExtensionsMsg)
  1009. case typeNewSessionTicket:
  1010. if c.vers >= VersionTLS13 {
  1011. m = new(newSessionTicketMsg13)
  1012. } else {
  1013. m = new(newSessionTicketMsg)
  1014. }
  1015. case typeEndOfEarlyData:
  1016. m = new(endOfEarlyDataMsg)
  1017. case typeCertificate:
  1018. if c.vers >= VersionTLS13 {
  1019. m = new(certificateMsg13)
  1020. } else {
  1021. m = new(certificateMsg)
  1022. }
  1023. case typeCertificateRequest:
  1024. if c.vers >= VersionTLS13 {
  1025. m = new(certificateRequestMsg13)
  1026. } else {
  1027. m = &certificateRequestMsg{
  1028. hasSignatureAndHash: c.vers >= VersionTLS12,
  1029. }
  1030. }
  1031. case typeCertificateStatus:
  1032. m = new(certificateStatusMsg)
  1033. case typeServerKeyExchange:
  1034. m = new(serverKeyExchangeMsg)
  1035. case typeServerHelloDone:
  1036. m = new(serverHelloDoneMsg)
  1037. case typeClientKeyExchange:
  1038. m = new(clientKeyExchangeMsg)
  1039. case typeCertificateVerify:
  1040. m = &certificateVerifyMsg{
  1041. hasSignatureAndHash: c.vers >= VersionTLS12,
  1042. }
  1043. case typeNextProtocol:
  1044. m = new(nextProtoMsg)
  1045. case typeFinished:
  1046. m = new(finishedMsg)
  1047. default:
  1048. return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  1049. }
  1050. // The handshake message unmarshalers
  1051. // expect to be able to keep references to data,
  1052. // so pass in a fresh copy that won't be overwritten.
  1053. data = append([]byte(nil), data...)
  1054. if unmarshalAlert := m.unmarshal(data); unmarshalAlert != alertSuccess {
  1055. return nil, c.in.setErrorLocked(c.sendAlert(unmarshalAlert))
  1056. }
  1057. return m, nil
  1058. }
  1059. var (
  1060. errClosed = errors.New("tls: use of closed connection")
  1061. errShutdown = errors.New("tls: protocol is shutdown")
  1062. )
  1063. // Write writes data to the connection.
  1064. func (c *Conn) Write(b []byte) (int, error) {
  1065. // interlock with Close below
  1066. for {
  1067. x := atomic.LoadInt32(&c.activeCall)
  1068. if x&1 != 0 {
  1069. return 0, errClosed
  1070. }
  1071. if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
  1072. defer atomic.AddInt32(&c.activeCall, -2)
  1073. break
  1074. }
  1075. }
  1076. if err := c.Handshake(); err != nil {
  1077. return 0, err
  1078. }
  1079. c.out.Lock()
  1080. defer c.out.Unlock()
  1081. if err := c.out.err; err != nil {
  1082. return 0, err
  1083. }
  1084. if !c.handshakeComplete {
  1085. return 0, alertInternalError
  1086. }
  1087. if c.closeNotifySent {
  1088. return 0, errShutdown
  1089. }
  1090. // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
  1091. // attack when using block mode ciphers due to predictable IVs.
  1092. // This can be prevented by splitting each Application Data
  1093. // record into two records, effectively randomizing the IV.
  1094. //
  1095. // http://www.openssl.org/~bodo/tls-cbc.txt
  1096. // https://bugzilla.mozilla.org/show_bug.cgi?id=665814
  1097. // http://www.imperialviolet.org/2012/01/15/beastfollowup.html
  1098. var m int
  1099. if len(b) > 1 && c.vers <= VersionTLS10 {
  1100. if _, ok := c.out.cipher.(cipher.BlockMode); ok {
  1101. n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
  1102. if err != nil {
  1103. return n, c.out.setErrorLocked(err)
  1104. }
  1105. m, b = 1, b[1:]
  1106. }
  1107. }
  1108. n, err := c.writeRecordLocked(recordTypeApplicationData, b)
  1109. return n + m, c.out.setErrorLocked(err)
  1110. }
  1111. // Process Handshake messages after the handshake has completed.
  1112. // c.in.Mutex <= L
  1113. func (c *Conn) handlePostHandshake() error {
  1114. msg, err := c.readHandshake()
  1115. if err != nil {
  1116. return err
  1117. }
  1118. switch hm := msg.(type) {
  1119. case *helloRequestMsg:
  1120. return c.handleRenegotiation(hm)
  1121. case *newSessionTicketMsg13:
  1122. if !c.isClient {
  1123. c.sendAlert(alertUnexpectedMessage)
  1124. return alertUnexpectedMessage
  1125. }
  1126. return nil // TODO implement session tickets
  1127. default:
  1128. c.sendAlert(alertUnexpectedMessage)
  1129. return alertUnexpectedMessage
  1130. }
  1131. }
  1132. // handleRenegotiation processes a HelloRequest handshake message.
  1133. // c.in.Mutex <= L
  1134. func (c *Conn) handleRenegotiation(*helloRequestMsg) error {
  1135. if !c.isClient {
  1136. return c.sendAlert(alertNoRenegotiation)
  1137. }
  1138. if c.vers >= VersionTLS13 {
  1139. return c.sendAlert(alertNoRenegotiation)
  1140. }
  1141. switch c.config.Renegotiation {
  1142. case RenegotiateNever:
  1143. return c.sendAlert(alertNoRenegotiation)
  1144. case RenegotiateOnceAsClient:
  1145. if c.handshakes > 1 {
  1146. return c.sendAlert(alertNoRenegotiation)
  1147. }
  1148. case RenegotiateFreelyAsClient:
  1149. // Ok.
  1150. default:
  1151. c.sendAlert(alertInternalError)
  1152. return errors.New("tls: unknown Renegotiation value")
  1153. }
  1154. c.handshakeMutex.Lock()
  1155. defer c.handshakeMutex.Unlock()
  1156. c.phase = handshakeRunning
  1157. c.handshakeComplete = false
  1158. if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
  1159. c.handshakes++
  1160. }
  1161. return c.handshakeErr
  1162. }
  1163. // ConfirmHandshake waits for the handshake to reach a point at which
  1164. // the connection is certainly not replayed. That is, after receiving
  1165. // the Client Finished.
  1166. //
  1167. // If ConfirmHandshake returns an error and until ConfirmHandshake
  1168. // returns, the 0-RTT data should not be trusted not to be replayed.
  1169. //
  1170. // This is only meaningful in TLS 1.3 when Accept0RTTData is true and the
  1171. // client sent valid 0-RTT data. In any other case it's equivalent to
  1172. // calling Handshake.
  1173. func (c *Conn) ConfirmHandshake() error {
  1174. if c.isClient {
  1175. panic("ConfirmHandshake should only be called for servers")
  1176. }
  1177. if err := c.Handshake(); err != nil {
  1178. return err
  1179. }
  1180. if c.vers < VersionTLS13 {
  1181. return nil
  1182. }
  1183. c.confirmMutex.Lock()
  1184. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1185. c.confirmMutex.Unlock()
  1186. return nil
  1187. } else {
  1188. defer func() {
  1189. // If we transitioned to handshakeConfirmed we already released the lock,
  1190. // otherwise do it here.
  1191. if c.phase != handshakeConfirmed {
  1192. c.confirmMutex.Unlock()
  1193. }
  1194. }()
  1195. }
  1196. c.in.Lock()
  1197. defer c.in.Unlock()
  1198. var input *block
  1199. // Try to read all data (if phase==readingEarlyData) or extract the
  1200. // remaining data from the previous read that could not fit in the read
  1201. // buffer (if c.input != nil).
  1202. if c.phase == readingEarlyData || c.input != nil {
  1203. buf := &bytes.Buffer{}
  1204. if _, err := buf.ReadFrom(earlyDataReader{c}); err != nil {
  1205. c.in.setErrorLocked(err)
  1206. return err
  1207. }
  1208. input = &block{data: buf.Bytes()}
  1209. }
  1210. // At this point, earlyDataReader has read all early data and received
  1211. // the end_of_early_data signal. Expect a Finished message.
  1212. // Locks held so far: c.confirmMutex, c.in
  1213. // not confirmed implies c.phase == discardingEarlyData || c.phase == waitingClientFinished
  1214. for c.phase != handshakeConfirmed {
  1215. if err := c.hs.readClientFinished13(true); err != nil {
  1216. c.in.setErrorLocked(err)
  1217. return err
  1218. }
  1219. }
  1220. if c.phase != handshakeConfirmed {
  1221. panic("should have reached handshakeConfirmed state")
  1222. }
  1223. if c.input != nil {
  1224. panic("should not have read past the Client Finished")
  1225. }
  1226. c.input = input
  1227. return nil
  1228. }
  1229. // earlyDataReader wraps a Conn and reads only early data, both buffered
  1230. // and still on the wire.
  1231. type earlyDataReader struct {
  1232. c *Conn
  1233. }
  1234. // c.in.Mutex <= L
  1235. func (r earlyDataReader) Read(b []byte) (n int, err error) {
  1236. c := r.c
  1237. if c.phase == handshakeConfirmed {
  1238. // c.input might not be early data
  1239. panic("earlyDataReader called at handshakeConfirmed")
  1240. }
  1241. for c.input == nil && c.in.err == nil && c.phase == readingEarlyData {
  1242. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1243. return 0, err
  1244. }
  1245. if c.hand.Len() > 0 {
  1246. if err := c.handleEndOfEarlyData(); err != nil {
  1247. return 0, err
  1248. }
  1249. }
  1250. }
  1251. if err := c.in.err; err != nil {
  1252. return 0, err
  1253. }
  1254. if c.input != nil {
  1255. n, err = c.input.Read(b)
  1256. if err == io.EOF {
  1257. err = nil
  1258. c.in.freeBlock(c.input)
  1259. c.input = nil
  1260. }
  1261. }
  1262. // Following early application data, an end_of_early_data is expected.
  1263. if err == nil && c.phase != readingEarlyData && c.input == nil {
  1264. err = io.EOF
  1265. }
  1266. return
  1267. }
  1268. // Read can be made to time out and return a net.Error with Timeout() == true
  1269. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  1270. func (c *Conn) Read(b []byte) (n int, err error) {
  1271. if err = c.Handshake(); err != nil {
  1272. return
  1273. }
  1274. if len(b) == 0 {
  1275. // Put this after Handshake, in case people were calling
  1276. // Read(nil) for the side effect of the Handshake.
  1277. return
  1278. }
  1279. c.confirmMutex.Lock()
  1280. if atomic.LoadInt32(&c.handshakeConfirmed) == 1 { // c.phase == handshakeConfirmed
  1281. c.confirmMutex.Unlock()
  1282. } else {
  1283. defer func() {
  1284. // If we transitioned to handshakeConfirmed we already released the lock,
  1285. // otherwise do it here.
  1286. if c.phase != handshakeConfirmed {
  1287. c.confirmMutex.Unlock()
  1288. }
  1289. }()
  1290. }
  1291. c.in.Lock()
  1292. defer c.in.Unlock()
  1293. // Some OpenSSL servers send empty records in order to randomize the
  1294. // CBC IV. So this loop ignores a limited number of empty records.
  1295. const maxConsecutiveEmptyRecords = 100
  1296. for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
  1297. for c.input == nil && c.in.err == nil {
  1298. if err := c.readRecord(recordTypeApplicationData); err != nil {
  1299. // Soft error, like EAGAIN
  1300. return 0, err
  1301. }
  1302. if c.hand.Len() > 0 {
  1303. if c.phase == readingEarlyData || c.phase == waitingClientFinished {
  1304. if c.phase == readingEarlyData {
  1305. if err := c.handleEndOfEarlyData(); err != nil {
  1306. return 0, err
  1307. }
  1308. }
  1309. // Server has received all early data, confirm
  1310. // by reading the Client Finished message.
  1311. if err := c.hs.readClientFinished13(true); err != nil {
  1312. c.in.setErrorLocked(err)
  1313. return 0, err
  1314. }
  1315. continue
  1316. }
  1317. if err := c.handlePostHandshake(); err != nil {
  1318. return 0, err
  1319. }
  1320. }
  1321. }
  1322. if err := c.in.err; err != nil {
  1323. return 0, err
  1324. }
  1325. n, err = c.input.Read(b)
  1326. if err == io.EOF {
  1327. err = nil
  1328. c.in.freeBlock(c.input)
  1329. c.input = nil
  1330. }
  1331. // If a close-notify alert is waiting, read it so that
  1332. // we can return (n, EOF) instead of (n, nil), to signal
  1333. // to the HTTP response reading goroutine that the
  1334. // connection is now closed. This eliminates a race
  1335. // where the HTTP response reading goroutine would
  1336. // otherwise not observe the EOF until its next read,
  1337. // by which time a client goroutine might have already
  1338. // tried to reuse the HTTP connection for a new
  1339. // request.
  1340. // See https://codereview.appspot.com/76400046
  1341. // and https://golang.org/issue/3514
  1342. if ri := c.rawInput; ri != nil &&
  1343. n != 0 && err == nil &&
  1344. c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
  1345. if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
  1346. err = recErr // will be io.EOF on closeNotify
  1347. }
  1348. }
  1349. if n != 0 || err != nil {
  1350. return n, err
  1351. }
  1352. }
  1353. return 0, io.ErrNoProgress
  1354. }
  1355. // Close closes the connection.
  1356. func (c *Conn) Close() error {
  1357. // Interlock with Conn.Write above.
  1358. var x int32
  1359. for {
  1360. x = atomic.LoadInt32(&c.activeCall)
  1361. if x&1 != 0 {
  1362. return errClosed
  1363. }
  1364. if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
  1365. break
  1366. }
  1367. }
  1368. if x != 0 {
  1369. // io.Writer and io.Closer should not be used concurrently.
  1370. // If Close is called while a Write is currently in-flight,
  1371. // interpret that as a sign that this Close is really just
  1372. // being used to break the Write and/or clean up resources and
  1373. // avoid sending the alertCloseNotify, which may block
  1374. // waiting on handshakeMutex or the c.out mutex.
  1375. return c.conn.Close()
  1376. }
  1377. var alertErr error
  1378. c.handshakeMutex.Lock()
  1379. if c.handshakeComplete {
  1380. alertErr = c.closeNotify()
  1381. }
  1382. c.handshakeMutex.Unlock()
  1383. if err := c.conn.Close(); err != nil {
  1384. return err
  1385. }
  1386. return alertErr
  1387. }
  1388. var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
  1389. // CloseWrite shuts down the writing side of the connection. It should only be
  1390. // called once the handshake has completed and does not call CloseWrite on the
  1391. // underlying connection. Most callers should just use Close.
  1392. func (c *Conn) CloseWrite() error {
  1393. c.handshakeMutex.Lock()
  1394. defer c.handshakeMutex.Unlock()
  1395. if !c.handshakeComplete {
  1396. return errEarlyCloseWrite
  1397. }
  1398. return c.closeNotify()
  1399. }
  1400. func (c *Conn) closeNotify() error {
  1401. c.out.Lock()
  1402. defer c.out.Unlock()
  1403. if !c.closeNotifySent {
  1404. c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
  1405. c.closeNotifySent = true
  1406. }
  1407. return c.closeNotifyErr
  1408. }
  1409. // Handshake runs the client or server handshake
  1410. // protocol if it has not yet been run.
  1411. // Most uses of this package need not call Handshake
  1412. // explicitly: the first Read or Write will call it automatically.
  1413. //
  1414. // In TLS 1.3 Handshake returns after the client and server first flights,
  1415. // without waiting for the Client Finished.
  1416. func (c *Conn) Handshake() error {
  1417. c.handshakeMutex.Lock()
  1418. defer c.handshakeMutex.Unlock()
  1419. if err := c.handshakeErr; err != nil {
  1420. return err
  1421. }
  1422. if c.handshakeComplete {
  1423. return nil
  1424. }
  1425. c.in.Lock()
  1426. defer c.in.Unlock()
  1427. // The handshake cannot have completed when handshakeMutex was unlocked
  1428. // because this goroutine set handshakeCond.
  1429. if c.handshakeErr != nil || c.handshakeComplete {
  1430. panic("handshake should not have been able to complete after handshakeCond was set")
  1431. }
  1432. c.connID = make([]byte, 8)
  1433. if _, err := io.ReadFull(c.config.rand(), c.connID); err != nil {
  1434. return err
  1435. }
  1436. if c.isClient {
  1437. c.handshakeErr = c.clientHandshake()
  1438. } else {
  1439. c.handshakeErr = c.serverHandshake()
  1440. }
  1441. if c.handshakeErr == nil {
  1442. c.handshakes++
  1443. } else {
  1444. // If an error occurred during the hadshake try to flush the
  1445. // alert that might be left in the buffer.
  1446. c.flush()
  1447. }
  1448. if c.handshakeErr == nil && !c.handshakeComplete {
  1449. panic("handshake should have had a result.")
  1450. }
  1451. return c.handshakeErr
  1452. }
  1453. // ConnectionState returns basic TLS details about the connection.
  1454. func (c *Conn) ConnectionState() ConnectionState {
  1455. c.handshakeMutex.Lock()
  1456. defer c.handshakeMutex.Unlock()
  1457. var state ConnectionState
  1458. state.HandshakeComplete = c.handshakeComplete
  1459. state.ServerName = c.serverName
  1460. if c.handshakeComplete {
  1461. state.ConnectionID = c.connID
  1462. state.ClientHello = c.clientHello
  1463. state.Version = c.vers
  1464. state.NegotiatedProtocol = c.clientProtocol
  1465. state.DidResume = c.didResume
  1466. state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
  1467. state.CipherSuite = c.cipherSuite
  1468. state.PeerCertificates = c.peerCertificates
  1469. state.VerifiedChains = c.verifiedChains
  1470. state.SignedCertificateTimestamps = c.scts
  1471. state.OCSPResponse = c.ocspResponse
  1472. state.HandshakeConfirmed = atomic.LoadInt32(&c.handshakeConfirmed) == 1
  1473. if !state.HandshakeConfirmed {
  1474. state.Unique0RTTToken = c.binder
  1475. }
  1476. if !c.didResume {
  1477. if c.clientFinishedIsFirst {
  1478. state.TLSUnique = c.clientFinished[:]
  1479. } else {
  1480. state.TLSUnique = c.serverFinished[:]
  1481. }
  1482. }
  1483. }
  1484. return state
  1485. }
  1486. // OCSPResponse returns the stapled OCSP response from the TLS server, if
  1487. // any. (Only valid for client connections.)
  1488. func (c *Conn) OCSPResponse() []byte {
  1489. c.handshakeMutex.Lock()
  1490. defer c.handshakeMutex.Unlock()
  1491. return c.ocspResponse
  1492. }
  1493. // VerifyHostname checks that the peer certificate chain is valid for
  1494. // connecting to host. If so, it returns nil; if not, it returns an error
  1495. // describing the problem.
  1496. func (c *Conn) VerifyHostname(host string) error {
  1497. c.handshakeMutex.Lock()
  1498. defer c.handshakeMutex.Unlock()
  1499. if !c.isClient {
  1500. return errors.New("tls: VerifyHostname called on TLS server connection")
  1501. }
  1502. if !c.handshakeComplete {
  1503. return errors.New("tls: handshake has not yet been performed")
  1504. }
  1505. if len(c.verifiedChains) == 0 {
  1506. return errors.New("tls: handshake did not verify certificate chain")
  1507. }
  1508. return c.peerCertificates[0].VerifyHostname(host)
  1509. }