Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

432 rindas
13 KiB

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