| 6 |
| // |
| 7 | // NOTE: This is a not even a remotely production-quality DTLS |
| 8 | // implementation. It is the bare minimum necessary to be able to |
| 9 | // achieve coverage on BoringSSL's implementation. Of note is that |
| 10 | // this implementation assumes the underlying net.PacketConn is not |
| 11 | // only reliable but also ordered. BoringSSL will be expected to deal |
| 12 | // with simulated loss, but there is no point in forcing the test |
| 13 | // driver to. |
| 14 |
| 15 | package runner |
| 16 |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "cmp" |
| 20 | "encoding/binary" |
| 21 | "errors" |
| 22 | "fmt" |
| 23 | "math/rand" |
| 24 | "net" |
| 25 | "slices" |
| 26 | "time" |
| 27 |
| 28 | "golang.org/x/crypto/cryptobyte" |
| 29 | ) |
| 30 |
| 31 | // A DTLSMessage is a DTLS handshake message or ChangeCipherSpec, along with the |
| 32 | // epoch that it is to be sent under. |
| 33 | type DTLSMessage struct { |
| 34 | Epoch uint16 |
| 35 | IsChangeCipherSpec bool |
| 36 | // The following fields are only used if IsChangeCipherSpec is false. |
| 37 | Type uint8 |
| 38 | Sequence uint16 |
| 39 | Data []byte |
| 40 | } |
| 41 |
| 42 | // Fragment returns a DTLSFragment for the message with the specified offset and |
| 43 | // length. |
| 44 | func (m *DTLSMessage) Fragment(offset, length int) DTLSFragment { |
| 45 | if m.IsChangeCipherSpec { |
| 46 | // Ignore the offset. ChangeCipherSpec cannot be fragmented. |
| 47 | return DTLSFragment{ |
| 48 | Epoch: m.Epoch, |
| 49 | IsChangeCipherSpec: m.IsChangeCipherSpec, |
| 50 | Data: m.Data, |
| 51 | } |
| 52 | } |
| 53 |
| 54 | return DTLSFragment{ |
| 55 | Epoch: m.Epoch, |
| 56 | Sequence: m.Sequence, |
| 57 | Type: m.Type, |
| 58 | Data: m.Data[offset : offset+length], |
| 59 | Offset: offset, |
| 60 | TotalLength: len(m.Data), |
| 61 | } |
| 62 | } |
| 63 |
| 64 | // Split returns two fragments for the message. |
| 65 | func (m *DTLSMessage) Split(offset int) (DTLSFragment, DTLSFragment) { |
| 66 | if m.IsChangeCipherSpec { |
| 67 | panic("tls: cannot split ChangeCipherSpec") |
| 68 | } |
| 69 |
| 70 | return m.Fragment(0, offset), m.Fragment(offset, len(m.Data)-offset) |
| 71 | } |
| 72 |
| 73 | // A DTLSFragment is a DTLS handshake fragment or ChangeCipherSpec, along with |
| 74 | // the epoch that it is to be sent under. |
| 75 | type DTLSFragment struct { |
| 76 | Epoch uint16 |
| 77 | IsChangeCipherSpec bool |
| 78 | // The following fields are only used if IsChangeCipherSpec is false. |
| 79 | Type uint8 |
| 80 | TotalLength int |
| 81 | Sequence uint16 |
| 82 | Offset int |
| 83 | Data []byte |
| 84 | // ShouldDiscard, if true, indicates the shim is expected to discard this |
| 85 | // fragment. A record with such a fragment must not be ACKed by the shim. |
| 86 | ShouldDiscard bool |
| 87 | } |
| 88 |
| 89 | func (f *DTLSFragment) Bytes() []byte { |
| 90 | if f.IsChangeCipherSpec { |
| 91 | return f.Data |
| 92 | } |
| 93 |
| 94 | bb := cryptobyte.NewBuilder(make([]byte, 0, 12+len(f.Data))) |
| 95 | bb.AddUint8(f.Type) |
| 96 | bb.AddUint24(uint32(f.TotalLength)) |
| 97 | bb.AddUint16(f.Sequence) |
| 98 | bb.AddUint24(uint32(f.Offset)) |
| 99 | addUint24LengthPrefixedBytes(bb, f.Data) |
| 100 | return bb.BytesOrPanic() |
| 101 | } |
| 102 |
| 103 | func comparePair[T1 cmp.Ordered, T2 cmp.Ordered](a1 T1, a2 T2, b1 T1, b2 T2) int { |
| 104 | cmp1 := cmp.Compare(a1, b1) |
| 105 | if cmp1 != 0 { |
| 106 | return cmp1 |
| 107 | } |
| 108 | return cmp.Compare(a2, b2) |
| 109 | } |
| 110 |
| 111 | type DTLSRecordNumber struct { |
| 112 | // Store the Epoch as a uint64, so that tests can send ACKs for epochs that |
| 113 | // the shim would never use. |
| 114 | Epoch uint64 |
| 115 | Sequence uint64 |
| 116 | } |
| 117 |
| 118 | // A DTLSRecordNumberInfo contains information about a record received from the |
| 119 | // shim, which we may attempt to ACK. |
| 120 | type DTLSRecordNumberInfo struct { |
| 121 | DTLSRecordNumber |
| 122 | // The first byte covered by this record, inclusive. We only need to store |
| 123 | // one range because we require that the shim arrange fragments in order. |
| 124 | // Any gaps will have been previously-ACKed data, so there is no harm in |
| 125 | // double-ACKing. |
| 126 | MessageStartSequence uint16 |
| 127 | MessageStartOffset int |
| 128 | // The last byte covered by this record, exclusive. |
| 129 | MessageEndSequence uint16 |
| 130 | MessageEndOffset int |
| 131 | } |
| 132 |
| 133 | func (r *DTLSRecordNumberInfo) HasACKInformation() bool { |
| 134 | return comparePair(r.MessageStartSequence, r.MessageStartOffset, r.MessageEndSequence, r.MessageEndOffset) < 0 |
| 135 | } |
| 136 |
| 137 | func (c *Conn) readDTLS13RecordHeader(epoch *epochState, b []byte) (headerLen int, recordLen int, recTyp recordType, err error) { |
| 138 | // The DTLS 1.3 record header starts with the type byte containing |
| 139 | // 0b001CSLEE, where C, S, L, and EE are bits with the following |
| 140 | // meanings: |
| 141 | // |
| 142 | // C=1: Connection ID is present (C=0: CID is absent) |
| 143 | // S=1: the sequence number is 16 bits (S=0: it is 8 bits) |
| 144 | // L=1: 16-bit length field is present (L=0: record goes to end of packet) |
| 145 | // EE: low two bits of the epoch. |
| 146 | // |
| 147 | // A real DTLS implementation would parse these bits and take |
| 148 | // appropriate action based on them. However, this is a test |
| 149 | // implementation, and the code we are testing only ever sends C=0, S=1, |
| 150 | // L=1. This code expects those bits to be set and will error if |
| 151 | // anything else is set. This means we expect the type byte to look like |
| 152 | // 0b001011EE, or 0x2c-0x2f. |
| 153 | recordHeaderLen := 5 |
| 154 | if len(b) < recordHeaderLen { |
| 155 | return 0, 0, 0, errors.New("dtls: failed to read record header") |
| 156 | } |
| 157 | typ := b[0] |
| 158 | if typ&0xfc != 0x2c { |
| 159 | return 0, 0, 0, errors.New("dtls: DTLS 1.3 record header has bad type byte") |
| 160 | } |
| 161 | // For test purposes, require the epoch received be the same as the |
| 162 | // epoch we expect to receive. |
| 163 | epochBits := typ & 0x03 |
| 164 | if epochBits != byte(epoch.epoch&0x03) { |
| 165 | c.sendAlert(alertIllegalParameter) |
| 166 | return 0, 0, 0, c.in.setErrorLocked(fmt.Errorf("dtls: bad epoch")) |
| 167 | } |
| 168 | wireSeq := b[1:3] |
| 169 | if !c.config.Bugs.NullAllCiphers { |
| 170 | sample := b[recordHeaderLen:] |
| 171 | mask := epoch.recordNumberEncrypter.generateMask(sample) |
| 172 | xorSlice(wireSeq, mask) |
| 173 | } |
| 174 | decWireSeq := binary.BigEndian.Uint16(wireSeq) |
| 175 | // Reconstruct the sequence number from the low 16 bits on the wire. |
| 176 | // A real implementation would compute the full sequence number that is |
| 177 | // closest to the highest successfully decrypted record in the |
| 178 | // identified epoch. Since this test implementation errors on decryption |
| 179 | // failures instead of simply discarding packets, it reconstructs a |
| 180 | // sequence number that is not less than c.in.seq. (This matches the |
| 181 | // behavior of the check of the sequence number in the old record |
| 182 | // header format.) |
| 183 | seqInt := binary.BigEndian.Uint64(epoch.seq[:]) |
| 184 | // epoch.seq has the epoch in the upper two bytes - clear those. |
| 185 | seqInt = seqInt &^ (0xffff << 48) |
| 186 | newSeq := seqInt&^0xffff | uint64(decWireSeq) |
| 187 | if newSeq < seqInt { |
| 188 | newSeq += 0x10000 |
| 189 | } |
| 190 |
| 191 | seq := make([]byte, 8) |
| 192 | binary.BigEndian.PutUint64(seq, newSeq) |
| 193 | copy(epoch.seq[2:], seq[2:]) |
| 194 |
| 195 | recordLen = int(b[3])<<8 | int(b[4]) |
| 196 | return recordHeaderLen, recordLen, 0, nil |
| 197 | } |
| 198 |
| 199 | // readDTLSRecordHeader reads the record header from the input. Based on the |
| 200 | // header it reads, it checks the header's validity and sets appropriate state |
| 201 | // as needed. This function returns the record header and the record type |
| 202 | // indicated in the header (if it contains the type). The connection's internal |
| 203 | // sequence number is updated to the value from the header. |
| 204 | func (c *Conn) readDTLSRecordHeader(epoch *epochState, b []byte) (headerLen int, recordLen int, typ recordType, err error) { |
| 205 | if epoch.cipher != nil && c.in.version >= VersionTLS13 { |
| 206 | return c.readDTLS13RecordHeader(epoch, b) |
| 207 | } |
| 208 |
| 209 | recordHeaderLen := 13 |
| 210 | // Read out one record. |
| 211 | // |
| 212 | // A real DTLS implementation should be tolerant of errors, |
| 213 | // but this is test code. We should not be tolerant of our |
| 214 | // peer sending garbage. |
| 215 | if len(b) < recordHeaderLen { |
| 216 | return 0, 0, 0, errors.New("dtls: failed to read record header") |
| 217 | } |
| 218 | typ = recordType(b[0]) |
| 219 | vers := uint16(b[1])<<8 | uint16(b[2]) |
| 220 | // Alerts sent near version negotiation do not have a well-defined |
| 221 | // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer |
| 222 | // version is irrelevant.) Additionally, if we're reading a retransmission, |
| 223 | // the peer may not know the version yet. |
| 224 | if typ != recordTypeAlert && !c.skipRecordVersionCheck { |
| 225 | if c.haveVers { |
| 226 | wireVersion := c.wireVersion |
| 227 | if c.vers >= VersionTLS13 { |
| 228 | wireVersion = VersionDTLS12 |
| 229 | } |
| 230 | if vers != wireVersion { |
| 231 | c.sendAlert(alertProtocolVersion) |
| 232 | return 0, 0, 0, c.in.setErrorLocked(fmt.Errorf("dtls: received record with version %x when expecting version %x", vers, c.wireVersion)) |
| 233 | } |
| 234 | } else { |
| 235 | if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect { |
| 236 | c.sendAlert(alertProtocolVersion) |
| 237 | return 0, 0, 0, c.in.setErrorLocked(fmt.Errorf("dtls: received record with version %x when expecting version %x", vers, expect)) |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | epochValue := binary.BigEndian.Uint16(b[3:5]) |
| 242 | seq := b[5:11] |
| 243 | // For test purposes, require the sequence number be monotonically |
| 244 | // increasing, so c.in includes the minimum next sequence number. Gaps |
| 245 | // may occur if packets failed to be sent out. A real implementation |
| 246 | // would maintain a replay window and such. |
| 247 | if epochValue != epoch.epoch { |
| 248 | c.sendAlert(alertIllegalParameter) |
| 249 | return 0, 0, 0, c.in.setErrorLocked(fmt.Errorf("dtls: bad epoch")) |
| 250 | } |
| 251 | if bytes.Compare(seq, epoch.seq[2:]) < 0 { |
| 252 | c.sendAlert(alertIllegalParameter) |
| 253 | return 0, 0, 0, c.in.setErrorLocked(fmt.Errorf("dtls: bad sequence number")) |
| 254 | } |
| 255 | copy(epoch.seq[2:], seq) |
| 256 | recordLen = int(b[11])<<8 | int(b[12]) |
| 257 | return recordHeaderLen, recordLen, typ, nil |
| 258 | } |
| 259 |
| 260 | func (c *Conn) dtlsDoReadRecord(epoch *epochState, want recordType) (recordType, []byte, error) { |
| 261 | // Read a new packet only if the current one is empty. |
| 262 | var newPacket bool |
| 263 | bytesAvailableInLastPacket := c.bytesAvailableInPacket |
| 264 | if c.rawInput.Len() == 0 { |
| 265 | // Pick some absurdly large buffer size. |
| 266 | c.rawInput.Grow(maxCiphertext + dtlsMaxRecordHeaderLen) |
| 267 | buf := c.rawInput.AvailableBuffer() |
| 268 | n, err := c.conn.Read(buf[:cap(buf)]) |
| 269 | if err != nil { |
| 270 | return 0, nil, err |
| 271 | } |
| 272 | if c.maxPacketLen != 0 { |
| 273 | if n > c.maxPacketLen { |
| 274 | return 0, nil, fmt.Errorf("dtls: exceeded maximum packet length") |
| 275 | } |
| 276 | c.bytesAvailableInPacket = c.maxPacketLen - n |
| 277 | } else { |
| 278 | c.bytesAvailableInPacket = 0 |
| 279 | } |
| 280 | c.rawInput.Write(buf[:n]) |
| 281 | newPacket = true |
| 282 | } |
| 283 |
| 284 | // Consume the next record from the buffer. |
| 285 | recordHeaderLen, n, typ, err := c.readDTLSRecordHeader(epoch, c.rawInput.Bytes()) |
| 286 | if err != nil { |
| 287 | return 0, nil, err |
| 288 | } |
| 289 | if n > maxCiphertext || c.rawInput.Len() < recordHeaderLen+n { |
| 290 | c.sendAlert(alertRecordOverflow) |
| 291 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: oversized record received with length %d", n)) |
| 292 | } |
| 293 | b := c.rawInput.Next(recordHeaderLen + n) |
| 294 |
| 295 | // Process message. |
| 296 | ok, encTyp, data, alertValue := c.in.decrypt(epoch, recordHeaderLen, b) |
| 297 | if !ok { |
| 298 | // A real DTLS implementation would silently ignore bad records, |
| 299 | // but we want to notice errors from the implementation under |
| 300 | // test. |
| 301 | return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue)) |
| 302 | } |
| 303 |
| 304 | if typ == 0 { |
| 305 | // readDTLSRecordHeader sets typ=0 when decoding the DTLS 1.3 |
| 306 | // record header. When the new record header format is used, the |
| 307 | // type is returned by decrypt() in encTyp. |
| 308 | typ = encTyp |
| 309 | } |
| 310 |
| 311 | if typ == recordTypeChangeCipherSpec || typ == recordTypeHandshake { |
| 312 | // If this is not the first record in the flight, check if it was packed |
| 313 | // efficiently. |
| 314 | if c.lastRecordInFlight != nil { |
| 315 | // 12-byte header + 1-byte fragment is the minimum to make progress. |
| 316 | const handshakeBytesNeeded = 13 |
| 317 | if typ == recordTypeHandshake && c.lastRecordInFlight.typ == recordTypeHandshake && epoch.epoch == c.lastRecordInFlight.epoch { |
| 318 | // The previous record was compatible with this one. The shim |
| 319 | // should have fit more in this record before making a new one. |
| 320 | // TODO(crbug.com/374991962): Enforce this for plaintext records |
| 321 | // too. |
| 322 | if c.lastRecordInFlight.bytesAvailable > handshakeBytesNeeded && epoch.epoch > 0 { |
| 323 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: previous handshake record had %d bytes available, but shim did not fit another fragment in it", c.lastRecordInFlight.bytesAvailable)) |
| 324 | } |
| 325 | } else if newPacket { |
| 326 | // The shim had to make a new record, but it did not need to |
| 327 | // make a new packet if this record fit in the previous. |
| 328 | bytesNeeded := 1 |
| 329 | if typ == recordTypeHandshake { |
| 330 | bytesNeeded = handshakeBytesNeeded |
| 331 | } |
| 332 | bytesNeeded += recordHeaderLen + c.in.maxEncryptOverhead(epoch, bytesNeeded) |
| 333 | if bytesNeeded < bytesAvailableInLastPacket { |
| 334 | return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: previous packet had %d bytes available, but shim did not fit record of type %d into it", bytesAvailableInLastPacket, typ)) |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 |
| 339 | // Save information about the current record, including how many more |
| 340 | // bytes the shim could have added. |
| 341 | recordBytesAvailable := c.bytesAvailableInPacket + c.rawInput.Len() |
| 342 | if cbc, ok := epoch.cipher.(*cbcMode); ok { |
| 343 | // It is possible that adding a byte would have added another block. |
| 344 | recordBytesAvailable = max(0, recordBytesAvailable-cbc.BlockSize()) |
| 345 | } |
| 346 | c.lastRecordInFlight = &dtlsRecordInfo{typ: typ, epoch: epoch.epoch, bytesAvailable: recordBytesAvailable} |
| 347 | } else { |
| 348 | c.lastRecordInFlight = nil |
| 349 | } |
| 350 |
| 351 | return typ, data, nil |
| 352 | } |
| 353 |
| 354 | func (c *Conn) dtlsWriteRecord(typ recordType, data []byte) (n int, err error) { |
| 355 | epoch := &c.out.epoch |
| 356 |
| 357 | // Outgoing DTLS records are buffered in several stages, to test the various |
| 358 | // layers that data may be combined in. |
| 359 | // |
| 360 | // First, handshake and ChangeCipherSpec records are buffered in |
| 361 | // c.nextFlight, to be flushed by dtlsWriteFlight. |
| 362 | // |
| 363 | // dtlsWriteFlight, with the aid of a test-supplied callback, will divide |
| 364 | // them into handshake records containing fragments, possibly with some |
| 365 | // rounds of shim retransmit tests. Those records and any other |
| 366 | // non-handshake application data records are encrypted by dtlsPackRecord |
| 367 | // into c.pendingPacket, which may combine multiple records into one packet. |
| 368 | // |
| 369 | // Finally, dtlsFlushPacket writes the packet to the shim. |
| 370 |
| 371 | if typ == recordTypeChangeCipherSpec { |
| 372 | // Don't send ChangeCipherSpec in DTLS 1.3. |
| 373 | // TODO(crbug.com/42290594): Add an option to send them anyway and test |
| 374 | // what our implementation does with unexpected ones. |
| 375 | if c.vers >= VersionTLS13 { |
| 376 | return |
| 377 | } |
| 378 | c.nextFlight = append(c.nextFlight, DTLSMessage{ |
| 379 | Epoch: epoch.epoch, |
| 380 | IsChangeCipherSpec: true, |
| 381 | Data: slices.Clone(data), |
| 382 | }) |
| 383 | err = c.out.changeCipherSpec() |
| 384 | if err != nil { |
| 385 | return n, c.sendAlertLocked(alertLevelError, err.(alert)) |
| 386 | } |
| 387 | return len(data), nil |
| 388 | } |
| 389 | if typ == recordTypeHandshake { |
| 390 | // Handshake messages have to be modified to include fragment |
| 391 | // offset and length and with the header replicated. Save the |
| 392 | // TLS header here. |
| 393 | header := data[:4] |
| 394 | body := data[4:] |
| 395 |
| 396 | c.nextFlight = append(c.nextFlight, DTLSMessage{ |
| 397 | Epoch: epoch.epoch, |
| 398 | Sequence: c.sendHandshakeSeq, |
| 399 | Type: header[0], |
| 400 | Data: slices.Clone(body), |
| 401 | }) |
| 402 | c.sendHandshakeSeq++ |
| 403 | return len(data), nil |
| 404 | } |
| 405 |
| 406 | // Flush any packets buffered from the handshake. |
| 407 | err = c.dtlsWriteFlight() |
| 408 | if err != nil { |
| 409 | return |
| 410 | } |
| 411 |
| 412 | if typ == recordTypeApplicationData && len(data) > 1 && c.config.Bugs.SplitAndPackAppData { |
| 413 | _, _, err = c.dtlsPackRecord(epoch, typ, data[:len(data)/2], false) |
| 414 | if err != nil { |
| 415 | return |
| 416 | } |
| 417 | _, _, err = c.dtlsPackRecord(epoch, typ, data[len(data)/2:], true) |
| 418 | if err != nil { |
| 419 | return |
| 420 | } |
| 421 | n = len(data) |
| 422 | } else { |
| 423 | n, _, err = c.dtlsPackRecord(epoch, typ, data, false) |
| 424 | if err != nil { |
| 425 | return |
| 426 | } |
| 427 | } |
| 428 |
| 429 | err = c.dtlsFlushPacket() |
| 430 | return |
| 431 | } |
| 432 |
| 433 | // dtlsWriteFlight packs the pending handshake flight into the pending record. |
| 434 | // Callers should follow up with dtlsFlushPacket to write the packets. |
| 435 | func (c *Conn) dtlsWriteFlight() error { |
| 436 | if len(c.nextFlight) == 0 { |
| 437 | return nil |
| 438 | } |
| 439 |
| 440 | // Avoid re-entrancy issues by updating the state immediately. The callback |
| 441 | // may try to write records. |
| 442 | prev, received, next, records := c.previousFlight, c.receivedFlight, c.nextFlight, c.receivedFlightRecords |
| 443 | c.previousFlight, c.receivedFlight, c.nextFlight, c.receivedFlightRecords = next, nil, nil, nil |
| 444 |
| 445 | controller := newDTLSController(c, received) |
| 446 | if c.config.Bugs.WriteFlightDTLS != nil { |
| 447 | c.config.Bugs.WriteFlightDTLS(&controller, prev, received, next, records) |
| 448 | } else { |
| 449 | controller.WriteFlight(next) |
| 450 | } |
| 451 | if err := controller.Err(); err != nil { |
| 452 | return err |
| 453 | } |
| 454 |
| 455 | if c.receivedFlight != nil || c.receivedFlightRecords != nil || c.nextFlight != nil { |
| 456 | panic("tls: flight state changed while writing flight") |
| 457 | } |
| 458 | if controller.mergeIntoNextFlight { |
| 459 | c.previousFlight, c.receivedFlight, c.nextFlight, c.receivedFlightRecords = prev, received, next, records |
| 460 | } |
| 461 |
| 462 | // Flush any ACKs, etc., we may have written. |
| 463 | return c.dtlsFlushPacket() |
| 464 | } |
| 465 |
| 466 | func (c *Conn) dtlsFlushHandshake() error { |
| 467 | if err := c.dtlsWriteFlight(); err != nil { |
| 468 | return err |
| 469 | } |
| 470 | if err := c.dtlsFlushPacket(); err != nil { |
| 471 | return err |
| 472 | } |
| 473 |
| 474 | return nil |
| 475 | } |
| 476 |
| 477 | func (c *Conn) dtlsACKHandshake() error { |
| 478 | if len(c.receivedFlight) == 0 { |
| 479 | return nil |
| 480 | } |
| 481 |
| 482 | if len(c.nextFlight) != 0 { |
| 483 | panic("tls: not a final flight; more messages were queued up") |
| 484 | } |
| 485 |
| 486 | // Avoid re-entrancy issues by updating the state immediately. The callback |
| 487 | // may try to write records. |
| 488 | prev, received, records := c.previousFlight, c.receivedFlight, c.receivedFlightRecords |
| 489 | c.previousFlight, c.receivedFlight, c.receivedFlightRecords = nil, nil, nil |
| 490 |
| 491 | controller := newDTLSController(c, received) |
| 492 | if c.config.Bugs.ACKFlightDTLS != nil { |
| 493 | c.config.Bugs.ACKFlightDTLS(&controller, prev, received, records) |
| 494 | } else { |
| 495 | if c.vers >= VersionTLS13 { |
| 496 | controller.WriteACK(controller.OutEpoch(), records) |
| 497 | } |
| 498 | } |
| 499 | if err := controller.Err(); err != nil { |
| 500 | return err |
| 501 | } |
| 502 |
| 503 | if c.previousFlight != nil || c.receivedFlight != nil || c.receivedFlightRecords != nil { |
| 504 | panic("tls: flight state changed while ACKing flight") |
| 505 | } |
| 506 | if controller.mergeIntoNextFlight { |
| 507 | c.previousFlight, c.receivedFlight, c.receivedFlightRecords = prev, received, records |
| 508 | } |
| 509 |
| 510 | // Flush any ACKs, etc., we may have written. |
| 511 | return c.dtlsFlushPacket() |
| 512 | } |
| 513 |
| 514 | // appendDTLS13RecordHeader appends to b the record header for a record of length |
| 515 | // recordLen. |
| 516 | func (c *Conn) appendDTLS13RecordHeader(b, seq []byte, recordLen int) []byte { |
| 517 | // Set the top 3 bits on the type byte to indicate the DTLS 1.3 record |
| 518 | // header format. |
| 519 | typ := byte(0x20) |
| 520 | // Set the Connection ID bit |
| 521 | if c.config.Bugs.DTLS13RecordHeaderSetCIDBit && c.handshakeComplete { |
| 522 | typ |= 0x10 |
| 523 | } |
| 524 | // Set the sequence number length bit |
| 525 | if !c.config.DTLSUseShortSeqNums { |
| 526 | typ |= 0x08 |
| 527 | } |
| 528 | // Set the length presence bit |
| 529 | if !c.config.DTLSRecordHeaderOmitLength { |
| 530 | typ |= 0x04 |
| 531 | } |
| 532 | // Set the epoch bits |
| 533 | typ |= seq[1] & 0x3 |
| 534 | b = append(b, typ) |
| 535 | if c.config.DTLSUseShortSeqNums { |
| 536 | b = append(b, seq[7]) |
| 537 | } else { |
| 538 | b = append(b, seq[6], seq[7]) |
| 539 | } |
| 540 | if !c.config.DTLSRecordHeaderOmitLength { |
| 541 | b = append(b, byte(recordLen>>8), byte(recordLen)) |
| 542 | } |
| 543 | return b |
| 544 | } |
| 545 |
| 546 | // dtlsPackRecord packs a single record to the pending packet, flushing it |
| 547 | // if necessary. The caller should call dtlsFlushPacket to flush the current |
| 548 | // pending packet afterwards. |
| 549 | func (c *Conn) dtlsPackRecord(epoch *epochState, typ recordType, data []byte, mustPack bool) (n int, num DTLSRecordNumber, err error) { |
| 550 | maxLen := c.config.Bugs.MaxHandshakeRecordLength |
| 551 | if maxLen <= 0 { |
| 552 | maxLen = 1024 |
| 553 | } |
| 554 |
| 555 | vers := c.wireVersion |
| 556 | if vers == 0 { |
| 557 | // Some TLS servers fail if the record version is greater than |
| 558 | // TLS 1.0 for the initial ClientHello. |
| 559 | if c.isDTLS { |
| 560 | vers = VersionDTLS10 |
| 561 | } else { |
| 562 | vers = VersionTLS10 |
| 563 | } |
| 564 | } |
| 565 | if c.vers >= VersionTLS13 || c.out.version >= VersionTLS13 { |
| 566 | vers = VersionDTLS12 |
| 567 | } |
| 568 |
| 569 | useDTLS13RecordHeader := c.out.version >= VersionTLS13 && epoch.cipher != nil && !c.useDTLSPlaintextHeader() |
| 570 | headerHasLength := true |
| 571 | record := make([]byte, 0, dtlsMaxRecordHeaderLen+len(data)+c.out.maxEncryptOverhead(epoch, len(data))) |
| 572 | seq := c.out.sequenceNumberForOutput(epoch) |
| 573 | if useDTLS13RecordHeader { |
| 574 | record = c.appendDTLS13RecordHeader(record, seq, len(data)) |
| 575 | headerHasLength = !c.config.DTLSRecordHeaderOmitLength |
| 576 | } else { |
| 577 | record = append(record, byte(typ)) |
| 578 | record = append(record, byte(vers>>8)) |
| 579 | record = append(record, byte(vers)) |
| 580 | // DTLS records include an explicit sequence number. |
| 581 | record = append(record, seq...) |
| 582 | record = append(record, byte(len(data)>>8)) |
| 583 | record = append(record, byte(len(data))) |
| 584 | } |
| 585 |
| 586 | recordHeaderLen := len(record) |
| 587 | record, err = c.out.encrypt(epoch, record, data, typ, recordHeaderLen, headerHasLength) |
| 588 | if err != nil { |
| 589 | return |
| 590 | } |
| 591 | num = c.out.lastRecordNumber(epoch, true /* isOut */) |
| 592 |
| 593 | // Encrypt the sequence number. |
| 594 | if useDTLS13RecordHeader && !c.config.Bugs.NullAllCiphers { |
| 595 | sample := record[recordHeaderLen:] |
| 596 | mask := epoch.recordNumberEncrypter.generateMask(sample) |
| 597 | seqLen := 2 |
| 598 | if c.config.DTLSUseShortSeqNums { |
| 599 | seqLen = 1 |
| 600 | } |
| 601 | // The sequence number starts at index 1 in the record header. |
| 602 | xorSlice(record[1:1+seqLen], mask) |
| 603 | } |
| 604 |
| 605 | // Flush the current pending packet if necessary. |
| 606 | if !mustPack && len(record)+len(c.pendingPacket) > c.config.Bugs.PackHandshakeRecords { |
| 607 | err = c.dtlsFlushPacket() |
| 608 | if err != nil { |
| 609 | return |
| 610 | } |
| 611 | } |
| 612 |
| 613 | // Add the record to the pending packet. |
| 614 | c.pendingPacket = append(c.pendingPacket, record...) |
| 615 | if c.config.DTLSRecordHeaderOmitLength { |
| 616 | if c.config.Bugs.SplitAndPackAppData { |
| 617 | panic("incompatible config") |
| 618 | } |
| 619 | err = c.dtlsFlushPacket() |
| 620 | if err != nil { |
| 621 | return |
| 622 | } |
| 623 | } |
| 624 | n = len(data) |
| 625 | return |
| 626 | } |
| 627 |
| 628 | func (c *Conn) dtlsFlushPacket() error { |
| 629 | if c.hand.Len() == 0 { |
| 630 | c.lastRecordInFlight = nil |
| 631 | } |
| 632 | if len(c.pendingPacket) == 0 { |
| 633 | return nil |
| 634 | } |
| 635 | _, err := c.conn.Write(c.pendingPacket) |
| 636 | c.pendingPacket = nil |
| 637 | return err |
| 638 | } |
| 639 |
| 640 | func readDTLSFragment(s *cryptobyte.String) (DTLSFragment, error) { |
| 641 | var f DTLSFragment |
| 642 | var totLen, fragOffset uint32 |
| 643 | if !s.ReadUint8(&f.Type) || |
| 644 | !s.ReadUint24(&totLen) || |
| 645 | !s.ReadUint16(&f.Sequence) || |
| 646 | !s.ReadUint24(&fragOffset) || |
| 647 | !readUint24LengthPrefixedBytes(s, &f.Data) { |
| 648 | return DTLSFragment{}, errors.New("dtls: bad handshake record") |
| 649 | } |
| 650 | f.TotalLength = int(totLen) |
| 651 | f.Offset = int(fragOffset) |
| 652 | if f.Offset > f.TotalLength || len(f.Data) > f.TotalLength-f.Offset { |
| 653 | return DTLSFragment{}, errors.New("dtls: bad fragment offset") |
| 654 | } |
| 655 | // Although syntactically valid, the shim should never send empty fragments |
| 656 | // of non-empty messages. |
| 657 | if len(f.Data) == 0 && f.TotalLength != 0 { |
| 658 | return DTLSFragment{}, errors.New("dtls: fragment makes no progress") |
| 659 | } |
| 660 | return f, nil |
| 661 | } |
| 662 |
| 663 | func (c *Conn) makeDTLSRecordNumberInfo(epoch *epochState, data []byte) (DTLSRecordNumberInfo, error) { |
| 664 | info := DTLSRecordNumberInfo{DTLSRecordNumber: c.in.lastRecordNumber(epoch, false /* isOut */)} |
| 665 |
| 666 | s := cryptobyte.String(data) |
| 667 | first := true |
| 668 | for !s.Empty() { |
| 669 | f, err := readDTLSFragment(&s) |
| 670 | if err != nil { |
| 671 | return DTLSRecordNumberInfo{}, err |
| 672 | } |
| 673 | // This assumes the shim sent fragments in order. This isn't checked |
| 674 | // here, but the caller will check when processing the fragments. |
| 675 | if first { |
| 676 | info.MessageStartSequence = f.Sequence |
| 677 | info.MessageStartOffset = f.Offset |
| 678 | first = false |
| 679 | } |
| 680 | info.MessageEndSequence = f.Sequence |
| 681 | info.MessageEndOffset = f.Offset + len(f.Data) |
| 682 | } |
| 683 |
| 684 | return info, nil |
| 685 | } |
| 686 |
| 687 | func (c *Conn) dtlsDoReadHandshake() ([]byte, error) { |
| 688 | // Assemble a full handshake message. For test purposes, this |
| 689 | // implementation assumes fragments arrive in order. It may |
| 690 | // need to be cleverer if we ever test BoringSSL's retransmit |
| 691 | // behavior. |
| 692 | for len(c.handMsg) < 4+c.handMsgLen { |
| 693 | // Get a new handshake record if the previous has been |
| 694 | // exhausted. |
| 695 | if c.hand.Len() == 0 { |
| 696 | if err := c.in.err; err != nil { |
| 697 | return nil, err |
| 698 | } |
| 699 | if err := c.readRecord(recordTypeHandshake); err != nil { |
| 700 | return nil, err |
| 701 | } |
| 702 | } |
| 703 |
| 704 | // Read the next fragment. It must fit entirely within |
| 705 | // the record. |
| 706 | s := cryptobyte.String(c.hand.Bytes()) |
| 707 | f, err := readDTLSFragment(&s) |
| 708 | if err != nil { |
| 709 | return nil, err |
| 710 | } |
| 711 | c.hand.Next(c.hand.Len() - len(s)) |
| 712 |
| 713 | // Check it's a fragment for the right message. |
| 714 | if f.Sequence != c.recvHandshakeSeq { |
| 715 | return nil, errors.New("dtls: bad handshake sequence number") |
| 716 | } |
| 717 |
| 718 | // Check that the length is consistent. |
| 719 | if c.handMsg == nil { |
| 720 | c.handMsgLen = f.TotalLength |
| 721 | if c.handMsgLen > maxHandshake { |
| 722 | return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) |
| 723 | } |
| 724 | // Start with the TLS handshake header, |
| 725 | // without the DTLS bits. |
| 726 | c.handMsg = []byte{f.Type, byte(f.TotalLength >> 16), byte(f.TotalLength >> 8), byte(f.TotalLength)} |
| 727 | } else if f.TotalLength != c.handMsgLen { |
| 728 | return nil, errors.New("dtls: bad handshake length") |
| 729 | } |
| 730 |
| 731 | // Add the fragment to the pending message. |
| 732 | if 4+f.Offset != len(c.handMsg) { |
| 733 | return nil, errors.New("dtls: bad fragment offset") |
| 734 | } |
| 735 | // If the message isn't complete, check that the peer could not have |
| 736 | // fit more into the record. |
| 737 | c.handMsg = append(c.handMsg, f.Data...) |
| 738 | if len(c.handMsg) < 4+c.handMsgLen { |
| 739 | if c.hand.Len() != 0 { |
| 740 | return nil, errors.New("dtls: truncated handshake fragment was not last in the record") |
| 741 | } |
| 742 | if c.lastRecordInFlight.bytesAvailable > 0 { |
| 743 | return nil, fmt.Errorf("dtls: handshake fragment was truncated, but record could have fit %d more bytes", c.lastRecordInFlight.bytesAvailable) |
| 744 | } |
| 745 | } |
| 746 |
| 747 | // Sending part of the next flight implicitly ACKs the previous flight. |
| 748 | // Having triggered this, the shim is expected to clear its ACK buffer. |
| 749 | c.expectedACK = nil |
| 750 | } |
| 751 | c.recvHandshakeSeq++ |
| 752 | ret := c.handMsg |
| 753 | c.handMsg, c.handMsgLen = nil, 0 |
| 754 | c.receivedFlight = append(c.receivedFlight, DTLSMessage{ |
| 755 | Epoch: c.in.epoch.epoch, |
| 756 | Type: ret[0], |
| 757 | Sequence: c.recvHandshakeSeq - 1, |
| 758 | Data: ret[4:], |
| 759 | }) |
| 760 | return ret, nil |
| 761 | } |
| 762 |
| 763 | func (c *Conn) checkACK(data []byte) error { |
| 764 | s := cryptobyte.String(data) |
| 765 | var child cryptobyte.String |
| 766 | if !s.ReadUint16LengthPrefixed(&child) || !s.Empty() { |
| 767 | return fmt.Errorf("tls: could not parse ACK record") |
| 768 | } |
| 769 |
| 770 | var acks []DTLSRecordNumber |
| 771 | for !child.Empty() { |
| 772 | var num DTLSRecordNumber |
| 773 | if !child.ReadUint64(&num.Epoch) || !child.ReadUint64(&num.Sequence) { |
| 774 | return fmt.Errorf("tls: could not parse ACK record") |
| 775 | } |
| 776 | acks = append(acks, num) |
| 777 | } |
| 778 |
| 779 | // Determine the expected ACKs, if any. |
| 780 | expected := c.expectedACK |
| 781 | if len(expected) > shimConfig.MaxACKBuffer { |
| 782 | expected = expected[len(expected)-shimConfig.MaxACKBuffer:] |
| 783 | } |
| 784 |
| 785 | // If we've configured a tighter MTU, the shim might have needed to truncate |
| 786 | // the list. Tolerate this as long as the shim sent the more recent records |
| 787 | // and still sent a plausible minimum number of ACKs. |
| 788 | if c.maxPacketLen != 0 && len(acks) > 10 && len(acks) < len(expected) { |
| 789 | expected = expected[len(expected)-len(acks):] |
| 790 | } |
| 791 |
| 792 | // The shim is expected to sort the record numbers in the ACK. |
| 793 | expected = slices.Clone(expected) |
| 794 | slices.SortFunc(expected, func(a, b DTLSRecordNumber) int { |
| 795 | cmp1 := cmp.Compare(a.Epoch, b.Epoch) |
| 796 | if cmp1 != 0 { |
| 797 | return cmp1 |
| 798 | } |
| 799 | return cmp.Compare(a.Sequence, b.Sequence) |
| 800 | }) |
| 801 |
| 802 | if !slices.Equal(acks, expected) { |
| 803 | return fmt.Errorf("tls: got ACKs %+v, but expected %+v", acks, expected) |
| 804 | } |
| 805 |
| 806 | return nil |
| 807 | } |
| 808 |
| 809 | // DTLSServer returns a new DTLS server side connection |
| 810 | // using conn as the underlying transport. |
| 811 | // The configuration config must be non-nil and must have |
| 812 | // at least one certificate. |
| 813 | func DTLSServer(conn net.Conn, config *Config) *Conn { |
| 814 | c := &Conn{config: config, isDTLS: true, conn: conn} |
| 815 | c.init() |
| 816 | return c |
| 817 | } |
| 818 |
| 819 | // DTLSClient returns a new DTLS client side connection |
| 820 | // using conn as the underlying transport. |
| 821 | // The config cannot be nil: users must set either ServerHostname or |
| 822 | // InsecureSkipVerify in the config. |
| 823 | func DTLSClient(conn net.Conn, config *Config) *Conn { |
| 824 | c := &Conn{config: config, isClient: true, isDTLS: true, conn: conn} |
| 825 | c.init() |
| 826 | return c |
| 827 | } |
| 828 |
| 829 | type WriteFlightFunc = func(c *DTLSController, prev, received, next []DTLSMessage, records []DTLSRecordNumberInfo) |
| 830 | type ACKFlightFunc = func(c *DTLSController, prev, received []DTLSMessage, records []DTLSRecordNumberInfo) |
| 831 |
| 832 | // A DTLSController is passed to a test callback and allows the callback to |
| 833 | // customize how an individual flight is sent. This is used to test DTLS's |
| 834 | // retransmission logic. |
| 835 | // |
| 836 | // Although DTLS runs over a lossy, reordered channel, runner assumes a |
| 837 | // reliable, ordered channel. When simulating packet loss, runner processes the |
| 838 | // shim's "lost" flight as usual. But, instead of responding, it calls a |
| 839 | // test-provided function type WriteFlightFunc. |
| 840 | // |
| 841 | // WriteFlight will be called next as the flight for the runner to send. prev is |
| 842 | // the previous flight sent by the runner, and received is the most recent |
| 843 | // flight received by the shim. prev and received may be nil if those flights do |
| 844 | // not exist. |
| 845 | // |
| 846 | // WriteFlight should send next to the shim, by calling methods on the |
| 847 | // DTLSController, and then return. The shim will then be expected to progress |
| 848 | // the connection. However, WriteFlight, may send fragments arbitrarily |
| 849 | // reordered or duplicated. It may also simulate packet loss with timeouts or |
| 850 | // retransmitted past fragments, and then test that the shim retransmits. |
| 851 | // |
| 852 | // WriteFlight must return as soon as the shim is expected to progress the |
| 853 | // connection. If WriteFlight expects the shim to send an alert, it must also |
| 854 | // return, at which point the logic to progress the connection will consume the |
| 855 | // alert and report it as a connection failure, to be captured in the test |
| 856 | // expectation. |
| 857 | // |
| 858 | // If unspecified, the default implementation of WriteFlight is: |
| 859 | // |
| 860 | // func WriteFlight(c *DTLSController, prev, received, next []DTLSMessage, records []DTLSRecordNumberInfo) { |
| 861 | // c.WriteFlight(next) |
| 862 | // } |
| 863 | // |
| 864 | // When the shim speaks last in a handshake or post-handshake transaction, there |
| 865 | // is no reply to implicitly acknowledge the flight. The runner will instead |
| 866 | // call a second callback type ACKFlightFunc. |
| 867 | // |
| 868 | // Like WriteFlight, ACKFlight may simulate packet loss with the DTLSController. |
| 869 | // It returns when it is ready to proceed. If not specified, it does nothing in |
| 870 | // DTLS 1.2 and ACKs the final flight in DTLS 1.3. |
| 871 | // |
| 872 | // This test design implicitly assumes the shim will never start a |
| 873 | // post-handshake transaction before the previous one is complete. Otherwise the |
| 874 | // retransmissions will get mixed up with the second transaction. |
| 875 | // |
| 876 | // For convenience, the DTLSController internally tracks whether it has |
| 877 | // encountered an error (e.g. an I/O error with the shim) and, if so, silently |
| 878 | // makes all methods do nothing. The Err method may be used to query if it is in |
| 879 | // this state, if it would otherwise cause an infinite loop. |
| 880 | type DTLSController struct { |
| 881 | conn *Conn |
| 882 | err error |
| 883 | // retransmitNeeded contains the list of fragments which the shim must |
| 884 | // retransmit. |
| 885 | retransmitNeeded []DTLSFragment |
| 886 | mergeIntoNextFlight bool |
| 887 | } |
| 888 |
| 889 | func newDTLSController(conn *Conn, received []DTLSMessage) DTLSController { |
| 890 | var retransmitNeeded []DTLSFragment |
| 891 | for i := range received { |
| 892 | msg := &received[i] |
| 893 | retransmitNeeded = append(retransmitNeeded, msg.Fragment(0, len(msg.Data))) |
| 894 | } |
| 895 |
| 896 | return DTLSController{conn: conn, retransmitNeeded: retransmitNeeded} |
| 897 | } |
| 898 |
| 899 | func (c *DTLSController) getOutEpochOrPanic(epochValue uint16) *epochState { |
| 900 | epoch, ok := c.conn.out.getEpoch(epochValue) |
| 901 | if !ok { |
| 902 | panic(fmt.Sprintf("tls: could not find epoch %d", epochValue)) |
| 903 | } |
| 904 | return epoch |
| 905 | } |
| 906 |
| 907 | func (c *DTLSController) getInEpochOrPanic(epochValue uint16) *epochState { |
| 908 | epoch, ok := c.conn.in.getEpoch(epochValue) |
| 909 | if !ok { |
| 910 | panic(fmt.Sprintf("tls: could not find epoch %d", epochValue)) |
| 911 | } |
| 912 | return epoch |
| 913 | } |
| 914 |
| 915 | // Err returns whether the controller has stopped due to an error, or nil |
| 916 | // otherwise. If it returns non-nil, other methods will silently do nothing. |
| 917 | func (c *DTLSController) Err() error { return c.err } |
| 918 |
| 919 | // OutEpoch returns the current outgoing epoch. |
| 920 | func (c *DTLSController) OutEpoch() uint16 { |
| 921 | return c.conn.out.epoch.epoch |
| 922 | } |
| 923 |
| 924 | // InEpoch returns the current incoming epoch. |
| 925 | func (c *DTLSController) InEpoch() uint16 { |
| 926 | return c.conn.in.epoch.epoch |
| 927 | } |
| 928 |
| 929 | // AdvanceClock advances the shim's clock by duration. It is a test failure if |
| 930 | // the shim sends anything before picking up the command. |
| 931 | func (c *DTLSController) AdvanceClock(duration time.Duration) { |
| 932 | if c.err != nil { |
| 933 | return |
| 934 | } |
| 935 |
| 936 | c.err = c.conn.dtlsFlushPacket() |
| 937 | if c.err != nil { |
| 938 | return |
| 939 | } |
| 940 |
| 941 | adaptor := c.conn.config.Bugs.PacketAdaptor |
| 942 | if adaptor == nil { |
| 943 | panic("tls: no PacketAdapter set") |
| 944 | } |
| 945 |
| 946 | received, err := adaptor.SendReadTimeout(duration) |
| 947 | if err != nil { |
| 948 | c.err = err |
| 949 | } else if len(received) != 0 { |
| 950 | c.err = fmt.Errorf("tls: received %d unexpected packets while simulating a timeout", len(received)) |
| 951 | } |
| 952 | } |
| 953 |
| 954 | // SetMTU updates the shim's MTU to mtu. |
| 955 | func (c *DTLSController) SetMTU(mtu int) { |
| 956 | if c.err != nil { |
| 957 | return |
| 958 | } |
| 959 |
| 960 | adaptor := c.conn.config.Bugs.PacketAdaptor |
| 961 | if adaptor == nil { |
| 962 | panic("tls: no PacketAdapter set") |
| 963 | } |
| 964 |
| 965 | c.conn.maxPacketLen = mtu |
| 966 | c.err = adaptor.SetPeerMTU(mtu) |
| 967 | } |
| 968 |
| 969 | // WriteFlight writes msgs to the shim, using the default fragmenting logic. |
| 970 | // This may be used when the test is not concerned with fragmentation. |
| 971 | func (c *DTLSController) WriteFlight(msgs []DTLSMessage) { |
| 972 | config := c.conn.config |
| 973 | if c.err != nil { |
| 974 | return |
| 975 | } |
| 976 |
| 977 | // Buffer up fragments to reorder them. |
| 978 | var fragments []DTLSFragment |
| 979 |
| 980 | // TODO(davidben): All this could also have been implemented in the custom |
| 981 | // fallbacks. These options date to before we had the callback. Should some |
| 982 | // of them be moved out? |
| 983 | for _, msg := range msgs { |
| 984 | if msg.IsChangeCipherSpec { |
| 985 | fragments = append(fragments, msg.Fragment(0, len(msg.Data))) |
| 986 | continue |
| 987 | } |
| 988 |
| 989 | maxLen := config.Bugs.MaxHandshakeRecordLength |
| 990 | if maxLen <= 0 { |
| 991 | maxLen = 1024 |
| 992 | } |
| 993 |
| 994 | if config.Bugs.SendEmptyFragments { |
| 995 | fragments = append(fragments, msg.Fragment(0, 0)) |
| 996 | fragments = append(fragments, msg.Fragment(len(msg.Data), 0)) |
| 997 | } |
| 998 |
| 999 | firstRun := true |
| 1000 | fragOffset := 0 |
| 1001 | for firstRun || fragOffset < len(msg.Data) { |
| 1002 | firstRun = false |
| 1003 | fragLen := min(len(msg.Data)-fragOffset, maxLen) |
| 1004 |
| 1005 | fragment := msg.Fragment(fragOffset, fragLen) |
| 1006 | fragments = append(fragments, fragment) |
| 1007 | if config.Bugs.ReorderHandshakeFragments { |
| 1008 | // Don't duplicate Finished to avoid the peer |
| 1009 | // interpreting it as a retransmit request. |
| 1010 | if msg.Type != typeFinished { |
| 1011 | fragments = append(fragments, fragment) |
| 1012 | } |
| 1013 |
| 1014 | if fragLen > (maxLen+1)/2 { |
| 1015 | // Overlap each fragment by half. |
| 1016 | fragLen = (maxLen + 1) / 2 |
| 1017 | } |
| 1018 | } |
| 1019 | fragOffset += fragLen |
| 1020 | } |
| 1021 | if config.Bugs.MixCompleteMessageWithFragments { |
| 1022 | fragments = append(fragments, msg.Fragment(0, len(msg.Data))) |
| 1023 | } |
| 1024 | } |
| 1025 |
| 1026 | // Reorder the fragments, but only within an epoch. |
| 1027 | for start := 0; start < len(fragments); { |
| 1028 | end := start + 1 |
| 1029 | for end < len(fragments) && fragments[start].Epoch == fragments[end].Epoch { |
| 1030 | end++ |
| 1031 | } |
| 1032 | chunk := fragments[start:end] |
| 1033 | if config.Bugs.ReorderHandshakeFragments { |
| 1034 | rand.Shuffle(len(chunk), func(i, j int) { chunk[i], chunk[j] = chunk[j], chunk[i] }) |
| 1035 | } |
| 1036 | start = end |
| 1037 | } |
| 1038 |
| 1039 | c.WriteFragments(fragments) |
| 1040 | } |
| 1041 |
| 1042 | // WriteFragments writes the specified handshake fragments to the shim. |
| 1043 | func (c *DTLSController) WriteFragments(fragments []DTLSFragment) { |
| 1044 | config := c.conn.config |
| 1045 | if c.err != nil { |
| 1046 | return |
| 1047 | } |
| 1048 |
| 1049 | maxRecordLen := config.Bugs.PackHandshakeFragments |
| 1050 | packRecord := func(epoch *epochState, typ recordType, data []byte, anyDiscard bool) error { |
| 1051 | _, num, err := c.conn.dtlsPackRecord(epoch, typ, data, false) |
| 1052 | if err != nil { |
| 1053 | return err |
| 1054 | } |
| 1055 | if !anyDiscard && typ == recordTypeHandshake { |
| 1056 | c.conn.expectedACK = append(c.conn.expectedACK, num) |
| 1057 | } |
| 1058 | return nil |
| 1059 | } |
| 1060 |
| 1061 | // Pack handshake fragments into records. |
| 1062 | var record []byte |
| 1063 | var epoch *epochState |
| 1064 | var anyDiscard bool |
| 1065 | flush := func() error { |
| 1066 | if len(record) > 0 { |
| 1067 | if err := packRecord(epoch, recordTypeHandshake, record, anyDiscard); err != nil { |
| 1068 | return err |
| 1069 | } |
| 1070 | } |
| 1071 | record = nil |
| 1072 | anyDiscard = false |
| 1073 | return nil |
| 1074 | } |
| 1075 |
| 1076 | for i := range fragments { |
| 1077 | f := &fragments[i] |
| 1078 | if epoch != nil && (f.Epoch != epoch.epoch || f.IsChangeCipherSpec) { |
| 1079 | c.err = flush() |
| 1080 | if c.err != nil { |
| 1081 | return |
| 1082 | } |
| 1083 | epoch = nil |
| 1084 | } |
| 1085 |
| 1086 | if epoch == nil { |
| 1087 | epoch = c.getOutEpochOrPanic(f.Epoch) |
| 1088 | } |
| 1089 |
| 1090 | if f.IsChangeCipherSpec { |
| 1091 | c.err = packRecord(epoch, recordTypeChangeCipherSpec, f.Bytes(), false) |
| 1092 | if c.err != nil { |
| 1093 | return |
| 1094 | } |
| 1095 | continue |
| 1096 | } |
| 1097 |
| 1098 | fBytes := f.Bytes() |
| 1099 | if n := config.Bugs.SplitFragments; n > 0 { |
| 1100 | if len(fBytes) > n { |
| 1101 | c.err = packRecord(epoch, recordTypeHandshake, fBytes[:n], f.ShouldDiscard) |
| 1102 | if c.err != nil { |
| 1103 | return |
| 1104 | } |
| 1105 | c.err = packRecord(epoch, recordTypeHandshake, fBytes[n:], f.ShouldDiscard) |
| 1106 | if c.err != nil { |
| 1107 | return |
| 1108 | } |
| 1109 | } else { |
| 1110 | c.err = packRecord(epoch, recordTypeHandshake, fBytes, f.ShouldDiscard) |
| 1111 | if c.err != nil { |
| 1112 | return |
| 1113 | } |
| 1114 | } |
| 1115 | } else { |
| 1116 | if len(record)+len(fBytes) > maxRecordLen { |
| 1117 | c.err = flush() |
| 1118 | if c.err != nil { |
| 1119 | return |
| 1120 | } |
| 1121 | } |
| 1122 | if f.ShouldDiscard { |
| 1123 | anyDiscard = true |
| 1124 | } |
| 1125 | record = append(record, fBytes...) |
| 1126 | } |
| 1127 | } |
| 1128 |
| 1129 | c.err = flush() |
| 1130 | } |
| 1131 |
| 1132 | // WriteACK writes the specified record numbers in an ACK record to the shim, |
| 1133 | // and updates shim expectations according to the specified byte ranges. To send |
| 1134 | // an ACK which the shim is expected to ignore (e.g. because it should have |
| 1135 | // forgotten a packet number), use a DTLSRecordNumberInfo with the |
| 1136 | // MessageStartSequence, etc., fields all set to zero. |
| 1137 | func (c *DTLSController) WriteACK(epoch uint16, records []DTLSRecordNumberInfo) { |
| 1138 | if c.err != nil { |
| 1139 | return |
| 1140 | } |
| 1141 |
| 1142 | // Send the ACK. |
| 1143 | ack := cryptobyte.NewBuilder(make([]byte, 0, 2+8*len(records))) |
| 1144 | ack.AddUint16LengthPrefixed(func(recordNumbers *cryptobyte.Builder) { |
| 1145 | for _, r := range records { |
| 1146 | recordNumbers.AddUint64(r.Epoch) |
| 1147 | recordNumbers.AddUint64(r.Sequence) |
| 1148 | } |
| 1149 | }) |
| 1150 | _, _, c.err = c.conn.dtlsPackRecord(c.getOutEpochOrPanic(epoch), recordTypeACK, ack.BytesOrPanic(), false) |
| 1151 | if c.err != nil { |
| 1152 | return |
| 1153 | } |
| 1154 |
| 1155 | // Update the list of expectations. This is inefficient, but is fine for |
| 1156 | // test code. |
| 1157 | for _, r := range records { |
| 1158 | if !r.HasACKInformation() { |
| 1159 | continue |
| 1160 | } |
| 1161 | var update []DTLSFragment |
| 1162 | for _, f := range c.retransmitNeeded { |
| 1163 | endOffset := f.Offset + len(f.Data) |
| 1164 | // Compute two, possibly empty, intersections: the fragment with |
| 1165 | // [0, ackStart) and the fragment with [ackStart, infinity). |
| 1166 |
| 1167 | // First, the portion of the fragment that is before the ACK: |
| 1168 | if comparePair(f.Sequence, f.Offset, r.MessageStartSequence, r.MessageStartOffset) < 0 { |
| 1169 | // The fragment begins before the ACK. |
| 1170 | if comparePair(f.Sequence, endOffset, r.MessageStartSequence, r.MessageStartOffset) <= 0 { |
| 1171 | // The fragment ends before the ACK. |
| 1172 | update = append(update, f) |
| 1173 | } else { |
| 1174 | // The ACK starts in the middle of the fragment. Retain a |
| 1175 | // prefix of the fragment. |
| 1176 | prefix := f |
| 1177 | prefix.Data = f.Data[:r.MessageStartOffset-f.Offset] |
| 1178 | update = append(update, prefix) |
| 1179 | } |
| 1180 | } |
| 1181 |
| 1182 | // Next, the portion of the fragment that is after the ACK: |
| 1183 | if comparePair(r.MessageEndSequence, r.MessageEndOffset, f.Sequence, endOffset) < 0 { |
| 1184 | // The fragment ends after the ACK. |
| 1185 | if comparePair(r.MessageEndSequence, r.MessageEndOffset, f.Sequence, f.Offset) <= 0 { |
| 1186 | // The fragment begins after the ACK. |
| 1187 | update = append(update, f) |
| 1188 | } else { |
| 1189 | // The ACK ends in the middle of the fragment. Retain a |
| 1190 | // suffix of the fragment. |
| 1191 | suffix := f |
| 1192 | suffix.Offset = r.MessageEndOffset |
| 1193 | suffix.Data = f.Data[r.MessageEndOffset-f.Offset:] |
| 1194 | update = append(update, suffix) |
| 1195 | } |
| 1196 | } |
| 1197 | } |
| 1198 | c.retransmitNeeded = update |
| 1199 | } |
| 1200 | } |
| 1201 |
| 1202 | // ReadRetransmit indicates the shim is expected to retransmit its current |
| 1203 | // flight and consumes the retransmission. It returns the record numbers of the |
| 1204 | // retransmission, for the test to ACK if it chooses. |
| 1205 | func (c *DTLSController) ReadRetransmit() []DTLSRecordNumberInfo { |
| 1206 | if c.err != nil { |
| 1207 | return nil |
| 1208 | } |
| 1209 |
| 1210 | var ret []DTLSRecordNumberInfo |
| 1211 | ret, c.err = c.doReadRetransmit() |
| 1212 | return ret |
| 1213 | } |
| 1214 |
| 1215 | func (c *DTLSController) doReadRetransmit() ([]DTLSRecordNumberInfo, error) { |
| 1216 | if err := c.conn.dtlsFlushPacket(); err != nil { |
| 1217 | return nil, err |
| 1218 | } |
| 1219 |
| 1220 | var records []DTLSRecordNumberInfo |
| 1221 | expected := slices.Clone(c.retransmitNeeded) |
| 1222 | for len(expected) > 0 { |
| 1223 | // Read a record from the expected epoch. The peer should retransmit in |
| 1224 | // order. |
| 1225 | wantTyp := recordTypeHandshake |
| 1226 | if expected[0].IsChangeCipherSpec { |
| 1227 | wantTyp = recordTypeChangeCipherSpec |
| 1228 | } |
| 1229 | epoch := c.getInEpochOrPanic(expected[0].Epoch) |
| 1230 | // Retransmitted ClientHellos predate the shim learning the version. |
| 1231 | // Ideally we would enforce the initial record-layer version, but |
| 1232 | // post-HelloVerifyRequest ClientHellos and post-HelloRetryRequest |
| 1233 | // ClientHellos look the same, but have different expectations. |
| 1234 | c.conn.skipRecordVersionCheck = !expected[0].IsChangeCipherSpec && expected[0].Type == typeClientHello |
| 1235 | typ, data, err := c.conn.dtlsDoReadRecord(epoch, wantTyp) |
| 1236 | c.conn.skipRecordVersionCheck = false |
| 1237 | if err != nil { |
| 1238 | return nil, err |
| 1239 | } |
| 1240 | if typ != wantTyp { |
| 1241 | return nil, fmt.Errorf("tls: got record of type %d in retransmit, but expected %d", typ, wantTyp) |
| 1242 | } |
| 1243 | if typ == recordTypeChangeCipherSpec { |
| 1244 | if len(data) != 1 || data[0] != 1 { |
| 1245 | return nil, errors.New("tls: got invalid ChangeCipherSpec") |
| 1246 | } |
| 1247 | expected = expected[1:] |
| 1248 | continue |
| 1249 | } |
| 1250 |
| 1251 | // Consume all the handshake fragments and match them to what we expect. |
| 1252 | s := cryptobyte.String(data) |
| 1253 | if s.Empty() { |
| 1254 | return nil, fmt.Errorf("tls: got empty record in retransmit") |
| 1255 | } |
| 1256 | for !s.Empty() { |
| 1257 | if len(expected) == 0 || expected[0].Epoch != epoch.epoch || expected[0].IsChangeCipherSpec { |
| 1258 | return nil, fmt.Errorf("tls: got excess data at epoch %d in retransmit", epoch.epoch) |
| 1259 | } |
| 1260 |
| 1261 | exp := &expected[0] |
| 1262 | var f DTLSFragment |
| 1263 | f, err = readDTLSFragment(&s) |
| 1264 | if f.Type != exp.Type || f.TotalLength != exp.TotalLength || f.Sequence != exp.Sequence || f.Offset != exp.Offset { |
| 1265 | return nil, fmt.Errorf("tls: got offset %d of message %d (type %d, length %d), expected offset %d of message %d (type %d, length %d)", f.Offset, f.Sequence, f.Type, f.TotalLength, exp.Offset, exp.Sequence, exp.Type, exp.TotalLength) |
| 1266 | } |
| 1267 | if len(f.Data) > len(exp.Data) { |
| 1268 | return nil, fmt.Errorf("tls: got %d bytes at offset %d of message %d but only %d bytes were missing", len(f.Data), f.Offset, f.Sequence, len(exp.Data)) |
| 1269 | } |
| 1270 | if !bytes.Equal(f.Data, exp.Data[:len(f.Data)]) { |
| 1271 | return nil, fmt.Errorf("tls: got %d bytes at offset %d of message %d but did not match original", len(f.Data), f.Offset, f.Sequence) |
| 1272 | } |
| 1273 | if len(f.Data) == len(exp.Data) { |
| 1274 | expected = expected[1:] |
| 1275 | } else { |
| 1276 | // We only got part of the fragment we wanted. |
| 1277 | exp.Offset += len(f.Data) |
| 1278 | exp.Data = exp.Data[len(f.Data):] |
| 1279 | // Check that the peer could not have fit more into the record. |
| 1280 | if !s.Empty() { |
| 1281 | return nil, errors.New("dtls: truncated handshake fragment was not last in the record") |
| 1282 | } |
| 1283 | if c.conn.lastRecordInFlight.bytesAvailable > 0 { |
| 1284 | return nil, fmt.Errorf("dtls: handshake fragment was truncated, but record could have fit %d more bytes", c.conn.lastRecordInFlight.bytesAvailable) |
| 1285 | } |
| 1286 | } |
| 1287 | } |
| 1288 |
| 1289 | record, err := c.conn.makeDTLSRecordNumberInfo(epoch, data) |
| 1290 | if err != nil { |
| 1291 | return nil, err |
| 1292 | } |
| 1293 | records = append(records, record) |
| 1294 | } |
| 1295 | return records, nil |
| 1296 | } |
| 1297 |
| 1298 | // ReadACK indicates the shim is expected to send an ACK at the specified epoch. |
| 1299 | // The contents of the ACK are checked against the connection's internal |
| 1300 | // simulation of the shim's expected behavior. |
| 1301 | func (c *DTLSController) ReadACK(epoch uint16) { |
| 1302 | if c.err != nil { |
| 1303 | return |
| 1304 | } |
| 1305 |
| 1306 | c.err = c.conn.dtlsFlushPacket() |
| 1307 | if c.err != nil { |
| 1308 | return |
| 1309 | } |
| 1310 |
| 1311 | typ, data, err := c.conn.dtlsDoReadRecord(c.getInEpochOrPanic(epoch), recordTypeACK) |
| 1312 | if err != nil { |
| 1313 | c.err = err |
| 1314 | return |
| 1315 | } |
| 1316 | if typ != recordTypeACK { |
| 1317 | c.err = fmt.Errorf("tls: got record of type %d, but expected ACK", typ) |
| 1318 | return |
| 1319 | } |
| 1320 |
| 1321 | c.err = c.conn.checkACK(data) |
| 1322 | } |
| 1323 |
| 1324 | // WriteAppData writes an application data record to the shim. This may be used |
| 1325 | // to test that post-handshake retransmits may interleave with application data. |
| 1326 | func (c *DTLSController) WriteAppData(epoch uint16, data []byte) { |
| 1327 | if c.err != nil { |
| 1328 | return |
| 1329 | } |
| 1330 |
| 1331 | _, _, c.err = c.conn.dtlsPackRecord(c.getOutEpochOrPanic(epoch), recordTypeApplicationData, data, false) |
| 1332 | } |
| 1333 |
| 1334 | // ReadAppData indicates the shim is expected to send the specified application |
| 1335 | // data record. This may be used to test that post-handshake retransmits may |
| 1336 | // interleave with application data. |
| 1337 | func (c *DTLSController) ReadAppData(epoch uint16, expected []byte) { |
| 1338 | if c.err != nil { |
| 1339 | return |
| 1340 | } |
| 1341 |
| 1342 | if err := c.conn.dtlsFlushPacket(); err != nil { |
| 1343 | c.err = err |
| 1344 | return |
| 1345 | } |
| 1346 |
| 1347 | typ, data, err := c.conn.dtlsDoReadRecord(c.getInEpochOrPanic(epoch), recordTypeApplicationData) |
| 1348 | if err != nil { |
| 1349 | c.err = err |
| 1350 | return |
| 1351 | } |
| 1352 | if typ != recordTypeApplicationData { |
| 1353 | c.err = fmt.Errorf("tls: got record of type %d, but expected application data", typ) |
| 1354 | return |
| 1355 | } |
| 1356 | if !bytes.Equal(data, expected) { |
| 1357 | c.err = fmt.Errorf("tls: got app data record containing %x, but expected %x", data, expected) |
| 1358 | return |
| 1359 | } |
| 1360 | } |
| 1361 |
| 1362 | // ExpectNextTimeout indicates the shim's next timeout should be d from now. |
| 1363 | func (c *DTLSController) ExpectNextTimeout(d time.Duration) { |
| 1364 | if c.err != nil { |
| 1365 | return |
| 1366 | } |
| 1367 | if err := c.conn.dtlsFlushPacket(); err != nil { |
| 1368 | c.err = err |
| 1369 | return |
| 1370 | } |
| 1371 | c.err = c.conn.config.Bugs.PacketAdaptor.ExpectNextTimeout(d) |
| 1372 | } |
| 1373 |
| 1374 | // ExpectNoNext indicates the shim should not have a next timeout. |
| 1375 | func (c *DTLSController) ExpectNoNextTimeout() { |
| 1376 | if c.err != nil { |
| 1377 | return |
| 1378 | } |
| 1379 | if err := c.conn.dtlsFlushPacket(); err != nil { |
| 1380 | c.err = err |
| 1381 | return |
| 1382 | } |
| 1383 | c.err = c.conn.config.Bugs.PacketAdaptor.ExpectNoNextTimeout() |
| 1384 | } |
| 1385 |
| 1386 | // MergeIntoNextFlight indicates the state from this flight should be merged |
| 1387 | // into the next WriteFlight or ACKFlight call. This allows the test to control |
| 1388 | // two independent post-handshake messages as a single unit. |
| 1389 | func (c *DTLSController) MergeIntoNextFlight() { |
| 1390 | c.mergeIntoNextFlight = true |
| 1391 | } |
| 1392 |