| 1 |
// Copyright 2014 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// DTLS implementation. |
| 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 |
"errors" |
| 20 |
"fmt" |
| 21 |
"io" |
| 22 |
"math/rand" |
| 23 |
"net" |
| 24 |
) |
| 25 |
|
| 26 |
func versionToWire(vers uint16, isDTLS bool) uint16 { |
| 27 |
if isDTLS { |
| 28 |
return ^(vers - 0x0201) |
| 29 |
} |
| 30 |
return vers |
| 31 |
} |
| 32 |
|
| 33 |
func wireToVersion(vers uint16, isDTLS bool) uint16 { |
| 34 |
if isDTLS { |
| 35 |
return ^vers + 0x0201 |
| 36 |
} |
| 37 |
return vers |
| 38 |
} |
| 39 |
|
| 40 |
func (c *Conn) dtlsDoReadRecord(want recordType) (recordType, *block, error) { |
| 41 |
recordHeaderLen := dtlsRecordHeaderLen |
| 42 |
|
| 43 |
if c.rawInput == nil { |
| 44 |
c.rawInput = c.in.newBlock() |
| 45 |
} |
| 46 |
b := c.rawInput |
| 47 |
|
| 48 |
// Read a new packet only if the current one is empty. |
| 49 |
var newPacket bool |
| 50 |
if len(b.data) == 0 { |
| 51 |
// Pick some absurdly large buffer size. |
| 52 |
b.resize(maxCiphertext + recordHeaderLen) |
| 53 |
n, err := c.conn.Read(c.rawInput.data) |
| 54 |
if err != nil { |
| 55 |
return 0, nil, err |
| 56 |
} |
| 57 |
if c.config.Bugs.MaxPacketLength != 0 && n > c.config.Bugs.MaxPacketLength { |
| 58 |
return 0, nil, fmt.Errorf("dtls: exceeded maximum packet length") |
| 59 |
} |
| 60 |
c.rawInput.resize(n) |
| 61 |
newPacket = true |
| 62 |
} |
| 63 |
|
| 64 |
// Read out one record. |
| 65 |
// |
| 66 |
// A real DTLS implementation should be tolerant of errors, |
| 67 |
// but this is test code. We should not be tolerant of our |
| 68 |
// peer sending garbage. |
| 69 |
if len(b.data) < recordHeaderLen { |
| 70 |
return 0, nil, errors.New("dtls: failed to read record header") |
| 71 |
} |
| 72 |
typ := recordType(b.data[0]) |
| 73 |
vers := wireToVersion(uint16(b.data[1])<<8|uint16(b.data[2]), c.isDTLS) |
| 74 |
if c.haveVers { |
| 75 |
if vers != c.vers { |
| 76 |
c.sendAlert(alertProtocolVersion) |
| 77 |
return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: received record with version %x when expecting version %x", vers, c.vers)) |
| 78 |
} |
| 79 |
} else { |
| 80 |
if expect := c.config.Bugs.ExpectInitialRecordVersion; expect != 0 && vers != expect { |
| 81 |
c.sendAlert(alertProtocolVersion) |
| 82 |
return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: received record with version %x when expecting version %x", vers, expect)) |
| 83 |
} |
| 84 |
} |
| 85 |
epoch := b.data[3:5] |
| 86 |
seq := b.data[5:11] |
| 87 |
// For test purposes, require the sequence number be monotonically |
| 88 |
// increasing, so c.in includes the minimum next sequence number. Gaps |
| 89 |
// may occur if packets failed to be sent out. A real implementation |
| 90 |
// would maintain a replay window and such. |
| 91 |
if !bytes.Equal(epoch, c.in.seq[:2]) { |
| 92 |
c.sendAlert(alertIllegalParameter) |
| 93 |
return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: bad epoch")) |
| 94 |
} |
| 95 |
if bytes.Compare(seq, c.in.seq[2:]) < 0 { |
| 96 |
c.sendAlert(alertIllegalParameter) |
| 97 |
return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: bad sequence number")) |
| 98 |
} |
| 99 |
copy(c.in.seq[2:], seq) |
| 100 |
n := int(b.data[11])<<8 | int(b.data[12]) |
| 101 |
if n > maxCiphertext || len(b.data) < recordHeaderLen+n { |
| 102 |
c.sendAlert(alertRecordOverflow) |
| 103 |
return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: oversized record received with length %d", n)) |
| 104 |
} |
| 105 |
|
| 106 |
// Process message. |
| 107 |
b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n) |
| 108 |
ok, off, err := c.in.decrypt(b) |
| 109 |
if !ok { |
| 110 |
c.in.setErrorLocked(c.sendAlert(err)) |
| 111 |
} |
| 112 |
b.off = off |
| 113 |
|
| 114 |
// Require that ChangeCipherSpec always share a packet with either the |
| 115 |
// previous or next handshake message. |
| 116 |
if newPacket && typ == recordTypeChangeCipherSpec && c.rawInput == nil { |
| 117 |
return 0, nil, c.in.setErrorLocked(fmt.Errorf("dtls: ChangeCipherSpec not packed together with Finished")) |
| 118 |
} |
| 119 |
|
| 120 |
return typ, b, nil |
| 121 |
} |
| 122 |
|
| 123 |
func (c *Conn) makeFragment(header, data []byte, fragOffset, fragLen int) []byte { |
| 124 |
fragment := make([]byte, 0, 12+fragLen) |
| 125 |
fragment = append(fragment, header...) |
| 126 |
fragment = append(fragment, byte(c.sendHandshakeSeq>>8), byte(c.sendHandshakeSeq)) |
| 127 |
fragment = append(fragment, byte(fragOffset>>16), byte(fragOffset>>8), byte(fragOffset)) |
| 128 |
fragment = append(fragment, byte(fragLen>>16), byte(fragLen>>8), byte(fragLen)) |
| 129 |
fragment = append(fragment, data[fragOffset:fragOffset+fragLen]...) |
| 130 |
return fragment |
| 131 |
} |
| 132 |
|
| 133 |
func (c *Conn) dtlsWriteRecord(typ recordType, data []byte) (n int, err error) { |
| 134 |
if typ != recordTypeHandshake { |
| 135 |
// Only handshake messages are fragmented. |
| 136 |
return c.dtlsWriteRawRecord(typ, data) |
| 137 |
} |
| 138 |
|
| 139 |
maxLen := c.config.Bugs.MaxHandshakeRecordLength |
| 140 |
if maxLen <= 0 { |
| 141 |
maxLen = 1024 |
| 142 |
} |
| 143 |
|
| 144 |
// Handshake messages have to be modified to include fragment |
| 145 |
// offset and length and with the header replicated. Save the |
| 146 |
// TLS header here. |
| 147 |
// |
| 148 |
// TODO(davidben): This assumes that data contains exactly one |
| 149 |
// handshake message. This is incompatible with |
| 150 |
// FragmentAcrossChangeCipherSpec. (Which is unfortunate |
| 151 |
// because OpenSSL's DTLS implementation will probably accept |
| 152 |
// such fragmentation and could do with a fix + tests.) |
| 153 |
header := data[:4] |
| 154 |
data = data[4:] |
| 155 |
|
| 156 |
isFinished := header[0] == typeFinished |
| 157 |
|
| 158 |
if c.config.Bugs.SendEmptyFragments { |
| 159 |
fragment := c.makeFragment(header, data, 0, 0) |
| 160 |
c.pendingFragments = append(c.pendingFragments, fragment) |
| 161 |
} |
| 162 |
|
| 163 |
firstRun := true |
| 164 |
fragOffset := 0 |
| 165 |
for firstRun || fragOffset < len(data) { |
| 166 |
firstRun = false |
| 167 |
fragLen := len(data) - fragOffset |
| 168 |
if fragLen > maxLen { |
| 169 |
fragLen = maxLen |
| 170 |
} |
| 171 |
|
| 172 |
fragment := c.makeFragment(header, data, fragOffset, fragLen) |
| 173 |
if c.config.Bugs.FragmentMessageTypeMismatch && fragOffset > 0 { |
| 174 |
fragment[0]++ |
| 175 |
} |
| 176 |
if c.config.Bugs.FragmentMessageLengthMismatch && fragOffset > 0 { |
| 177 |
fragment[3]++ |
| 178 |
} |
| 179 |
|
| 180 |
// Buffer the fragment for later. They will be sent (and |
| 181 |
// reordered) on flush. |
| 182 |
c.pendingFragments = append(c.pendingFragments, fragment) |
| 183 |
if c.config.Bugs.ReorderHandshakeFragments { |
| 184 |
// Don't duplicate Finished to avoid the peer |
| 185 |
// interpreting it as a retransmit request. |
| 186 |
if !isFinished { |
| 187 |
c.pendingFragments = append(c.pendingFragments, fragment) |
| 188 |
} |
| 189 |
|
| 190 |
if fragLen > (maxLen+1)/2 { |
| 191 |
// Overlap each fragment by half. |
| 192 |
fragLen = (maxLen + 1) / 2 |
| 193 |
} |
| 194 |
} |
| 195 |
fragOffset += fragLen |
| 196 |
n += fragLen |
| 197 |
} |
| 198 |
if !isFinished && c.config.Bugs.MixCompleteMessageWithFragments { |
| 199 |
fragment := c.makeFragment(header, data, 0, len(data)) |
| 200 |
c.pendingFragments = append(c.pendingFragments, fragment) |
| 201 |
} |
| 202 |
|
| 203 |
// Increment the handshake sequence number for the next |
| 204 |
// handshake message. |
| 205 |
c.sendHandshakeSeq++ |
| 206 |
return |
| 207 |
} |
| 208 |
|
| 209 |
func (c *Conn) dtlsFlushHandshake() error { |
| 210 |
if !c.isDTLS { |
| 211 |
return nil |
| 212 |
} |
| 213 |
|
| 214 |
// This is a test-only DTLS implementation, so there is no need to |
| 215 |
// retain |c.pendingFragments| for a future retransmit. |
| 216 |
var fragments [][]byte |
| 217 |
fragments, c.pendingFragments = c.pendingFragments, fragments |
| 218 |
|
| 219 |
if c.config.Bugs.ReorderHandshakeFragments { |
| 220 |
perm := rand.New(rand.NewSource(0)).Perm(len(fragments)) |
| 221 |
tmp := make([][]byte, len(fragments)) |
| 222 |
for i := range tmp { |
| 223 |
tmp[i] = fragments[perm[i]] |
| 224 |
} |
| 225 |
fragments = tmp |
| 226 |
} |
| 227 |
|
| 228 |
maxRecordLen := c.config.Bugs.PackHandshakeFragments |
| 229 |
maxPacketLen := c.config.Bugs.PackHandshakeRecords |
| 230 |
|
| 231 |
// Pack handshake fragments into records. |
| 232 |
var records [][]byte |
| 233 |
for _, fragment := range fragments { |
| 234 |
if n := c.config.Bugs.SplitFragments; n > 0 { |
| 235 |
if len(fragment) > n { |
| 236 |
records = append(records, fragment[:n]) |
| 237 |
records = append(records, fragment[n:]) |
| 238 |
} else { |
| 239 |
records = append(records, fragment) |
| 240 |
} |
| 241 |
} else if i := len(records) - 1; len(records) > 0 && len(records[i])+len(fragment) <= maxRecordLen { |
| 242 |
records[i] = append(records[i], fragment...) |
| 243 |
} else { |
| 244 |
// The fragment will be appended to, so copy it. |
| 245 |
records = append(records, append([]byte{}, fragment...)) |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
// Format them into packets. |
| 250 |
var packets [][]byte |
| 251 |
for _, record := range records { |
| 252 |
b, err := c.dtlsSealRecord(recordTypeHandshake, record) |
| 253 |
if err != nil { |
| 254 |
return err |
| 255 |
} |
| 256 |
|
| 257 |
if i := len(packets) - 1; len(packets) > 0 && len(packets[i])+len(b.data) <= maxPacketLen { |
| 258 |
packets[i] = append(packets[i], b.data...) |
| 259 |
} else { |
| 260 |
// The sealed record will be appended to and reused by |
| 261 |
// |c.out|, so copy it. |
| 262 |
packets = append(packets, append([]byte{}, b.data...)) |
| 263 |
} |
| 264 |
c.out.freeBlock(b) |
| 265 |
} |
| 266 |
|
| 267 |
// Send all the packets. |
| 268 |
for _, packet := range packets { |
| 269 |
if _, err := c.conn.Write(packet); err != nil { |
| 270 |
return err |
| 271 |
} |
| 272 |
} |
| 273 |
return nil |
| 274 |
} |
| 275 |
|
| 276 |
// dtlsSealRecord seals a record into a block from |c.out|'s pool. |
| 277 |
func (c *Conn) dtlsSealRecord(typ recordType, data []byte) (b *block, err error) { |
| 278 |
recordHeaderLen := dtlsRecordHeaderLen |
| 279 |
maxLen := c.config.Bugs.MaxHandshakeRecordLength |
| 280 |
if maxLen <= 0 { |
| 281 |
maxLen = 1024 |
| 282 |
} |
| 283 |
|
| 284 |
b = c.out.newBlock() |
| 285 |
|
| 286 |
explicitIVLen := 0 |
| 287 |
explicitIVIsSeq := false |
| 288 |
|
| 289 |
if cbc, ok := c.out.cipher.(cbcMode); ok { |
| 290 |
// Block cipher modes have an explicit IV. |
| 291 |
explicitIVLen = cbc.BlockSize() |
| 292 |
} else if aead, ok := c.out.cipher.(*tlsAead); ok { |
| 293 |
if aead.explicitNonce { |
| 294 |
explicitIVLen = 8 |
| 295 |
// The AES-GCM construction in TLS has an explicit nonce so that |
| 296 |
// the nonce can be random. However, the nonce is only 8 bytes |
| 297 |
// which is too small for a secure, random nonce. Therefore we |
| 298 |
// use the sequence number as the nonce. |
| 299 |
explicitIVIsSeq = true |
| 300 |
} |
| 301 |
} else if c.out.cipher != nil { |
| 302 |
panic("Unknown cipher") |
| 303 |
} |
| 304 |
b.resize(recordHeaderLen + explicitIVLen + len(data)) |
| 305 |
b.data[0] = byte(typ) |
| 306 |
vers := c.vers |
| 307 |
if vers == 0 { |
| 308 |
// Some TLS servers fail if the record version is greater than |
| 309 |
// TLS 1.0 for the initial ClientHello. |
| 310 |
vers = VersionTLS10 |
| 311 |
} |
| 312 |
vers = versionToWire(vers, c.isDTLS) |
| 313 |
b.data[1] = byte(vers >> 8) |
| 314 |
b.data[2] = byte(vers) |
| 315 |
// DTLS records include an explicit sequence number. |
| 316 |
copy(b.data[3:11], c.out.outSeq[0:]) |
| 317 |
b.data[11] = byte(len(data) >> 8) |
| 318 |
b.data[12] = byte(len(data)) |
| 319 |
if explicitIVLen > 0 { |
| 320 |
explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] |
| 321 |
if explicitIVIsSeq { |
| 322 |
copy(explicitIV, c.out.outSeq[:]) |
| 323 |
} else { |
| 324 |
if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { |
| 325 |
return |
| 326 |
} |
| 327 |
} |
| 328 |
} |
| 329 |
copy(b.data[recordHeaderLen+explicitIVLen:], data) |
| 330 |
c.out.encrypt(b, explicitIVLen) |
| 331 |
return |
| 332 |
} |
| 333 |
|
| 334 |
func (c *Conn) dtlsWriteRawRecord(typ recordType, data []byte) (n int, err error) { |
| 335 |
b, err := c.dtlsSealRecord(typ, data) |
| 336 |
if err != nil { |
| 337 |
return |
| 338 |
} |
| 339 |
|
| 340 |
_, err = c.conn.Write(b.data) |
| 341 |
if err != nil { |
| 342 |
return |
| 343 |
} |
| 344 |
n = len(data) |
| 345 |
|
| 346 |
c.out.freeBlock(b) |
| 347 |
|
| 348 |
if typ == recordTypeChangeCipherSpec { |
| 349 |
err = c.out.changeCipherSpec(c.config) |
| 350 |
if err != nil { |
| 351 |
// Cannot call sendAlert directly, |
| 352 |
// because we already hold c.out.Mutex. |
| 353 |
c.tmp[0] = alertLevelError |
| 354 |
c.tmp[1] = byte(err.(alert)) |
| 355 |
c.writeRecord(recordTypeAlert, c.tmp[0:2]) |
| 356 |
return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) |
| 357 |
} |
| 358 |
} |
| 359 |
return |
| 360 |
} |
| 361 |
|
| 362 |
func (c *Conn) dtlsDoReadHandshake() ([]byte, error) { |
| 363 |
// Assemble a full handshake message. For test purposes, this |
| 364 |
// implementation assumes fragments arrive in order. It may |
| 365 |
// need to be cleverer if we ever test BoringSSL's retransmit |
| 366 |
// behavior. |
| 367 |
for len(c.handMsg) < 4+c.handMsgLen { |
| 368 |
// Get a new handshake record if the previous has been |
| 369 |
// exhausted. |
| 370 |
if c.hand.Len() == 0 { |
| 371 |
if err := c.in.err; err != nil { |
| 372 |
return nil, err |
| 373 |
} |
| 374 |
if err := c.readRecord(recordTypeHandshake); err != nil { |
| 375 |
return nil, err |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
// Read the next fragment. It must fit entirely within |
| 380 |
// the record. |
| 381 |
if c.hand.Len() < 12 { |
| 382 |
return nil, errors.New("dtls: bad handshake record") |
| 383 |
} |
| 384 |
header := c.hand.Next(12) |
| 385 |
fragN := int(header[1])<<16 | int(header[2])<<8 | int(header[3]) |
| 386 |
fragSeq := uint16(header[4])<<8 | uint16(header[5]) |
| 387 |
fragOff := int(header[6])<<16 | int(header[7])<<8 | int(header[8]) |
| 388 |
fragLen := int(header[9])<<16 | int(header[10])<<8 | int(header[11]) |
| 389 |
|
| 390 |
if c.hand.Len() < fragLen { |
| 391 |
return nil, errors.New("dtls: fragment length too long") |
| 392 |
} |
| 393 |
fragment := c.hand.Next(fragLen) |
| 394 |
|
| 395 |
// Check it's a fragment for the right message. |
| 396 |
if fragSeq != c.recvHandshakeSeq { |
| 397 |
return nil, errors.New("dtls: bad handshake sequence number") |
| 398 |
} |
| 399 |
|
| 400 |
// Check that the length is consistent. |
| 401 |
if c.handMsg == nil { |
| 402 |
c.handMsgLen = fragN |
| 403 |
if c.handMsgLen > maxHandshake { |
| 404 |
return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) |
| 405 |
} |
| 406 |
// Start with the TLS handshake header, |
| 407 |
// without the DTLS bits. |
| 408 |
c.handMsg = append([]byte{}, header[:4]...) |
| 409 |
} else if fragN != c.handMsgLen { |
| 410 |
return nil, errors.New("dtls: bad handshake length") |
| 411 |
} |
| 412 |
|
| 413 |
// Add the fragment to the pending message. |
| 414 |
if 4+fragOff != len(c.handMsg) { |
| 415 |
return nil, errors.New("dtls: bad fragment offset") |
| 416 |
} |
| 417 |
if fragOff+fragLen > c.handMsgLen { |
| 418 |
return nil, errors.New("dtls: bad fragment length") |
| 419 |
} |
| 420 |
c.handMsg = append(c.handMsg, fragment...) |
| 421 |
} |
| 422 |
c.recvHandshakeSeq++ |
| 423 |
ret := c.handMsg |
| 424 |
c.handMsg, c.handMsgLen = nil, 0 |
| 425 |
return ret, nil |
| 426 |
} |
| 427 |
|
| 428 |
// DTLSServer returns a new DTLS server side connection |
| 429 |
// using conn as the underlying transport. |
| 430 |
// The configuration config must be non-nil and must have |
| 431 |
// at least one certificate. |
| 432 |
func DTLSServer(conn net.Conn, config *Config) *Conn { |
| 433 |
c := &Conn{config: config, isDTLS: true, conn: conn} |
| 434 |
c.init() |
| 435 |
return c |
| 436 |
} |
| 437 |
|
| 438 |
// DTLSClient returns a new DTLS client side connection |
| 439 |
// using conn as the underlying transport. |
| 440 |
// The config cannot be nil: users must set either ServerHostname or |
| 441 |
// InsecureSkipVerify in the config. |
| 442 |
func DTLSClient(conn net.Conn, config *Config) *Conn { |
| 443 |
c := &Conn{config: config, isClient: true, isDTLS: true, conn: conn} |
| 444 |
c.init() |
| 445 |
return c |
| 446 |
} |