| 6 |
| 7 | package runner |
| 8 |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "crypto/aes" |
| 12 | "crypto/cipher" |
| 13 | "crypto/ecdsa" |
| 14 | "crypto/subtle" |
| 15 | "crypto/x509" |
| 16 | "encoding/binary" |
| 17 | "errors" |
| 18 | "fmt" |
| 19 | "io" |
| 20 | "net" |
| 21 | "slices" |
| 22 | "sync" |
| 23 | "time" |
| 24 |
| 25 | "golang.org/x/crypto/chacha20" |
| 26 | "golang.org/x/crypto/cryptobyte" |
| 27 | ) |
| 28 |
| 29 | type dtlsRecordInfo struct { |
| 30 | typ recordType |
| 31 | epoch uint16 |
| 32 | // bytesAvailable is the number of additional bytes of plaintext that could |
| 33 | // have been added to this record without exceeding the packet limit. |
| 34 | bytesAvailable int |
| 35 | } |
| 36 |
| 37 | // A Conn represents a secured connection. |
| 38 | // It implements the net.Conn interface. |
| 39 | type Conn struct { |
| 40 | // constant |
| 41 | conn net.Conn |
| 42 | isDTLS bool |
| 43 | isClient bool |
| 44 |
| 45 | // constant after handshake; protected by handshakeMutex |
| 46 | handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex |
| 47 | handshakeErr error // error resulting from handshake |
| 48 | wireVersion uint16 // TLS wire version |
| 49 | vers uint16 // TLS version |
| 50 | haveVers bool // version has been negotiated |
| 51 | config *Config // configuration passed to constructor |
| 52 | handshakeComplete bool |
| 53 | skipEarlyData bool // On a server, indicates that the client is sending early data that must be skipped over. |
| 54 | didResume bool // whether this connection was a session resumption |
| 55 | extendedMasterSecret bool // whether this session used an extended master secret |
| 56 | cipherSuite *cipherSuite |
| 57 | ocspResponse []byte // stapled OCSP response |
| 58 | sctList []byte // signed certificate timestamp list |
| 59 | peerCertificates []*x509.Certificate |
| 60 | peerDelegatedCredential []byte |
| 61 | // verifiedChains contains the certificate chains that we built, as |
| 62 | // opposed to the ones presented by the server. |
| 63 | verifiedChains [][]*x509.Certificate |
| 64 | // serverName contains the server name indicated by the client, if any. |
| 65 | serverName string |
| 66 | // firstFinished contains the first Finished hash sent during the |
| 67 | // handshake. This is the "tls-unique" channel binding value. |
| 68 | firstFinished [12]byte |
| 69 | // peerSignatureAlgorithm contains the signature algorithm that was used |
| 70 | // by the peer in the handshake, or zero if not applicable. |
| 71 | peerSignatureAlgorithm signatureAlgorithm |
| 72 | // curveID contains the curve that was used in the handshake, or zero if |
| 73 | // not applicable. |
| 74 | curveID CurveID |
| 75 | // quicTransportParams contains the QUIC transport params received |
| 76 | // by the peer using codepoint 57. |
| 77 | quicTransportParams []byte |
| 78 | // quicTransportParams contains the QUIC transport params received |
| 79 | // by the peer using legacy codepoint 0xffa5. |
| 80 | quicTransportParamsLegacy []byte |
| 81 |
| 82 | clientRandom, serverRandom [32]byte |
| 83 | earlyExporterSecret []byte |
| 84 | exporterSecret []byte |
| 85 | resumptionSecret []byte |
| 86 |
| 87 | clientProtocol string |
| 88 | clientProtocolFallback bool |
| 89 | usedALPN bool |
| 90 |
| 91 | localApplicationSettings, peerApplicationSettings []byte |
| 92 | hasApplicationSettings bool |
| 93 | localApplicationSettingsOld, peerApplicationSettingsOld []byte |
| 94 | hasApplicationSettingsOld bool |
| 95 |
| 96 | // verify_data values for the renegotiation extension. |
| 97 | clientVerify []byte |
| 98 | serverVerify []byte |
| 99 |
| 100 | channelID *ecdsa.PublicKey |
| 101 |
| 102 | srtpProtectionProfile uint16 |
| 103 |
| 104 | clientVersion uint16 |
| 105 |
| 106 | // input/output |
| 107 | in, out halfConn // in.Mutex < out.Mutex |
| 108 | rawInput bytes.Buffer // raw input, right off the wire |
| 109 | input bytes.Buffer // application record waiting to be read |
| 110 | hand bytes.Buffer // handshake record waiting to be read |
| 111 |
| 112 | // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of |
| 113 | // handshake data to be split into records at the end of the flight. |
| 114 | pendingFlight bytes.Buffer |
| 115 |
| 116 | // DTLS state |
| 117 | sendHandshakeSeq uint16 |
| 118 | recvHandshakeSeq uint16 |
| 119 | handMsg []byte // pending assembled handshake message |
| 120 | handMsgLen int // handshake message length, not including the header |
| 121 | pendingPacket []byte // pending outgoing packet. |
| 122 | maxPacketLen int |
| 123 |
| 124 | previousFlight []DTLSMessage |
| 125 | receivedFlight []DTLSMessage |
| 126 | receivedFlightRecords []DTLSRecordNumberInfo |
| 127 | nextFlight []DTLSMessage |
| 128 | expectedACK []DTLSRecordNumber |
| 129 |
| 130 | keyUpdateSeen bool |
| 131 | keyUpdateRequested bool |
| 132 | seenOneByteRecord bool |
| 133 |
| 134 | expectTLS13ChangeCipherSpec bool |
| 135 |
| 136 | // seenHandshakePackEnd is whether the most recent handshake record was |
| 137 | // not full for ExpectPackedEncryptedHandshake. If true, no more |
| 138 | // handshake data may be received until the next flight or epoch change. |
| 139 | seenHandshakePackEnd bool |
| 140 |
| 141 | // lastRecordInFlight contains information about the previous handshake or |
| 142 | // ChangeCipherSpec record from the current flight, or nil if we are not in |
| 143 | // the middle of reading a flight from the peer. |
| 144 | lastRecordInFlight *dtlsRecordInfo |
| 145 |
| 146 | // bytesAvailableInPacket is the number of bytes that were still available |
| 147 | // in the current DTLS packet, up to a budget of maxPacketLen. |
| 148 | bytesAvailableInPacket int |
| 149 |
| 150 | // skipRecordVersionCheck, if true, causes the DTLS record layer to skip the |
| 151 | // record version check, even if the version is known. This is used when |
| 152 | // simulating retransmits. |
| 153 | skipRecordVersionCheck bool |
| 154 |
| 155 | // echAccepted indicates whether ECH was accepted for this connection. |
| 156 | echAccepted bool |
| 157 |
| 158 | tmp [16]byte |
| 159 | } |
| 160 |
| 161 | func (c *Conn) init() { |
| 162 | c.in.isDTLS = c.isDTLS |
| 163 | c.out.isDTLS = c.isDTLS |
| 164 | c.in.config = c.config |
| 165 | c.out.config = c.config |
| 166 | c.in.conn = c |
| 167 | c.out.conn = c |
| 168 | c.maxPacketLen = c.config.Bugs.MaxPacketLength |
| 169 | } |
| 170 |
| 171 | // Access to net.Conn methods. |
| 172 | // Cannot just embed net.Conn because that would |
| 173 | // export the struct field too. |
| 174 |
| 175 | // LocalAddr returns the local network address. |
| 176 | func (c *Conn) LocalAddr() net.Addr { |
| 177 | return c.conn.LocalAddr() |
| 178 | } |
| 179 |
| 180 | // RemoteAddr returns the remote network address. |
| 181 | func (c *Conn) RemoteAddr() net.Addr { |
| 182 | return c.conn.RemoteAddr() |
| 183 | } |
| 184 |
| 185 | // SetDeadline sets the read and write deadlines associated with the connection. |
| 186 | // A zero value for t means Read and Write will not time out. |
| 187 | // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. |
| 188 | func (c *Conn) SetDeadline(t time.Time) error { |
| 189 | return c.conn.SetDeadline(t) |
| 190 | } |
| 191 |
| 192 | // SetReadDeadline sets the read deadline on the underlying connection. |
| 193 | // A zero value for t means Read will not time out. |
| 194 | func (c *Conn) SetReadDeadline(t time.Time) error { |
| 195 | return c.conn.SetReadDeadline(t) |
| 196 | } |
| 197 |
| 198 | // SetWriteDeadline sets the write deadline on the underlying conneciton. |
| 199 | // A zero value for t means Write will not time out. |
| 200 | // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. |
| 201 | func (c *Conn) SetWriteDeadline(t time.Time) error { |
| 202 | return c.conn.SetWriteDeadline(t) |
| 203 | } |
| 204 |
| 205 | // Arbitrarily cap the number of past epochs to 4. This is far more than is |
| 206 | // necessary. We set a limit only so tests can freely trigger unboundedly many |
| 207 | // KeyUpdates. |
| 208 | const maxEpochs = 4 |
| 209 |
| 210 | type epochState struct { |
| 211 | epoch uint16 |
| 212 | cipher any // cipher algorithm |
| 213 | recordNumberEncrypter recordNumberEncrypter |
| 214 | mac macFunction |
| 215 | seq [8]byte |
| 216 | } |
| 217 |
| 218 | // A halfConn represents one direction of the record layer |
| 219 | // connection, either sending or receiving. |
| 220 | type halfConn struct { |
| 221 | sync.Mutex |
| 222 |
| 223 | err error // first permanent error |
| 224 | version uint16 // protocol version |
| 225 | wireVersion uint16 // wire version |
| 226 | isDTLS bool |
| 227 | epoch epochState |
| 228 | pastEpochs []epochState |
| 229 |
| 230 | nextEpoch epochState |
| 231 |
| 232 | // used to save allocating a new buffer for each MAC. |
| 233 | macBuf []byte |
| 234 |
| 235 | trafficSecret []byte |
| 236 |
| 237 | config *Config |
| 238 | conn *Conn |
| 239 | } |
| 240 |
| 241 | func (hc *halfConn) setErrorLocked(err error) error { |
| 242 | hc.err = err |
| 243 | return err |
| 244 | } |
| 245 |
| 246 | func (hc *halfConn) error() error { |
| 247 | // This should be locked, but I've removed it for the renegotiation |
| 248 | // tests since we don't concurrently read and write the same tls.Conn |
| 249 | // in any case during testing. |
| 250 | err := hc.err |
| 251 | return err |
| 252 | } |
| 253 |
| 254 | func (hc *halfConn) getEpoch(epochValue uint16) (*epochState, bool) { |
| 255 | if hc.epoch.epoch == epochValue { |
| 256 | return &hc.epoch, true |
| 257 | } |
| 258 | for i := range hc.pastEpochs { |
| 259 | if hc.pastEpochs[i].epoch == epochValue { |
| 260 | return &hc.pastEpochs[i], true |
| 261 | } |
| 262 | } |
| 263 | return nil, false |
| 264 | } |
| 265 |
| 266 | func (hc *halfConn) changeEpoch(epoch epochState) { |
| 267 | if len(hc.pastEpochs) < maxEpochs { |
| 268 | hc.pastEpochs = append(hc.pastEpochs, hc.epoch) |
| 269 | } else { |
| 270 | for i := 1; i < len(hc.pastEpochs); i++ { |
| 271 | hc.pastEpochs[i-1] = hc.pastEpochs[i] |
| 272 | } |
| 273 | hc.pastEpochs[len(hc.pastEpochs)-1] = hc.epoch |
| 274 | } |
| 275 | hc.epoch = epoch |
| 276 | } |
| 277 |
| 278 | func (hc *halfConn) newEpochState(epoch uint16, cipher any, mac macFunction) epochState { |
| 279 | ret := epochState{epoch: epoch, cipher: cipher, mac: mac} |
| 280 | if hc.isDTLS { |
| 281 | binary.BigEndian.PutUint16(ret.seq[:2], epoch) |
| 282 | } |
| 283 | return ret |
| 284 | } |
| 285 |
| 286 | // prepareCipherSpec sets the encryption and MAC states |
| 287 | // that a subsequent changeCipherSpec will use. |
| 288 | func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac macFunction) { |
| 289 | hc.wireVersion = version |
| 290 | protocolVersion, ok := wireToVersion(version, hc.isDTLS) |
| 291 | if !ok { |
| 292 | panic("TLS: unknown version") |
| 293 | } |
| 294 | hc.version = protocolVersion |
| 295 | epoch := hc.epoch.epoch + 1 |
| 296 | if epoch == 0 { |
| 297 | panic("TLS: epoch overflow") |
| 298 | } |
| 299 | hc.nextEpoch = hc.newEpochState(epoch, cipher, mac) |
| 300 | } |
| 301 |
| 302 | // changeCipherSpec changes the encryption and MAC states |
| 303 | // to the ones previously passed to prepareCipherSpec. |
| 304 | func (hc *halfConn) changeCipherSpec() error { |
| 305 | if hc.nextEpoch.cipher == nil { |
| 306 | return alertInternalError |
| 307 | } |
| 308 | hc.changeEpoch(hc.nextEpoch) |
| 309 | hc.nextEpoch = epochState{} |
| 310 |
| 311 | if hc.config.Bugs.NullAllCiphers { |
| 312 | hc.epoch.cipher = nullCipher{} |
| 313 | hc.epoch.mac = nil |
| 314 | } |
| 315 | return nil |
| 316 | } |
| 317 |
| 318 | // useTrafficSecret sets the current cipher state for TLS 1.3. |
| 319 | func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection, epoch uint16) { |
| 320 | hc.wireVersion = version |
| 321 | protocolVersion, ok := wireToVersion(version, hc.isDTLS) |
| 322 | if !ok { |
| 323 | panic("TLS: unknown version") |
| 324 | } |
| 325 | hc.version = protocolVersion |
| 326 | newEpoch := hc.newEpochState(epoch, deriveTrafficAEAD(version, suite, secret, side, hc.isDTLS), nil) |
| 327 | if hc.isDTLS && !hc.config.Bugs.NullAllCiphers { |
| 328 | sn_key := hkdfExpandLabel(suite.hash(), secret, []byte("sn"), nil, suite.keyLen, hc.isDTLS) |
| 329 | switch suite.id { |
| 330 | case TLS_CHACHA20_POLY1305_SHA256: |
| 331 | newEpoch.recordNumberEncrypter = newChachaRecordNumberEncrypter(sn_key) |
| 332 | case TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384: |
| 333 | newEpoch.recordNumberEncrypter = newAESRecordNumberEncrypter(sn_key) |
| 334 | default: |
| 335 | panic("Cipher suite does not support TLS 1.3") |
| 336 | } |
| 337 | } |
| 338 | if hc.config.Bugs.NullAllCiphers { |
| 339 | newEpoch.cipher = nullCipher{} |
| 340 | } |
| 341 | hc.trafficSecret = secret |
| 342 | hc.changeEpoch(newEpoch) |
| 343 | } |
| 344 |
| 345 | // resetCipher resets the cipher state back to no encryption to be able |
| 346 | // to send an unencrypted ClientHello in response to HelloRetryRequest |
| 347 | // after 0-RTT data was rejected. |
| 348 | func (hc *halfConn) resetCipher() { |
| 349 | initialEpoch, ok := hc.getEpoch(0) |
| 350 | if !ok { |
| 351 | panic("tls: could not find initial epoch") |
| 352 | } |
| 353 | hc.epoch = *initialEpoch |
| 354 | hc.pastEpochs = nil |
| 355 | } |
| 356 |
| 357 | // incSeq increments the sequence number. |
| 358 | func (hc *halfConn) incSeq(epoch *epochState) { |
| 359 | limit := 0 |
| 360 | increment := uint64(1) |
| 361 | if hc.isDTLS { |
| 362 | // Increment up to the epoch in DTLS. |
| 363 | limit = 2 |
| 364 | } |
| 365 | for i := 7; i >= limit; i-- { |
| 366 | increment += uint64(epoch.seq[i]) |
| 367 | epoch.seq[i] = byte(increment) |
| 368 | increment >>= 8 |
| 369 | } |
| 370 |
| 371 | // Not allowed to let sequence number wrap. |
| 372 | // Instead, must renegotiate before it does. |
| 373 | // Not likely enough to bother. |
| 374 | if increment != 0 { |
| 375 | panic("TLS: sequence number wraparound") |
| 376 | } |
| 377 | } |
| 378 |
| 379 | // lastRecordNumber returns the most recent record number decrypted or encrypted |
| 380 | // on a halfConn. |
| 381 | // |
| 382 | // TODO(crbug.com/376641666): This function is a bit hacky. It needs to rewind |
| 383 | // the state back to what the last call actually used. Fix the TLS/DTLS |
| 384 | // abstractions so we can return this value out directly. |
| 385 | func (hc *halfConn) lastRecordNumber(epoch *epochState, isOut bool) DTLSRecordNumber { |
| 386 | seq := binary.BigEndian.Uint64(epoch.seq[:]) |
| 387 | // We maintain the next record number, so undo the increment. |
| 388 | if seq&(1<<48-1) == 0 { |
| 389 | panic("tls: epoch has never been used") |
| 390 | } |
| 391 | seq-- |
| 392 | if hc.isDTLS { |
| 393 | if isOut && hc.config.Bugs.SequenceNumberMapping != nil { |
| 394 | seq = hc.config.Bugs.SequenceNumberMapping(seq) |
| 395 | } |
| 396 | // Remove the embedded epoch number. |
| 397 | seq &= 1<<48 - 1 |
| 398 | } |
| 399 | return DTLSRecordNumber{Epoch: uint64(epoch.epoch), Sequence: seq} |
| 400 | } |
| 401 |
| 402 | func (hc *halfConn) sequenceNumberForOutput(epoch *epochState) []byte { |
| 403 | if !hc.isDTLS || hc.config.Bugs.SequenceNumberMapping == nil { |
| 404 | return epoch.seq[:] |
| 405 | } |
| 406 |
| 407 | var seq [8]byte |
| 408 | seqU64 := binary.BigEndian.Uint64(epoch.seq[:]) |
| 409 | seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64) |
| 410 | binary.BigEndian.PutUint64(seq[:], seqU64) |
| 411 | // The DTLS epoch cannot be changed. |
| 412 | copy(seq[:2], epoch.seq[:2]) |
| 413 | return seq[:] |
| 414 | } |
| 415 |
| 416 | func (hc *halfConn) explicitIVLen(epoch *epochState) int { |
| 417 | if epoch.cipher == nil { |
| 418 | return 0 |
| 419 | } |
| 420 | switch c := epoch.cipher.(type) { |
| 421 | case cipher.Stream: |
| 422 | return 0 |
| 423 | case *tlsAead: |
| 424 | if c.explicitNonce { |
| 425 | return 8 |
| 426 | } |
| 427 | return 0 |
| 428 | case *cbcMode: |
| 429 | if hc.version >= VersionTLS11 || hc.isDTLS { |
| 430 | return c.BlockSize() |
| 431 | } |
| 432 | return 0 |
| 433 | case nullCipher: |
| 434 | return 0 |
| 435 | default: |
| 436 | panic("unknown cipher type") |
| 437 | } |
| 438 | } |
| 439 |
| 440 | func (hc *halfConn) computeMAC(epoch *epochState, seq, header, data []byte) []byte { |
| 441 | hc.macBuf = epoch.mac.MAC(hc.macBuf[:0], seq, header[:3], header[len(header)-2:], data) |
| 442 | return hc.macBuf |
| 443 | } |
| 444 |
| 445 | // removePadding returns an unpadded slice, in constant time, which is a prefix |
| 446 | // of the input. It also returns a byte which is equal to 255 if the padding |
| 447 | // was valid and 0 otherwise. See RFC 2246, section 6.2.3.2 |
| 448 | func removePadding(payload []byte) ([]byte, byte) { |
| 449 | if len(payload) < 1 { |
| 450 | return payload, 0 |
| 451 | } |
| 452 |
| 453 | paddingLen := payload[len(payload)-1] |
| 454 | t := uint(len(payload)-1) - uint(paddingLen) |
| 455 | // if len(payload) >= (paddingLen - 1) then the MSB of t is zero |
| 456 | good := byte(int32(^t) >> 31) |
| 457 |
| 458 | toCheck := 255 // the maximum possible padding length |
| 459 | // The length of the padded data is public, so we can use an if here |
| 460 | if toCheck+1 > len(payload) { |
| 461 | toCheck = len(payload) - 1 |
| 462 | } |
| 463 |
| 464 | for i := 0; i < toCheck; i++ { |
| 465 | t := uint(paddingLen) - uint(i) |
| 466 | // if i <= paddingLen then the MSB of t is zero |
| 467 | mask := byte(int32(^t) >> 31) |
| 468 | b := payload[len(payload)-1-i] |
| 469 | good &^= mask&paddingLen ^ mask&b |
| 470 | } |
| 471 |
| 472 | // We AND together the bits of good and replicate the result across |
| 473 | // all the bits. |
| 474 | good &= good << 4 |
| 475 | good &= good << 2 |
| 476 | good &= good << 1 |
| 477 | good = uint8(int8(good) >> 7) |
| 478 |
| 479 | toRemove := good&paddingLen + 1 |
| 480 | return payload[:len(payload)-int(toRemove)], good |
| 481 | } |
| 482 |
| 483 | func roundUp(a, b int) int { |
| 484 | return a + (b-a%b)%b |
| 485 | } |
| 486 |
| 487 | // decrypt checks and strips the mac and decrypts the data in record. Returns a |
| 488 | // success boolean, the application payload, the encrypted record type (or 0 |
| 489 | // if there is none), and an optional alert value. Decryption occurs in-place, |
| 490 | // so the contents of record will be overwritten as part of this process. |
| 491 | func (hc *halfConn) decrypt(epoch *epochState, recordHeaderLen int, record []byte) (ok bool, contentType recordType, data []byte, alertValue alert) { |
| 492 | // pull out payload |
| 493 | payload := record[recordHeaderLen:] |
| 494 |
| 495 | macSize := 0 |
| 496 | if epoch.mac != nil { |
| 497 | macSize = epoch.mac.Size() |
| 498 | } |
| 499 |
| 500 | paddingGood := byte(255) |
| 501 | explicitIVLen := hc.explicitIVLen(epoch) |
| 502 |
| 503 | // decrypt |
| 504 | if epoch.cipher != nil { |
| 505 | switch c := epoch.cipher.(type) { |
| 506 | case cipher.Stream: |
| 507 | c.XORKeyStream(payload, payload) |
| 508 | case *tlsAead: |
| 509 | nonce := epoch.seq[:] |
| 510 | if hc.isDTLS && hc.version >= VersionTLS13 && !hc.conn.useDTLSPlaintextHeader() { |
| 511 | // Unlike DTLS 1.2, DTLS 1.3's nonce construction does not use |
| 512 | // the epoch number. We store the epoch and nonce numbers |
| 513 | // together, so make a copy without the epoch. |
| 514 | nonce = make([]byte, 8) |
| 515 | copy(nonce[2:], epoch.seq[2:]) |
| 516 | } |
| 517 |
| 518 | if explicitIVLen != 0 { |
| 519 | if len(payload) < explicitIVLen { |
| 520 | return false, 0, nil, alertBadRecordMAC |
| 521 | } |
| 522 | nonce = payload[:explicitIVLen] |
| 523 | payload = payload[explicitIVLen:] |
| 524 | } |
| 525 |
| 526 | var additionalData []byte |
| 527 | if hc.version < VersionTLS13 { |
| 528 | additionalData = make([]byte, 13) |
| 529 | copy(additionalData, epoch.seq[:]) |
| 530 | copy(additionalData[8:], record[:3]) |
| 531 | n := len(payload) - c.Overhead() |
| 532 | additionalData[11] = byte(n >> 8) |
| 533 | additionalData[12] = byte(n) |
| 534 | } else { |
| 535 | additionalData = record[:recordHeaderLen] |
| 536 | } |
| 537 | var err error |
| 538 | payload, err = c.Open(payload[:0], nonce, payload, additionalData) |
| 539 | if err != nil { |
| 540 | return false, 0, nil, alertBadRecordMAC |
| 541 | } |
| 542 | case *cbcMode: |
| 543 | blockSize := c.BlockSize() |
| 544 | if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) { |
| 545 | return false, 0, nil, alertBadRecordMAC |
| 546 | } |
| 547 |
| 548 | if explicitIVLen > 0 { |
| 549 | c.SetIV(payload[:explicitIVLen]) |
| 550 | payload = payload[explicitIVLen:] |
| 551 | } |
| 552 | c.CryptBlocks(payload, payload) |
| 553 | payload, paddingGood = removePadding(payload) |
| 554 |
| 555 | // note that we still have a timing side-channel in the |
| 556 | // MAC check, below. An attacker can align the record |
| 557 | // so that a correct padding will cause one less hash |
| 558 | // block to be calculated. Then they can iteratively |
| 559 | // decrypt a record by breaking each byte. See |
| 560 | // "Password Interception in a SSL/TLS Channel", Brice |
| 561 | // Canvel et al. |
| 562 | // |
| 563 | // However, our behavior matches OpenSSL, so we leak |
| 564 | // only as much as they do. |
| 565 | case nullCipher: |
| 566 | break |
| 567 | default: |
| 568 | panic("unknown cipher type") |
| 569 | } |
| 570 |
| 571 | if hc.version >= VersionTLS13 { |
| 572 | i := len(payload) |
| 573 | for i > 0 && payload[i-1] == 0 { |
| 574 | i-- |
| 575 | } |
| 576 | payload = payload[:i] |
| 577 | if len(payload) == 0 { |
| 578 | return false, 0, nil, alertUnexpectedMessage |
| 579 | } |
| 580 | contentType = recordType(payload[len(payload)-1]) |
| 581 | payload = payload[:len(payload)-1] |
| 582 | } |
| 583 | } |
| 584 |
| 585 | // check, strip mac |
| 586 | if epoch.mac != nil { |
| 587 | if len(payload) < macSize { |
| 588 | return false, 0, nil, alertBadRecordMAC |
| 589 | } |
| 590 |
| 591 | // strip mac off payload |
| 592 | n := len(payload) - macSize |
| 593 | remoteMAC := payload[n:] |
| 594 | payload = payload[:n] |
| 595 | record[recordHeaderLen-2] = byte(n >> 8) |
| 596 | record[recordHeaderLen-1] = byte(n) |
| 597 | localMAC := hc.computeMAC(epoch, epoch.seq[:], record[:recordHeaderLen], payload) |
| 598 | if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 { |
| 599 | return false, 0, nil, alertBadRecordMAC |
| 600 | } |
| 601 | } |
| 602 | hc.incSeq(epoch) |
| 603 |
| 604 | return true, contentType, payload, 0 |
| 605 | } |
| 606 |
| 607 | // extendSlice updates *data to contain n more bytes and returns a slice |
| 608 | // containing the bytes that were added. |
| 609 | func extendSlice(data *[]byte, n int) []byte { |
| 610 | // Reallocate the slice if needed. |
| 611 | *data = slices.Grow(*data, n) |
| 612 | // Extend data into the capacity and return the newly added slice. |
| 613 | oldLen := len(*data) |
| 614 | newLen := oldLen + n |
| 615 | *data = (*data)[:newLen] |
| 616 | return (*data)[oldLen:newLen] |
| 617 | } |
| 618 |
| 619 | // computingCBCPaddingLength returns the number of bytes of CBC padding to use |
| 620 | // for a payload (plaintext + MAC) of length payloadLen. |
| 621 | func computingCBCPaddingLength(payloadLen, blockSize int, config *Config) int { |
| 622 | paddingLen := blockSize - payloadLen%blockSize |
| 623 | if config.Bugs.MaxPadding { |
| 624 | for paddingLen+blockSize <= 256 { |
| 625 | paddingLen += blockSize |
| 626 | } |
| 627 | } |
| 628 | return paddingLen |
| 629 | } |
| 630 |
| 631 | // appendCBCPadding computes paddingLen bytes of padding data, appends it to b, |
| 632 | // and returns the result. |
| 633 | func appendCBCPadding(b []byte, paddingLen int, config *Config) []byte { |
| 634 | padding := extendSlice(&b, paddingLen) |
| 635 | for i := range padding { |
| 636 | padding[i] = byte(paddingLen - 1) |
| 637 | } |
| 638 | if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 { |
| 639 | padding[0] ^= 0xff |
| 640 | } |
| 641 | return b |
| 642 | } |
| 643 |
| 644 | func (hc *halfConn) maxEncryptOverhead(epoch *epochState, payloadLen int) int { |
| 645 | var macSize int |
| 646 | if epoch.mac != nil { |
| 647 | macSize = epoch.mac.Size() |
| 648 | } |
| 649 | overhead := macSize + hc.explicitIVLen(epoch) |
| 650 | if hc.version >= VersionTLS13 { |
| 651 | overhead += 1 + hc.config.Bugs.RecordPadding // type + padding |
| 652 | } |
| 653 | if epoch.cipher != nil { |
| 654 | switch c := epoch.cipher.(type) { |
| 655 | case cipher.Stream, *nullCipher: |
| 656 | case *tlsAead: |
| 657 | overhead += c.Overhead() |
| 658 | case *cbcMode: |
| 659 | overhead += computingCBCPaddingLength(payloadLen+macSize, c.BlockSize(), hc.config) |
| 660 | case nullCipher: |
| 661 | break |
| 662 | default: |
| 663 | panic("unknown cipher type") |
| 664 | } |
| 665 | } |
| 666 | return overhead |
| 667 | } |
| 668 |
| 669 | func (c *Conn) useDTLSPlaintextHeader() bool { |
| 670 | return c.config.Bugs.DTLSUsePlaintextRecordHeader && c.handshakeComplete |
| 671 | } |
| 672 |
| 673 | // encrypt encrypts and MACs the data in payload, appending it record. On |
| 674 | // entry, the last headerLen bytes of record must be the header. The length |
| 675 | // (which must be in the last two bytes of the header) should be computed for |
| 676 | // the unencrypted, unpadded payload. It will be updated, potentially in-place, |
| 677 | // with the final length. |
| 678 | func (hc *halfConn) encrypt(epoch *epochState, record, payload []byte, typ recordType, headerLen int, headerHasLength bool) ([]byte, error) { |
| 679 | seq := hc.sequenceNumberForOutput(epoch) |
| 680 | prefixLen := len(record) |
| 681 | header := record[prefixLen-headerLen:] |
| 682 | explicitIVLen := hc.explicitIVLen(epoch) |
| 683 |
| 684 | // Reserve some space for the explicit IV. The slice may get reallocated |
| 685 | // after this, so don't use the return value. |
| 686 | extendSlice(&record, explicitIVLen) |
| 687 |
| 688 | // Stage the plaintext, TLS 1.3 padding, and TLS 1.2 MAC in the record, to |
| 689 | // be encrypted in-place. |
| 690 | record = append(record, payload...) |
| 691 |
| 692 | if hc.version >= VersionTLS13 && epoch.cipher != nil { |
| 693 | if hc.config.Bugs.OmitRecordContents { |
| 694 | record = record[:len(record)-len(payload)] |
| 695 | } else { |
| 696 | record = append(record, byte(typ)) |
| 697 | } |
| 698 | padding := extendSlice(&record, hc.config.Bugs.RecordPadding) |
| 699 | clear(padding) |
| 700 | } |
| 701 |
| 702 | if epoch.mac != nil { |
| 703 | record = append(record, hc.computeMAC(epoch, seq, header, payload)...) |
| 704 | } |
| 705 |
| 706 | explicitIV := record[prefixLen : prefixLen+explicitIVLen] |
| 707 | if epoch.cipher != nil { |
| 708 | switch c := epoch.cipher.(type) { |
| 709 | case cipher.Stream: |
| 710 | if explicitIVLen != 0 { |
| 711 | panic("tls: unexpected explicit IV length") |
| 712 | } |
| 713 | c.XORKeyStream(record[prefixLen:], record[prefixLen:]) |
| 714 | case *tlsAead: |
| 715 | nonce := seq |
| 716 | if hc.isDTLS && hc.version >= VersionTLS13 && !hc.conn.useDTLSPlaintextHeader() { |
| 717 | // Unlike DTLS 1.2, DTLS 1.3's nonce construction does not use |
| 718 | // the epoch number. We store the epoch and nonce numbers |
| 719 | // together, so make a copy without the epoch. |
| 720 | nonce = make([]byte, 8) |
| 721 | copy(nonce[2:], seq[2:]) |
| 722 | } |
| 723 |
| 724 | // Save the explicit IV, if not empty. |
| 725 | if len(explicitIV) != 0 { |
| 726 | if explicitIVLen != len(nonce) { |
| 727 | panic("tls: unexpected explicit IV length") |
| 728 | } |
| 729 | copy(explicitIV, nonce) |
| 730 | } |
| 731 |
| 732 | var additionalData []byte |
| 733 | if hc.version < VersionTLS13 { |
| 734 | // (D)TLS 1.2's AD is seq_num || type || version || plaintext length |
| 735 | additionalData = make([]byte, 13) |
| 736 | copy(additionalData, seq) |
| 737 | copy(additionalData[8:], header[:3]) |
| 738 | additionalData[11] = byte(len(payload) >> 8) |
| 739 | additionalData[12] = byte(len(payload)) |
| 740 | } else { |
| 741 | // (D)TLS 1.3's AD is the ciphertext record header, so update the |
| 742 | // length now. |
| 743 | if headerHasLength { |
| 744 | n := len(record) - prefixLen + c.Overhead() |
| 745 | record[prefixLen-2] = byte(n >> 8) |
| 746 | record[prefixLen-1] = byte(n) |
| 747 | } |
| 748 | additionalData = record[prefixLen-headerLen : prefixLen] |
| 749 | } |
| 750 |
| 751 | record = c.Seal(record[:prefixLen+explicitIVLen], nonce, record[prefixLen+explicitIVLen:], additionalData) |
| 752 | case *cbcMode: |
| 753 | if explicitIVLen > 0 { |
| 754 | if _, err := io.ReadFull(hc.config.rand(), explicitIV); err != nil { |
| 755 | return nil, err |
| 756 | } |
| 757 | c.SetIV(explicitIV) |
| 758 | } |
| 759 |
| 760 | blockSize := c.BlockSize() |
| 761 | paddingLen := computingCBCPaddingLength(len(record)-prefixLen, blockSize, hc.config) |
| 762 | record = appendCBCPadding(record, paddingLen, hc.config) |
| 763 | c.CryptBlocks(record[prefixLen:], record[prefixLen:]) |
| 764 | case nullCipher: |
| 765 | break |
| 766 | default: |
| 767 | panic("unknown cipher type") |
| 768 | } |
| 769 | } |
| 770 |
| 771 | // Update the record header to include the encryption overhead. |
| 772 | if headerHasLength { |
| 773 | n := len(record) - prefixLen |
| 774 | record[prefixLen-2] = byte(n >> 8) |
| 775 | record[prefixLen-1] = byte(n) |
| 776 | } |
| 777 | hc.incSeq(epoch) |
| 778 |
| 779 | return record, nil |
| 780 | } |
| 781 |
| 782 | type recordNumberEncrypter interface { |
| 783 | // GenerateMask takes a sample of the encrypted record and returns the |
| 784 | // mask used to encrypt and decrypt record numbers. |
| 785 | generateMask(sample []byte) []byte |
| 786 | } |
| 787 |
| 788 | type aesRecordNumberEncrypter struct { |
| 789 | aesCipher cipher.Block |
| 790 | } |
| 791 |
| 792 | func newAESRecordNumberEncrypter(key []byte) *aesRecordNumberEncrypter { |
| 793 | aesCipher, err := aes.NewCipher(key) |
| 794 | if err != nil { |
| 795 | panic("Incorrect usage of newAESRecordNumberEncrypter") |
| 796 | } |
| 797 | return &aesRecordNumberEncrypter{ |
| 798 | aesCipher: aesCipher, |
| 799 | } |
| 800 | } |
| 801 |
| 802 | func (a *aesRecordNumberEncrypter) generateMask(sample []byte) []byte { |
| 803 | out := make([]byte, len(sample)) |
| 804 | a.aesCipher.Encrypt(out, sample) |
| 805 | return out |
| 806 | } |
| 807 |
| 808 | type chachaRecordNumberEncrypter struct { |
| 809 | key []byte |
| 810 | } |
| 811 |
| 812 | func newChachaRecordNumberEncrypter(key []byte) *chachaRecordNumberEncrypter { |
| 813 | out := &chachaRecordNumberEncrypter{ |
| 814 | key: key, |
| 815 | } |
| 816 | return out |
| 817 | } |
| 818 |
| 819 | func (c *chachaRecordNumberEncrypter) generateMask(sample []byte) []byte { |
| 820 | var counter, nonce []byte |
| 821 | sampleReader := cryptobyte.String(sample) |
| 822 | if !sampleReader.ReadBytes(&counter, 4) || !sampleReader.ReadBytes(&nonce, 12) { |
| 823 | panic("chachaRecordNumberEncrypter.GenerateMask called with wrong size sample") |
| 824 | } |
| 825 | cipher, err := chacha20.NewUnauthenticatedCipher(c.key, nonce) |
| 826 | if err != nil { |
| 827 | panic("Failed to create chacha20 cipher for record number encryption") |
| 828 | } |
| 829 | cipher.SetCounter(binary.LittleEndian.Uint32(counter)) |
| 830 | out := make([]byte, 2) |
| 831 | cipher.XORKeyStream(out, out) |
| 832 | return out |
| 833 | } |
| 834 |
| 835 | func (c *Conn) useInTrafficSecret(epoch uint16, version uint16, suite *cipherSuite, secret []byte) error { |
| 836 | if c.hand.Len() != 0 { |
| 837 | return c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change")) |
| 838 | } |
| 839 | side := serverWrite |
| 840 | if !c.isClient { |
| 841 | side = clientWrite |
| 842 | } |
| 843 | if c.config.Bugs.MockQUICTransport != nil { |
| 844 | if epoch > uint16(encryptionApplication) { |
| 845 | panic("tls: KeyUpdate processed in QUIC") |
| 846 | } |
| 847 | c.config.Bugs.MockQUICTransport.readLevel = encryptionLevel(epoch) |
| 848 | c.config.Bugs.MockQUICTransport.readSecret = secret |
| 849 | c.config.Bugs.MockQUICTransport.readCipherSuite = suite.id |
| 850 | } |
| 851 | c.in.useTrafficSecret(version, suite, secret, side, epoch) |
| 852 | c.seenHandshakePackEnd = false |
| 853 | return nil |
| 854 | } |
| 855 |
| 856 | func (c *Conn) useOutTrafficSecret(epoch uint16, version uint16, suite *cipherSuite, secret []byte) { |
| 857 | if !c.isDTLS { |
| 858 | // The TLS logic relies on flushHandshake to write out packed handshake |
| 859 | // data on key changes. The DTLS logic handles key changes directly. |
| 860 | c.flushHandshake() |
| 861 | } |
| 862 | side := serverWrite |
| 863 | if c.isClient { |
| 864 | side = clientWrite |
| 865 | } |
| 866 | if c.config.Bugs.MockQUICTransport != nil { |
| 867 | if epoch > uint16(encryptionApplication) { |
| 868 | panic("tls: KeyUpdate processed in QUIC") |
| 869 | } |
| 870 | c.config.Bugs.MockQUICTransport.writeLevel = encryptionLevel(epoch) |
| 871 | c.config.Bugs.MockQUICTransport.writeSecret = secret |
| 872 | c.config.Bugs.MockQUICTransport.writeCipherSuite = suite.id |
| 873 | } |
| 874 | c.out.useTrafficSecret(version, suite, secret, side, epoch) |
| 875 | } |
| 876 |
| 877 | func (c *Conn) setSkipEarlyData() { |
| 878 | if c.config.Bugs.MockQUICTransport != nil { |
| 879 | c.config.Bugs.MockQUICTransport.skipEarlyData = true |
| 880 | } else { |
| 881 | c.skipEarlyData = true |
| 882 | } |
| 883 | } |
| 884 |
| 885 | func (c *Conn) shouldSkipEarlyData() bool { |
| 886 | if c.config.Bugs.MockQUICTransport != nil { |
| 887 | return c.config.Bugs.MockQUICTransport.skipEarlyData |
| 888 | } |
| 889 | return c.skipEarlyData |
| 890 | } |
| 891 |
| 892 | func (c *Conn) readRawInputUntil(n int) error { |
| 893 | if c.rawInput.Len() >= n { |
| 894 | return nil |
| 895 | } |
| 896 |
| 897 | n -= c.rawInput.Len() |
| 898 | c.rawInput.Grow(n) |
| 899 | buf := c.rawInput.AvailableBuffer() |
| 900 | nread, err := io.ReadAtLeast(c.conn, buf[:cap(buf)], n) |
| 901 | c.rawInput.Write(buf[:nread]) |
| 902 | return err |
| 903 | } |
| 904 |
| 905 | func (c *Conn) doReadRecord(want recordType) (recordType, []byte, error) { |
| 906 | RestartReadRecord: |
| 907 | if c.isDTLS { |
| 908 | return c.dtlsDoReadRecord(&c.in.epoch, want) |
| 909 | } |
| 910 |
| 911 | recordHeaderLen := tlsRecordHeaderLen |
| 912 |
| 913 | // Read header, payload. |
| 914 | if err := c.readRawInputUntil(recordHeaderLen); err != nil { |
| 915 | // RFC suggests that EOF without an alertCloseNotify is |
| 916 | // an error, but popular web sites seem to do this, |
| 917 | // so we can't make it an error, outside of tests. |
| 918 | if err == io.EOF && c.config.Bugs.ExpectCloseNotify { |
| 919 | err = io.ErrUnexpectedEOF |
| 920 | } |
| 921 | if e, ok := err.(net.Error); !ok || !e.Temporary() { |
| 922 | c.in.setErrorLocked(err) |
| 923 | } |
| 924 | return 0, nil, err |
| 925 | } |
| 926 |
| 927 | header := c.rawInput.Bytes()[:recordHeaderLen] |
| 928 | typ := recordType(header[0]) |
| 929 |
| 930 | // No valid TLS record has a type of 0x80, however SSLv2 handshakes |
| 931 | // start with a uint16 length where the MSB is set and the first record |
| 932 | // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests |
| 933 | // an SSLv2 client. |
| 934 | if want == recordTypeHandshake && typ == 0x80 { |
| 935 | c.sendAlert(alertProtocolVersion) |
| 936 | return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received")) |
| 937 | } |
| 938 |
| 939 | vers := uint16(header[1])<<8 | uint16(header[2]) |
| 940 | n := int(header[3])<<8 | int(header[4]) |
| 941 |
| 942 | // Alerts sent near version negotiation do not have a well-defined |
| 943 | // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer |
| 944 | // version is irrelevant.) |
| 945 | if typ != recordTypeAlert { |
| 946 | var expect uint16 |
| 947 | if c.haveVers { |
| 948 | expect = c.vers |
| 949 | if c.vers >= VersionTLS13 { |
| 950 | expect = VersionTLS12 |
| 951 | } |
| 952 | } else { |
| 953 | expect = c.config.Bugs.ExpectInitialRecordVersion |
| 954 | } |
| 955 | if expect != 0 && vers != expect { |
| 956 | c.sendAlert(alertProtocolVersion) |
| 957 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect)) |
| 958 | } |
| 959 | } |
| 960 | if n > maxCiphertext { |
| 961 | c.sendAlert(alertRecordOverflow) |
| 962 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n)) |
| 963 | } |
| 964 | if !c.haveVers { |
| 965 | // First message, be extra suspicious: |
| 966 | // this might not be a TLS client. |
| 967 | // Bail out before reading a full 'body', if possible. |
| 968 | // The current max version is 3.1. |
| 969 | // If the version is >= 16.0, it's probably not real. |
| 970 | // Similarly, a clientHello message encodes in |
| 971 | // well under a kilobyte. If the length is >= 12 kB, |
| 972 | // it's probably not real. |
| 973 | if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 { |
| 974 | c.sendAlert(alertUnexpectedMessage) |
| 975 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake")) |
| 976 | } |
| 977 | } |
| 978 | if err := c.readRawInputUntil(recordHeaderLen + n); err != nil { |
| 979 | if err == io.EOF { |
| 980 | err = io.ErrUnexpectedEOF |
| 981 | } |
| 982 | if e, ok := err.(net.Error); !ok || !e.Temporary() { |
| 983 | c.in.setErrorLocked(err) |
| 984 | } |
| 985 | return 0, nil, err |
| 986 | } |
| 987 |
| 988 | // Process message. |
| 989 | b := c.rawInput.Next(recordHeaderLen + n) |
| 990 | epoch := &c.in.epoch |
| 991 | ok, encTyp, data, alertValue := c.in.decrypt(epoch, recordHeaderLen, b) |
| 992 | if !ok { |
| 993 | // TLS 1.3 early data uses trial decryption. |
| 994 | if c.skipEarlyData { |
| 995 | goto RestartReadRecord |
| 996 | } |
| 997 | return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue)) |
| 998 | } |
| 999 |
| 1000 | // If the server is expecting a second ClientHello (in response to |
| 1001 | // a HelloRetryRequest) and the client sends early data, there |
| 1002 | // won't be a decryption failure (we will interpret the ciphertext |
| 1003 | // as plaintext application data) but it still needs to be skipped. |
| 1004 | if epoch.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData { |
| 1005 | goto RestartReadRecord |
| 1006 | } |
| 1007 |
| 1008 | c.skipEarlyData = false |
| 1009 |
| 1010 | if c.vers >= VersionTLS13 && epoch.cipher != nil { |
| 1011 | if typ != recordTypeApplicationData { |
| 1012 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data")) |
| 1013 | } |
| 1014 | typ = encTyp |
| 1015 | } |
| 1016 |
| 1017 | if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && len(data) != 1 && !c.seenOneByteRecord { |
| 1018 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split")) |
| 1019 | } |
| 1020 |
| 1021 | c.seenOneByteRecord = typ == recordTypeApplicationData && len(data) == 1 |
| 1022 | return typ, data, nil |
| 1023 | } |
| 1024 |
| 1025 | func (c *Conn) readTLS13ChangeCipherSpec() error { |
| 1026 | if c.config.Bugs.MockQUICTransport != nil { |
| 1027 | return nil |
| 1028 | } |
| 1029 | if c.isDTLS { |
| 1030 | // ChangeCipherSpec in DTLS 1.3 is handled within dtlsDoReadRecord. |
| 1031 | return nil |
| 1032 | } |
| 1033 | if !c.expectTLS13ChangeCipherSpec { |
| 1034 | panic("c.expectTLS13ChangeCipherSpec not set") |
| 1035 | } |
| 1036 |
| 1037 | // Read the ChangeCipherSpec. |
| 1038 | if err := c.readRawInputUntil(6); err != nil { |
| 1039 | return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err)) |
| 1040 | } |
| 1041 | if recordType(c.rawInput.Bytes()[0]) == recordTypeAlert { |
| 1042 | // If the client is sending an alert, allow the ChangeCipherSpec |
| 1043 | // to be skipped. It may be rejecting a sufficiently malformed |
| 1044 | // ServerHello that it can't parse out the version. |
| 1045 | c.expectTLS13ChangeCipherSpec = false |
| 1046 | return nil |
| 1047 | } |
| 1048 |
| 1049 | // Check they match that we expect. |
| 1050 | expected := [6]byte{byte(recordTypeChangeCipherSpec), 3, 1, 0, 1, 1} |
| 1051 | if c.vers >= VersionTLS13 { |
| 1052 | expected[2] = 3 |
| 1053 | } |
| 1054 | if data := c.rawInput.Bytes()[:6]; !bytes.Equal(data, expected[:]) { |
| 1055 | return c.in.setErrorLocked(fmt.Errorf("tls: error invalid TLS 1.3 ChangeCipherSpec: %x", data)) |
| 1056 | } |
| 1057 |
| 1058 | // Discard the data. |
| 1059 | c.rawInput.Next(6) |
| 1060 |
| 1061 | c.expectTLS13ChangeCipherSpec = false |
| 1062 | return nil |
| 1063 | } |
| 1064 |
| 1065 | // readRecord reads the next TLS record from the connection |
| 1066 | // and updates the record layer state. |
| 1067 | // c.in.Mutex <= L; c.input == nil. |
| 1068 | func (c *Conn) readRecord(want recordType) error { |
| 1069 | // Caller must be in sync with connection: |
| 1070 | // handshake data if handshake not yet completed, |
| 1071 | // else application data. |
| 1072 | switch want { |
| 1073 | default: |
| 1074 | c.sendAlert(alertInternalError) |
| 1075 | return c.in.setErrorLocked(errors.New("tls: unknown record type requested")) |
| 1076 | case recordTypeChangeCipherSpec: |
| 1077 | if c.handshakeComplete { |
| 1078 | c.sendAlert(alertInternalError) |
| 1079 | return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete")) |
| 1080 | } |
| 1081 | case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake, recordTypeACK: |
| 1082 | break |
| 1083 | } |
| 1084 |
| 1085 | if c.expectTLS13ChangeCipherSpec { |
| 1086 | if err := c.readTLS13ChangeCipherSpec(); err != nil { |
| 1087 | return err |
| 1088 | } |
| 1089 | } |
| 1090 |
| 1091 | Again: |
| 1092 | doReadRecord := c.doReadRecord |
| 1093 | if c.config.Bugs.MockQUICTransport != nil { |
| 1094 | doReadRecord = c.config.Bugs.MockQUICTransport.readRecord |
| 1095 | } |
| 1096 | typ, data, err := doReadRecord(want) |
| 1097 | if err != nil { |
| 1098 | return err |
| 1099 | } |
| 1100 | max := maxPlaintext |
| 1101 | if c.config.Bugs.MaxReceivePlaintext != 0 { |
| 1102 | max = c.config.Bugs.MaxReceivePlaintext |
| 1103 | } |
| 1104 | if len(data) > max { |
| 1105 | err := c.sendAlert(alertRecordOverflow) |
| 1106 | return c.in.setErrorLocked(err) |
| 1107 | } |
| 1108 |
| 1109 | if typ != recordTypeHandshake { |
| 1110 | c.seenHandshakePackEnd = false |
| 1111 | } else if c.seenHandshakePackEnd { |
| 1112 | return c.in.setErrorLocked(errors.New("tls: peer violated ExpectPackedEncryptedHandshake")) |
| 1113 | } |
| 1114 |
| 1115 | switch typ { |
| 1116 | default: |
| 1117 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1118 |
| 1119 | case recordTypeAlert: |
| 1120 | if len(data) != 2 { |
| 1121 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1122 | break |
| 1123 | } |
| 1124 | if alert(data[1]) == alertCloseNotify { |
| 1125 | c.in.setErrorLocked(io.EOF) |
| 1126 | break |
| 1127 | } |
| 1128 | switch data[0] { |
| 1129 | case alertLevelWarning: |
| 1130 | // drop on the floor |
| 1131 | goto Again |
| 1132 | case alertLevelError: |
| 1133 | c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) |
| 1134 | default: |
| 1135 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1136 | } |
| 1137 |
| 1138 | case recordTypeChangeCipherSpec: |
| 1139 | if typ != want || len(data) != 1 || data[0] != 1 { |
| 1140 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1141 | break |
| 1142 | } |
| 1143 | if c.hand.Len() != 0 { |
| 1144 | c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change")) |
| 1145 | break |
| 1146 | } |
| 1147 | if c.isDTLS { |
| 1148 | // Track the ChangeCipherSpec record in the current flight. |
| 1149 | c.receivedFlight = append(c.receivedFlight, DTLSMessage{ |
| 1150 | Epoch: c.in.epoch.epoch, |
| 1151 | IsChangeCipherSpec: true, |
| 1152 | Data: slices.Clone(data), |
| 1153 | }) |
| 1154 | } |
| 1155 | if err := c.in.changeCipherSpec(); err != nil { |
| 1156 | c.in.setErrorLocked(c.sendAlert(err.(alert))) |
| 1157 | } |
| 1158 |
| 1159 | case recordTypeApplicationData: |
| 1160 | if typ != want { |
| 1161 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1162 | break |
| 1163 | } |
| 1164 | c.input.Write(data) |
| 1165 |
| 1166 | case recordTypeHandshake: |
| 1167 | // Allow handshake data while reading application data to |
| 1168 | // trigger post-handshake messages. |
| 1169 | // TODO(rsc): Should at least pick off connection close. |
| 1170 | if typ != want && want != recordTypeApplicationData { |
| 1171 | return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation)) |
| 1172 | } |
| 1173 | c.hand.Write(data) |
| 1174 | if pack := c.config.Bugs.ExpectPackedEncryptedHandshake; pack > 0 && len(data) < pack && c.out.epoch.cipher != nil { |
| 1175 | c.seenHandshakePackEnd = true |
| 1176 | } |
| 1177 | if c.isDTLS { |
| 1178 | record, err := c.makeDTLSRecordNumberInfo(&c.in.epoch, c.hand.Bytes()) |
| 1179 | if err != nil { |
| 1180 | return err |
| 1181 | } |
| 1182 | c.receivedFlightRecords = append(c.receivedFlightRecords, record) |
| 1183 | } |
| 1184 |
| 1185 | case recordTypeACK: |
| 1186 | if typ != want || !c.isDTLS { |
| 1187 | c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1188 | break |
| 1189 | } |
| 1190 |
| 1191 | if err := c.checkACK(data); err != nil { |
| 1192 | c.in.setErrorLocked(err) |
| 1193 | break |
| 1194 | } |
| 1195 | } |
| 1196 |
| 1197 | return c.in.err |
| 1198 | } |
| 1199 |
| 1200 | // sendAlert sends a TLS alert message. |
| 1201 | // c.out.Mutex <= L. |
| 1202 | func (c *Conn) sendAlertLocked(level byte, err alert) error { |
| 1203 | c.tmp[0] = level |
| 1204 | c.tmp[1] = byte(err) |
| 1205 | if c.config.Bugs.FragmentAlert { |
| 1206 | c.writeRecord(recordTypeAlert, c.tmp[0:1]) |
| 1207 | c.writeRecord(recordTypeAlert, c.tmp[1:2]) |
| 1208 | } else if c.config.Bugs.DoubleAlert { |
| 1209 | copy(c.tmp[2:4], c.tmp[0:2]) |
| 1210 | c.writeRecord(recordTypeAlert, c.tmp[0:4]) |
| 1211 | } else { |
| 1212 | c.writeRecord(recordTypeAlert, c.tmp[0:2]) |
| 1213 | } |
| 1214 | // Error alerts are fatal to the connection. |
| 1215 | if level == alertLevelError { |
| 1216 | return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) |
| 1217 | } |
| 1218 | return nil |
| 1219 | } |
| 1220 |
| 1221 | // sendAlert sends a TLS alert message. |
| 1222 | // L < c.out.Mutex. |
| 1223 | func (c *Conn) sendAlert(err alert) error { |
| 1224 | level := byte(alertLevelError) |
| 1225 | if err == alertNoRenegotiation || err == alertCloseNotify { |
| 1226 | level = alertLevelWarning |
| 1227 | } |
| 1228 | return c.SendAlert(level, err) |
| 1229 | } |
| 1230 |
| 1231 | func (c *Conn) SendAlert(level byte, err alert) error { |
| 1232 | c.out.Lock() |
| 1233 | defer c.out.Unlock() |
| 1234 | return c.sendAlertLocked(level, err) |
| 1235 | } |
| 1236 |
| 1237 | // writeV2Record writes a record for a V2ClientHello. |
| 1238 | func (c *Conn) writeV2Record(data []byte) (n int, err error) { |
| 1239 | record := make([]byte, 2+len(data)) |
| 1240 | record[0] = uint8(len(data)>>8) | 0x80 |
| 1241 | record[1] = uint8(len(data)) |
| 1242 | copy(record[2:], data) |
| 1243 | return c.conn.Write(record) |
| 1244 | } |
| 1245 |
| 1246 | // writeRecord writes a TLS record with the given type and payload |
| 1247 | // to the connection and updates the record layer state. |
| 1248 | // c.out.Mutex <= L. |
| 1249 | func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { |
| 1250 | c.seenHandshakePackEnd = false |
| 1251 | if c.hand.Len() == 0 { |
| 1252 | c.lastRecordInFlight = nil |
| 1253 | } |
| 1254 | if typ == recordTypeHandshake { |
| 1255 | msgType := data[0] |
| 1256 | if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType { |
| 1257 | msgType += 42 |
| 1258 | } |
| 1259 | if msgType != data[0] { |
| 1260 | data = append([]byte{msgType}, data[1:]...) |
| 1261 | } |
| 1262 |
| 1263 | if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData { |
| 1264 | // Add a 0 to the body. |
| 1265 | newData := make([]byte, len(data)+1) |
| 1266 | copy(newData, data) |
| 1267 |
| 1268 | // Fix the header. |
| 1269 | newLen := len(newData) - 4 |
| 1270 | newData[1] = byte(newLen >> 16) |
| 1271 | newData[2] = byte(newLen >> 8) |
| 1272 | newData[3] = byte(newLen) |
| 1273 |
| 1274 | data = newData |
| 1275 | } |
| 1276 |
| 1277 | if c.config.Bugs.TrailingDataWithFinished && msgType == typeFinished { |
| 1278 | // Add a 0 to the record. Note unused bytes in |data| may be owned by the |
| 1279 | // caller, so we force a new allocation. |
| 1280 | data = append(data[:len(data):len(data)], 0) |
| 1281 | } |
| 1282 | } |
| 1283 |
| 1284 | if c.isDTLS { |
| 1285 | return c.dtlsWriteRecord(typ, data) |
| 1286 | } |
| 1287 | if c.config.Bugs.MockQUICTransport != nil { |
| 1288 | return c.config.Bugs.MockQUICTransport.writeRecord(typ, data) |
| 1289 | } |
| 1290 |
| 1291 | if typ == recordTypeHandshake { |
| 1292 | if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage { |
| 1293 | newData := make([]byte, 0, 4+len(data)) |
| 1294 | newData = append(newData, typeHelloRequest, 0, 0, 0) |
| 1295 | newData = append(newData, data...) |
| 1296 | data = newData |
| 1297 | } |
| 1298 |
| 1299 | if c.config.Bugs.PackHandshakeFlight { |
| 1300 | c.pendingFlight.Write(data) |
| 1301 | return len(data), nil |
| 1302 | } |
| 1303 | } |
| 1304 |
| 1305 | // Flush buffered data before writing anything. |
| 1306 | if err := c.flushHandshake(); err != nil { |
| 1307 | return 0, err |
| 1308 | } |
| 1309 |
| 1310 | if typ == recordTypeApplicationData && c.config.Bugs.SendPostHandshakeChangeCipherSpec { |
| 1311 | if _, err := c.doWriteRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { |
| 1312 | return 0, err |
| 1313 | } |
| 1314 | } |
| 1315 |
| 1316 | return c.doWriteRecord(typ, data) |
| 1317 | } |
| 1318 |
| 1319 | func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) { |
| 1320 | first := true |
| 1321 | for len(data) > 0 || first { |
| 1322 | m := len(data) |
| 1323 | if m > maxPlaintext && !c.config.Bugs.SendLargeRecords { |
| 1324 | m = maxPlaintext |
| 1325 | } |
| 1326 | if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength { |
| 1327 | m = c.config.Bugs.MaxHandshakeRecordLength |
| 1328 | } |
| 1329 | first = false |
| 1330 |
| 1331 | // Determine record version. |
| 1332 | vers := c.vers |
| 1333 | if vers == 0 { |
| 1334 | // Some TLS servers fail if the record version is |
| 1335 | // greater than TLS 1.0 for the initial ClientHello. |
| 1336 | // |
| 1337 | // TLS 1.3 fixes the version number in the record |
| 1338 | // layer to {3, 1}. |
| 1339 | vers = VersionTLS10 |
| 1340 | } |
| 1341 | if c.vers >= VersionTLS13 || c.out.version >= VersionTLS13 { |
| 1342 | vers = VersionTLS12 |
| 1343 | } |
| 1344 | if c.config.Bugs.SendRecordVersion != 0 { |
| 1345 | vers = c.config.Bugs.SendRecordVersion |
| 1346 | } |
| 1347 | if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 { |
| 1348 | vers = c.config.Bugs.SendInitialRecordVersion |
| 1349 | } |
| 1350 |
| 1351 | // Assemble the record header. |
| 1352 | epoch := &c.out.epoch |
| 1353 | record := make([]byte, tlsRecordHeaderLen, tlsRecordHeaderLen+m+c.out.maxEncryptOverhead(epoch, m)) |
| 1354 | record[0] = byte(typ) |
| 1355 | if c.vers >= VersionTLS13 && epoch.cipher != nil { |
| 1356 | record[0] = byte(recordTypeApplicationData) |
| 1357 | if outerType := c.config.Bugs.OuterRecordType; outerType != 0 { |
| 1358 | record[0] = byte(outerType) |
| 1359 | } |
| 1360 | } |
| 1361 | record[1] = byte(vers >> 8) |
| 1362 | record[2] = byte(vers) |
| 1363 | record[3] = byte(m >> 8) // encrypt will update this |
| 1364 | record[4] = byte(m) |
| 1365 |
| 1366 | record, err = c.out.encrypt(epoch, record, data[:m], typ, tlsRecordHeaderLen, true /* header has length */) |
| 1367 | if err != nil { |
| 1368 | return |
| 1369 | } |
| 1370 | _, err = c.conn.Write(record) |
| 1371 | if err != nil { |
| 1372 | break |
| 1373 | } |
| 1374 | n += m |
| 1375 | data = data[m:] |
| 1376 | } |
| 1377 |
| 1378 | if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 { |
| 1379 | err = c.out.changeCipherSpec() |
| 1380 | if err != nil { |
| 1381 | return n, c.sendAlertLocked(alertLevelError, err.(alert)) |
| 1382 | } |
| 1383 | } |
| 1384 | return |
| 1385 | } |
| 1386 |
| 1387 | func (c *Conn) flushHandshake() error { |
| 1388 | if c.isDTLS { |
| 1389 | return c.dtlsFlushHandshake() |
| 1390 | } |
| 1391 |
| 1392 | for c.pendingFlight.Len() > 0 { |
| 1393 | var buf [maxPlaintext]byte |
| 1394 | n, _ := c.pendingFlight.Read(buf[:]) |
| 1395 | if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil { |
| 1396 | return err |
| 1397 | } |
| 1398 | } |
| 1399 |
| 1400 | c.pendingFlight.Reset() |
| 1401 | return nil |
| 1402 | } |
| 1403 |
| 1404 | func (c *Conn) ackHandshake() error { |
| 1405 | if c.isDTLS { |
| 1406 | return c.dtlsACKHandshake() |
| 1407 | } |
| 1408 | return nil |
| 1409 | } |
| 1410 |
| 1411 | func (c *Conn) doReadHandshake() ([]byte, error) { |
| 1412 | if c.isDTLS { |
| 1413 | return c.dtlsDoReadHandshake() |
| 1414 | } |
| 1415 |
| 1416 | for c.hand.Len() < 4 { |
| 1417 | if err := c.in.err; err != nil { |
| 1418 | return nil, err |
| 1419 | } |
| 1420 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 1421 | return nil, err |
| 1422 | } |
| 1423 | } |
| 1424 |
| 1425 | data := c.hand.Bytes() |
| 1426 | n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) |
| 1427 | if n > maxHandshake { |
| 1428 | return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) |
| 1429 | } |
| 1430 | for c.hand.Len() < 4+n { |
| 1431 | if err := c.in.err; err != nil { |
| 1432 | return nil, err |
| 1433 | } |
| 1434 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 1435 | return nil, err |
| 1436 | } |
| 1437 | } |
| 1438 | return c.hand.Next(4 + n), nil |
| 1439 | } |
| 1440 |
| 1441 | // readHandshake reads the next handshake message from |
| 1442 | // the record layer. |
| 1443 | // c.in.Mutex < L; c.out.Mutex < L. |
| 1444 | func (c *Conn) readHandshake() (any, error) { |
| 1445 | data, err := c.doReadHandshake() |
| 1446 | if err != nil { |
| 1447 | return nil, err |
| 1448 | } |
| 1449 |
| 1450 | typ := data[0] |
| 1451 | var m handshakeMessage |
| 1452 | switch typ { |
| 1453 | case typeHelloRequest: |
| 1454 | m = new(helloRequestMsg) |
| 1455 | case typeClientHello: |
| 1456 | m = &clientHelloMsg{ |
| 1457 | isDTLS: c.isDTLS, |
| 1458 | } |
| 1459 | case typeServerHello: |
| 1460 | m = &serverHelloMsg{ |
| 1461 | isDTLS: c.isDTLS, |
| 1462 | } |
| 1463 | case typeNewSessionTicket: |
| 1464 | m = &newSessionTicketMsg{ |
| 1465 | vers: c.wireVersion, |
| 1466 | isDTLS: c.isDTLS, |
| 1467 | } |
| 1468 | case typeEncryptedExtensions: |
| 1469 | if c.isClient { |
| 1470 | m = new(encryptedExtensionsMsg) |
| 1471 | } else { |
| 1472 | m = new(clientEncryptedExtensionsMsg) |
| 1473 | } |
| 1474 | case typeCertificate: |
| 1475 | m = &certificateMsg{ |
| 1476 | hasRequestContext: c.vers >= VersionTLS13, |
| 1477 | } |
| 1478 | case typeCompressedCertificate: |
| 1479 | m = new(compressedCertificateMsg) |
| 1480 | case typeCertificateRequest: |
| 1481 | m = &certificateRequestMsg{ |
| 1482 | vers: c.wireVersion, |
| 1483 | hasSignatureAlgorithm: c.vers >= VersionTLS12, |
| 1484 | hasRequestContext: c.vers >= VersionTLS13, |
| 1485 | } |
| 1486 | case typeCertificateStatus: |
| 1487 | m = new(certificateStatusMsg) |
| 1488 | case typeServerKeyExchange: |
| 1489 | m = new(serverKeyExchangeMsg) |
| 1490 | case typeServerHelloDone: |
| 1491 | m = new(serverHelloDoneMsg) |
| 1492 | case typeClientKeyExchange: |
| 1493 | m = new(clientKeyExchangeMsg) |
| 1494 | case typeCertificateVerify: |
| 1495 | m = &certificateVerifyMsg{ |
| 1496 | hasSignatureAlgorithm: c.vers >= VersionTLS12, |
| 1497 | } |
| 1498 | case typeNextProtocol: |
| 1499 | m = new(nextProtoMsg) |
| 1500 | case typeFinished: |
| 1501 | m = new(finishedMsg) |
| 1502 | case typeHelloVerifyRequest: |
| 1503 | m = new(helloVerifyRequestMsg) |
| 1504 | case typeChannelID: |
| 1505 | m = new(channelIDMsg) |
| 1506 | case typeKeyUpdate: |
| 1507 | m = new(keyUpdateMsg) |
| 1508 | case typeEndOfEarlyData: |
| 1509 | m = new(endOfEarlyDataMsg) |
| 1510 | default: |
| 1511 | return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) |
| 1512 | } |
| 1513 |
| 1514 | // The handshake message unmarshallers |
| 1515 | // expect to be able to keep references to data, |
| 1516 | // so pass in a fresh copy that won't be overwritten. |
| 1517 | data = slices.Clone(data) |
| 1518 |
| 1519 | if data[0] == typeServerHello && len(data) >= 38 { |
| 1520 | vers := uint16(data[4])<<8 | uint16(data[5]) |
| 1521 | if (vers == VersionDTLS12 || vers == VersionTLS12) && bytes.Equal(data[6:38], tls13HelloRetryRequest) { |
| 1522 | m = &helloRetryRequestMsg{isDTLS: c.isDTLS} |
| 1523 | } |
| 1524 | } |
| 1525 |
| 1526 | if !m.unmarshal(data) { |
| 1527 | c.sendAlert(alertDecodeError) |
| 1528 | return nil, c.in.setErrorLocked(fmt.Errorf("tls: error decoding %s message", messageTypeToString(typ))) |
| 1529 | } |
| 1530 | return m, nil |
| 1531 | } |
| 1532 |
| 1533 | func readHandshakeType[T any](c *Conn) (*T, error) { |
| 1534 | m, err := c.readHandshake() |
| 1535 | if err != nil { |
| 1536 | return nil, err |
| 1537 | } |
| 1538 | mType, ok := m.(*T) |
| 1539 | if !ok { |
| 1540 | c.sendAlert(alertUnexpectedMessage) |
| 1541 | return nil, unexpectedMessageError(mType, m) |
| 1542 | } |
| 1543 | return mType, nil |
| 1544 | } |
| 1545 |
| 1546 | func (c *Conn) SendHalfHelloRequest() error { |
| 1547 | if err := c.Handshake(); err != nil { |
| 1548 | return err |
| 1549 | } |
| 1550 |
| 1551 | c.out.Lock() |
| 1552 | defer c.out.Unlock() |
| 1553 |
| 1554 | if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil { |
| 1555 | return err |
| 1556 | } |
| 1557 | return c.flushHandshake() |
| 1558 | } |
| 1559 |
| 1560 | // Write writes data to the connection. |
| 1561 | func (c *Conn) Write(b []byte) (int, error) { |
| 1562 | if err := c.Handshake(); err != nil { |
| 1563 | return 0, err |
| 1564 | } |
| 1565 |
| 1566 | c.out.Lock() |
| 1567 | defer c.out.Unlock() |
| 1568 |
| 1569 | if err := c.out.err; err != nil { |
| 1570 | return 0, err |
| 1571 | } |
| 1572 |
| 1573 | if !c.handshakeComplete { |
| 1574 | return 0, alertInternalError |
| 1575 | } |
| 1576 |
| 1577 | if c.keyUpdateRequested { |
| 1578 | if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil { |
| 1579 | return 0, err |
| 1580 | } |
| 1581 | c.keyUpdateRequested = false |
| 1582 | } |
| 1583 |
| 1584 | if c.config.Bugs.SendSpuriousAlert != 0 { |
| 1585 | c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert) |
| 1586 | } |
| 1587 |
| 1588 | if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord { |
| 1589 | c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0}) |
| 1590 | c.flushHandshake() |
| 1591 | } |
| 1592 |
| 1593 | // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext |
| 1594 | // attack when using block mode ciphers due to predictable IVs. |
| 1595 | // This can be prevented by splitting each Application Data |
| 1596 | // record into two records, effectively randomizing the IV. |
| 1597 | // |
| 1598 | // http://www.openssl.org/~bodo/tls-cbc.txt |
| 1599 | // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 |
| 1600 | // http://www.imperialviolet.org/2012/01/15/beastfollowup.html |
| 1601 |
| 1602 | var m int |
| 1603 | if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS { |
| 1604 | if _, ok := c.out.epoch.cipher.(*cbcMode); ok { |
| 1605 | n, err := c.writeRecord(recordTypeApplicationData, b[:1]) |
| 1606 | if err != nil { |
| 1607 | return n, c.out.setErrorLocked(err) |
| 1608 | } |
| 1609 | m, b = 1, b[1:] |
| 1610 | } |
| 1611 | } |
| 1612 |
| 1613 | n, err := c.writeRecord(recordTypeApplicationData, b) |
| 1614 | return n + m, c.out.setErrorLocked(err) |
| 1615 | } |
| 1616 |
| 1617 | func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error { |
| 1618 | session := &ClientSessionState{ |
| 1619 | sessionTicket: newSessionTicket.ticket, |
| 1620 | vers: c.vers, |
| 1621 | wireVersion: c.wireVersion, |
| 1622 | cipherSuite: cipherSuite, |
| 1623 | secret: deriveSessionPSK(cipherSuite, c.wireVersion, c.resumptionSecret, newSessionTicket.ticketNonce, c.isDTLS), |
| 1624 | serverCertificates: c.peerCertificates, |
| 1625 | sctList: c.sctList, |
| 1626 | ocspResponse: c.ocspResponse, |
| 1627 | ticketCreationTime: c.config.time(), |
| 1628 | ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second), |
| 1629 | ticketAgeAdd: newSessionTicket.ticketAgeAdd, |
| 1630 | maxEarlyDataSize: newSessionTicket.maxEarlyDataSize, |
| 1631 | earlyALPN: c.clientProtocol, |
| 1632 | hasApplicationSettings: c.hasApplicationSettings, |
| 1633 | localApplicationSettings: c.localApplicationSettings, |
| 1634 | peerApplicationSettings: c.peerApplicationSettings, |
| 1635 | hasApplicationSettingsOld: c.hasApplicationSettingsOld, |
| 1636 | localApplicationSettingsOld: c.localApplicationSettingsOld, |
| 1637 | peerApplicationSettingsOld: c.peerApplicationSettingsOld, |
| 1638 | resumptionAcrossNames: newSessionTicket.flags.hasFlag(flagResumptionAcrossNames), |
| 1639 | } |
| 1640 |
| 1641 | if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension { |
| 1642 | return errors.New("tls: no GREASE ticket extension found") |
| 1643 | } |
| 1644 |
| 1645 | if c.config.Bugs.ExpectTicketEarlyData && newSessionTicket.maxEarlyDataSize == 0 { |
| 1646 | return errors.New("tls: no early_data ticket extension found") |
| 1647 | } |
| 1648 |
| 1649 | if c.config.Bugs.ExpectNoNewSessionTicket || c.config.Bugs.ExpectNoNonEmptyNewSessionTicket { |
| 1650 | return errors.New("tls: received unexpected NewSessionTicket") |
| 1651 | } |
| 1652 |
| 1653 | if expect := c.config.Bugs.ExpectResumptionAcrossNames; expect != nil && session.resumptionAcrossNames != *expect { |
| 1654 | return errors.New("tls: resumption_across_names status of ticket did not match expectation") |
| 1655 | } |
| 1656 |
| 1657 | if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 { |
| 1658 | return nil |
| 1659 | } |
| 1660 |
| 1661 | cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) |
| 1662 | _, ok := c.config.ClientSessionCache.Get(cacheKey) |
| 1663 | if !ok || !c.config.Bugs.UseFirstSessionTicket { |
| 1664 | c.config.ClientSessionCache.Put(cacheKey, session) |
| 1665 | } |
| 1666 |
| 1667 | return c.ackHandshake() |
| 1668 | } |
| 1669 |
| 1670 | func (c *Conn) processKeyUpdate(keyUpdate *keyUpdateMsg) error { |
| 1671 | epoch := c.in.epoch.epoch + 1 |
| 1672 | if epoch == 0 && !c.config.Bugs.AllowEpochOverflow { |
| 1673 | return errors.New("tls: too many KeyUpdates") |
| 1674 | } |
| 1675 | if err := c.useInTrafficSecret(epoch, c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret, c.isDTLS)); err != nil { |
| 1676 | return err |
| 1677 | } |
| 1678 | if keyUpdate.keyUpdateRequest == keyUpdateRequested { |
| 1679 | c.keyUpdateRequested = true |
| 1680 | } |
| 1681 | return c.ackHandshake() |
| 1682 | } |
| 1683 |
| 1684 | func (c *Conn) handlePostHandshakeMessage() error { |
| 1685 | msg, err := c.readHandshake() |
| 1686 | if err != nil { |
| 1687 | return err |
| 1688 | } |
| 1689 |
| 1690 | if c.vers < VersionTLS13 { |
| 1691 | if !c.isClient { |
| 1692 | c.sendAlert(alertUnexpectedMessage) |
| 1693 | return errors.New("tls: unexpected post-handshake message") |
| 1694 | } |
| 1695 |
| 1696 | _, ok := msg.(*helloRequestMsg) |
| 1697 | if !ok { |
| 1698 | c.sendAlert(alertUnexpectedMessage) |
| 1699 | return alertUnexpectedMessage |
| 1700 | } |
| 1701 |
| 1702 | c.handshakeComplete = false |
| 1703 | return c.Handshake() |
| 1704 | } |
| 1705 |
| 1706 | if c.isClient { |
| 1707 | if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok { |
| 1708 | return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite) |
| 1709 | } |
| 1710 | } |
| 1711 |
| 1712 | if keyUpdate, ok := msg.(*keyUpdateMsg); ok { |
| 1713 | c.keyUpdateSeen = true |
| 1714 | if c.config.Bugs.RejectUnsolicitedKeyUpdate { |
| 1715 | return errors.New("tls: unexpected KeyUpdate message") |
| 1716 | } |
| 1717 | return c.processKeyUpdate(keyUpdate) |
| 1718 | } |
| 1719 |
| 1720 | c.sendAlert(alertUnexpectedMessage) |
| 1721 | return errors.New("tls: unexpected post-handshake message") |
| 1722 | } |
| 1723 |
| 1724 | // Reads a KeyUpdate from the peer, with type key_update_not_requested. There |
| 1725 | // may not be any application data records before the message. |
| 1726 | func (c *Conn) ReadKeyUpdate() error { |
| 1727 | c.in.Lock() |
| 1728 | defer c.in.Unlock() |
| 1729 |
| 1730 | keyUpdate, err := readHandshakeType[keyUpdateMsg](c) |
| 1731 | if err != nil { |
| 1732 | return err |
| 1733 | } |
| 1734 |
| 1735 | if keyUpdate.keyUpdateRequest != keyUpdateNotRequested { |
| 1736 | return errors.New("tls: received invalid KeyUpdate message") |
| 1737 | } |
| 1738 |
| 1739 | return c.processKeyUpdate(keyUpdate) |
| 1740 | } |
| 1741 |
| 1742 | func (c *Conn) Renegotiate() error { |
| 1743 | if !c.isClient { |
| 1744 | helloReq := new(helloRequestMsg).marshal() |
| 1745 | if c.config.Bugs.BadHelloRequest != nil { |
| 1746 | helloReq = c.config.Bugs.BadHelloRequest |
| 1747 | } |
| 1748 | c.writeRecord(recordTypeHandshake, helloReq) |
| 1749 | c.flushHandshake() |
| 1750 | } |
| 1751 |
| 1752 | c.handshakeComplete = false |
| 1753 | return c.Handshake() |
| 1754 | } |
| 1755 |
| 1756 | // Read can be made to time out and return a net.Error with Timeout() == true |
| 1757 | // after a fixed time limit; see SetDeadline and SetReadDeadline. |
| 1758 | func (c *Conn) Read(b []byte) (n int, err error) { |
| 1759 | if err = c.Handshake(); err != nil { |
| 1760 | return |
| 1761 | } |
| 1762 |
| 1763 | c.in.Lock() |
| 1764 | defer c.in.Unlock() |
| 1765 |
| 1766 | // Some OpenSSL servers send empty records in order to randomize the |
| 1767 | // CBC IV. So this loop ignores a limited number of empty records. |
| 1768 | const maxConsecutiveEmptyRecords = 100 |
| 1769 | for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ { |
| 1770 | for c.input.Len() == 0 && c.in.err == nil { |
| 1771 | if err := c.readRecord(recordTypeApplicationData); err != nil { |
| 1772 | // Soft error, like EAGAIN |
| 1773 | return 0, err |
| 1774 | } |
| 1775 | for c.hand.Len() > 0 { |
| 1776 | // We received handshake bytes, indicating a |
| 1777 | // post-handshake message. |
| 1778 | if err := c.handlePostHandshakeMessage(); err != nil { |
| 1779 | return 0, err |
| 1780 | } |
| 1781 | } |
| 1782 | } |
| 1783 | if err := c.in.err; err != nil { |
| 1784 | return 0, err |
| 1785 | } |
| 1786 |
| 1787 | n, err = c.input.Read(b) |
| 1788 | if c.input.Len() == 0 || c.isDTLS { |
| 1789 | c.input.Reset() |
| 1790 | } |
| 1791 |
| 1792 | // If a close-notify alert is waiting, read it so that |
| 1793 | // we can return (n, EOF) instead of (n, nil), to signal |
| 1794 | // to the HTTP response reading goroutine that the |
| 1795 | // connection is now closed. This eliminates a race |
| 1796 | // where the HTTP response reading goroutine would |
| 1797 | // otherwise not observe the EOF until its next read, |
| 1798 | // by which time a client goroutine might have already |
| 1799 | // tried to reuse the HTTP connection for a new |
| 1800 | // request. |
| 1801 | // See https://codereview.appspot.com/76400046 |
| 1802 | // and http://golang.org/issue/3514 |
| 1803 | if ri := c.rawInput.Bytes(); !c.isDTLS && n != 0 && err == nil && |
| 1804 | c.input.Len() == 0 && len(ri) > 0 && recordType(ri[0]) == recordTypeAlert { |
| 1805 | if recErr := c.readRecord(recordTypeApplicationData); recErr != nil { |
| 1806 | err = recErr // will be io.EOF on closeNotify |
| 1807 | } |
| 1808 | } |
| 1809 |
| 1810 | if n != 0 || err != nil { |
| 1811 | return n, err |
| 1812 | } |
| 1813 | } |
| 1814 |
| 1815 | return 0, io.ErrNoProgress |
| 1816 | } |
| 1817 |
| 1818 | // Close closes the connection. |
| 1819 | func (c *Conn) Close() error { |
| 1820 | var alertErr error |
| 1821 |
| 1822 | c.handshakeMutex.Lock() |
| 1823 | defer c.handshakeMutex.Unlock() |
| 1824 | if c.handshakeComplete && !c.config.Bugs.NoCloseNotify { |
| 1825 | alert := alertCloseNotify |
| 1826 | if c.config.Bugs.SendAlertOnShutdown != 0 { |
| 1827 | alert = c.config.Bugs.SendAlertOnShutdown |
| 1828 | } |
| 1829 | alertErr = c.sendAlert(alert) |
| 1830 | // Clear local alerts when sending alerts so we continue to wait |
| 1831 | // for the peer rather than closing the socket early. |
| 1832 | if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" { |
| 1833 | alertErr = nil |
| 1834 | } |
| 1835 | } |
| 1836 |
| 1837 | // Consume a close_notify from the peer if one hasn't been received |
| 1838 | // already. This avoids the peer from failing |SSL_shutdown| due to a |
| 1839 | // write failing. |
| 1840 | if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify { |
| 1841 | for c.in.error() == nil { |
| 1842 | c.readRecord(recordTypeAlert) |
| 1843 | } |
| 1844 | if c.in.error() != io.EOF { |
| 1845 | alertErr = c.in.error() |
| 1846 | } |
| 1847 | } |
| 1848 |
| 1849 | if err := c.conn.Close(); err != nil { |
| 1850 | return err |
| 1851 | } |
| 1852 | return alertErr |
| 1853 | } |
| 1854 |
| 1855 | // Handshake runs the client or server handshake |
| 1856 | // protocol if it has not yet been run. |
| 1857 | // Most uses of this package need not call Handshake |
| 1858 | // explicitly: the first Read or Write will call it automatically. |
| 1859 | func (c *Conn) Handshake() error { |
| 1860 | c.handshakeMutex.Lock() |
| 1861 | defer c.handshakeMutex.Unlock() |
| 1862 | if err := c.handshakeErr; err != nil { |
| 1863 | return err |
| 1864 | } |
| 1865 | if c.handshakeComplete { |
| 1866 | return nil |
| 1867 | } |
| 1868 |
| 1869 | if c.isDTLS && c.config.Bugs.SendSplitAlert { |
| 1870 | c.conn.Write([]byte{ |
| 1871 | byte(recordTypeAlert), // type |
| 1872 | 0xfe, 0xff, // version |
| 1873 | 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence |
| 1874 | 0x0, 0x2, // length |
| 1875 | }) |
| 1876 | c.conn.Write([]byte{alertLevelError, byte(alertInternalError)}) |
| 1877 | } |
| 1878 | if data := c.config.Bugs.AppDataBeforeHandshake; data != nil { |
| 1879 | c.writeRecord(recordTypeApplicationData, data) |
| 1880 | } |
| 1881 | if c.isClient { |
| 1882 | c.handshakeErr = c.clientHandshake() |
| 1883 | } else { |
| 1884 | c.handshakeErr = c.serverHandshake() |
| 1885 | } |
| 1886 | if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType { |
| 1887 | c.writeRecord(recordType(42), []byte("invalid record")) |
| 1888 | } |
| 1889 | return c.handshakeErr |
| 1890 | } |
| 1891 |
| 1892 | // ConnectionState returns basic TLS details about the connection. |
| 1893 | func (c *Conn) ConnectionState() ConnectionState { |
| 1894 | c.handshakeMutex.Lock() |
| 1895 | defer c.handshakeMutex.Unlock() |
| 1896 |
| 1897 | var state ConnectionState |
| 1898 | state.HandshakeComplete = c.handshakeComplete |
| 1899 | if c.handshakeComplete { |
| 1900 | state.Version = c.vers |
| 1901 | state.NegotiatedProtocol = c.clientProtocol |
| 1902 | state.DidResume = c.didResume |
| 1903 | state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback |
| 1904 | state.NegotiatedProtocolFromALPN = c.usedALPN |
| 1905 | state.CipherSuite = c.cipherSuite.id |
| 1906 | state.PeerCertificates = c.peerCertificates |
| 1907 | state.PeerDelegatedCredential = c.peerDelegatedCredential |
| 1908 | state.VerifiedChains = c.verifiedChains |
| 1909 | state.OCSPResponse = c.ocspResponse |
| 1910 | state.ServerName = c.serverName |
| 1911 | state.ChannelID = c.channelID |
| 1912 | state.SRTPProtectionProfile = c.srtpProtectionProfile |
| 1913 | state.TLSUnique = c.firstFinished[:] |
| 1914 | state.SCTList = c.sctList |
| 1915 | state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm |
| 1916 | state.CurveID = c.curveID |
| 1917 | state.QUICTransportParams = c.quicTransportParams |
| 1918 | state.QUICTransportParamsLegacy = c.quicTransportParamsLegacy |
| 1919 | state.HasApplicationSettings = c.hasApplicationSettings |
| 1920 | state.PeerApplicationSettings = c.peerApplicationSettings |
| 1921 | state.HasApplicationSettingsOld = c.hasApplicationSettingsOld |
| 1922 | state.PeerApplicationSettingsOld = c.peerApplicationSettingsOld |
| 1923 | state.ECHAccepted = c.echAccepted |
| 1924 | } |
| 1925 |
| 1926 | return state |
| 1927 | } |
| 1928 |
| 1929 | // VerifyHostname checks that the peer certificate chain is valid for |
| 1930 | // connecting to host. If so, it returns nil; if not, it returns an error |
| 1931 | // describing the problem. |
| 1932 | func (c *Conn) VerifyHostname(host string) error { |
| 1933 | c.handshakeMutex.Lock() |
| 1934 | defer c.handshakeMutex.Unlock() |
| 1935 | if !c.isClient { |
| 1936 | return errors.New("tls: VerifyHostname called on TLS server connection") |
| 1937 | } |
| 1938 | if !c.handshakeComplete { |
| 1939 | return errors.New("tls: handshake has not yet been performed") |
| 1940 | } |
| 1941 | return c.peerCertificates[0].VerifyHostname(host) |
| 1942 | } |
| 1943 |
| 1944 | func (c *Conn) exportKeyingMaterialTLS13(length int, secret, label, context []byte) []byte { |
| 1945 | hash := c.cipherSuite.hash() |
| 1946 | exporterKeyingLabel := []byte("exporter") |
| 1947 | contextHash := hash.New() |
| 1948 | contextHash.Write(context) |
| 1949 | exporterContext := hash.New().Sum(nil) |
| 1950 | derivedSecret := hkdfExpandLabel(c.cipherSuite.hash(), secret, label, exporterContext, hash.Size(), c.isDTLS) |
| 1951 | return hkdfExpandLabel(c.cipherSuite.hash(), derivedSecret, exporterKeyingLabel, contextHash.Sum(nil), length, c.isDTLS) |
| 1952 | } |
| 1953 |
| 1954 | // ExportKeyingMaterial exports keying material from the current connection |
| 1955 | // state, as per RFC 5705. |
| 1956 | func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) { |
| 1957 | c.handshakeMutex.Lock() |
| 1958 | defer c.handshakeMutex.Unlock() |
| 1959 | if !c.handshakeComplete { |
| 1960 | return nil, errors.New("tls: handshake has not yet been performed") |
| 1961 | } |
| 1962 |
| 1963 | if c.vers >= VersionTLS13 { |
| 1964 | return c.exportKeyingMaterialTLS13(length, c.exporterSecret, label, context), nil |
| 1965 | } |
| 1966 |
| 1967 | seedLen := len(c.clientRandom) + len(c.serverRandom) |
| 1968 | if useContext { |
| 1969 | seedLen += 2 + len(context) |
| 1970 | } |
| 1971 | seed := make([]byte, 0, seedLen) |
| 1972 | seed = append(seed, c.clientRandom[:]...) |
| 1973 | seed = append(seed, c.serverRandom[:]...) |
| 1974 | if useContext { |
| 1975 | seed = append(seed, byte(len(context)>>8), byte(len(context))) |
| 1976 | seed = append(seed, context...) |
| 1977 | } |
| 1978 | result := make([]byte, length) |
| 1979 | prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed) |
| 1980 | return result, nil |
| 1981 | } |
| 1982 |
| 1983 | func (c *Conn) ExportEarlyKeyingMaterial(length int, label, context []byte) ([]byte, error) { |
| 1984 | if c.vers < VersionTLS13 { |
| 1985 | return nil, errors.New("tls: early exporters not defined before TLS 1.3") |
| 1986 | } |
| 1987 |
| 1988 | if c.earlyExporterSecret == nil { |
| 1989 | return nil, errors.New("tls: no early exporter secret") |
| 1990 | } |
| 1991 |
| 1992 | return c.exportKeyingMaterialTLS13(length, c.earlyExporterSecret, label, context), nil |
| 1993 | } |
| 1994 |
| 1995 | // noRenegotiationInfo returns true if the renegotiation info extension |
| 1996 | // should be supported in the current handshake. |
| 1997 | func (c *Conn) noRenegotiationInfo() bool { |
| 1998 | if c.config.Bugs.NoRenegotiationInfo { |
| 1999 | return true |
| 2000 | } |
| 2001 | if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial { |
| 2002 | return true |
| 2003 | } |
| 2004 | if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial { |
| 2005 | return true |
| 2006 | } |
| 2007 | return false |
| 2008 | } |
| 2009 |
| 2010 | func (c *Conn) SendNewSessionTicket(nonce []byte) error { |
| 2011 | if c.isClient || c.vers < VersionTLS13 { |
| 2012 | return errors.New("tls: cannot send post-handshake NewSessionTicket") |
| 2013 | } |
| 2014 |
| 2015 | var peerCertificatesRaw [][]byte |
| 2016 | for _, cert := range c.peerCertificates { |
| 2017 | peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw) |
| 2018 | } |
| 2019 |
| 2020 | addBuffer := make([]byte, 4) |
| 2021 | _, err := io.ReadFull(c.config.rand(), addBuffer) |
| 2022 | if err != nil { |
| 2023 | c.sendAlert(alertInternalError) |
| 2024 | return errors.New("tls: short read from Rand: " + err.Error()) |
| 2025 | } |
| 2026 | ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]) |
| 2027 |
| 2028 | // TODO(davidben): Allow configuring these values. |
| 2029 | m := &newSessionTicketMsg{ |
| 2030 | vers: c.wireVersion, |
| 2031 | isDTLS: c.isDTLS, |
| 2032 | ticketLifetime: uint32(24 * time.Hour / time.Second), |
| 2033 | duplicateEarlyDataExtension: c.config.Bugs.DuplicateTicketEarlyData, |
| 2034 | customExtension: c.config.Bugs.CustomTicketExtension, |
| 2035 | ticketAgeAdd: ticketAgeAdd, |
| 2036 | ticketNonce: nonce, |
| 2037 | maxEarlyDataSize: c.config.MaxEarlyDataSize, |
| 2038 | flags: flagSet{ |
| 2039 | mustInclude: c.config.Bugs.AlwaysSendTicketFlags, |
| 2040 | padding: c.config.Bugs.TicketFlagPadding, |
| 2041 | }, |
| 2042 | } |
| 2043 | if c.config.Bugs.MockQUICTransport != nil && m.maxEarlyDataSize > 0 { |
| 2044 | m.maxEarlyDataSize = 0xffffffff |
| 2045 | } |
| 2046 |
| 2047 | if c.config.Bugs.SendTicketLifetime != 0 { |
| 2048 | m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second) |
| 2049 | } |
| 2050 | if c.config.ResumptionAcrossNames { |
| 2051 | m.flags.setFlag(flagResumptionAcrossNames) |
| 2052 | } |
| 2053 | for _, flag := range c.config.Bugs.SendTicketFlags { |
| 2054 | m.flags.setFlag(flag) |
| 2055 | } |
| 2056 |
| 2057 | state := sessionState{ |
| 2058 | vers: c.vers, |
| 2059 | cipherSuite: c.cipherSuite.id, |
| 2060 | secret: deriveSessionPSK(c.cipherSuite, c.wireVersion, c.resumptionSecret, nonce, c.isDTLS), |
| 2061 | certificates: peerCertificatesRaw, |
| 2062 | ticketCreationTime: c.config.time(), |
| 2063 | ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second), |
| 2064 | ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]), |
| 2065 | earlyALPN: []byte(c.clientProtocol), |
| 2066 | hasApplicationSettings: c.hasApplicationSettings, |
| 2067 | localApplicationSettings: c.localApplicationSettings, |
| 2068 | peerApplicationSettings: c.peerApplicationSettings, |
| 2069 | hasApplicationSettingsOld: c.hasApplicationSettingsOld, |
| 2070 | localApplicationSettingsOld: c.localApplicationSettingsOld, |
| 2071 | peerApplicationSettingsOld: c.peerApplicationSettingsOld, |
| 2072 | } |
| 2073 |
| 2074 | if !c.config.Bugs.SendEmptySessionTicket { |
| 2075 | var err error |
| 2076 | m.ticket, err = c.encryptTicket(&state) |
| 2077 | if err != nil { |
| 2078 | return err |
| 2079 | } |
| 2080 | } |
| 2081 | c.out.Lock() |
| 2082 | defer c.out.Unlock() |
| 2083 | _, err = c.writeRecord(recordTypeHandshake, m.marshal()) |
| 2084 | return err |
| 2085 | } |
| 2086 |
| 2087 | func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error { |
| 2088 | c.out.Lock() |
| 2089 | defer c.out.Unlock() |
| 2090 | return c.sendKeyUpdateLocked(keyUpdateRequest) |
| 2091 | } |
| 2092 |
| 2093 | func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error { |
| 2094 | if c.vers < VersionTLS13 { |
| 2095 | return errors.New("tls: attempted to send KeyUpdate before TLS 1.3") |
| 2096 | } |
| 2097 | epoch := c.out.epoch.epoch + 1 |
| 2098 | if epoch == 0 && !c.config.Bugs.AllowEpochOverflow { |
| 2099 | return errors.New("tls: too many KeyUpdates") |
| 2100 | } |
| 2101 |
| 2102 | m := keyUpdateMsg{ |
| 2103 | keyUpdateRequest: keyUpdateRequest, |
| 2104 | } |
| 2105 | if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { |
| 2106 | return err |
| 2107 | } |
| 2108 | // In DTLS 1.3, a real implementation would not install the new epoch until |
| 2109 | // receiving an ACK. Our test transport is ordered and reliable, so this is |
| 2110 | // not necessary. ACK effects will be simulated in tests by the WriteFlight |
| 2111 | // callback. |
| 2112 | c.useOutTrafficSecret(epoch, c.out.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.out.trafficSecret, c.isDTLS)) |
| 2113 | return c.flushHandshake() |
| 2114 | } |
| 2115 |
| 2116 | func (c *Conn) sendFakeEarlyData(len int) error { |
| 2117 | // Assemble a fake early data record. This does not use writeRecord |
| 2118 | // because the record layer may be using different keys at this point. |
| 2119 | payload := make([]byte, 5+len) |
| 2120 | payload[0] = byte(recordTypeApplicationData) |
| 2121 | payload[1] = 3 |
| 2122 | payload[2] = 3 |
| 2123 | payload[3] = byte(len >> 8) |
| 2124 | payload[4] = byte(len) |
| 2125 | _, err := c.conn.Write(payload) |
| 2126 | return err |
| 2127 | } |
| 2128 |
| 2129 | func (c *Conn) usesEndOfEarlyData() bool { |
| 2130 | if c.isClient && c.config.Bugs.SendEndOfEarlyDataInQUICAndDTLS { |
| 2131 | return true |
| 2132 | } |
| 2133 | return c.config.Bugs.MockQUICTransport == nil && !c.isDTLS |
| 2134 | } |
| 2135 |