conn_test.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  1. package dtls
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/rand"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net"
  12. "sync"
  13. "sync/atomic"
  14. "testing"
  15. "time"
  16. "github.com/pion/dtls/v2/internal/ciphersuite"
  17. "github.com/pion/dtls/v2/internal/net/dpipe"
  18. "github.com/pion/dtls/v2/pkg/crypto/elliptic"
  19. "github.com/pion/dtls/v2/pkg/crypto/hash"
  20. "github.com/pion/dtls/v2/pkg/crypto/selfsign"
  21. "github.com/pion/dtls/v2/pkg/crypto/signature"
  22. "github.com/pion/dtls/v2/pkg/crypto/signaturehash"
  23. "github.com/pion/dtls/v2/pkg/protocol"
  24. "github.com/pion/dtls/v2/pkg/protocol/alert"
  25. "github.com/pion/dtls/v2/pkg/protocol/extension"
  26. "github.com/pion/dtls/v2/pkg/protocol/handshake"
  27. "github.com/pion/dtls/v2/pkg/protocol/recordlayer"
  28. "github.com/pion/transport/test"
  29. )
  30. var (
  31. errTestPSKInvalidIdentity = errors.New("TestPSK: Server got invalid identity")
  32. errPSKRejected = errors.New("PSK Rejected")
  33. errNotExpectedChain = errors.New("not expected chain")
  34. errExpecedChain = errors.New("expected chain")
  35. errWrongCert = errors.New("wrong cert")
  36. )
  37. func TestStressDuplex(t *testing.T) {
  38. // Limit runtime in case of deadlocks
  39. lim := test.TimeOut(time.Second * 20)
  40. defer lim.Stop()
  41. // Check for leaking routines
  42. report := test.CheckRoutines(t)
  43. defer report()
  44. // Run the test
  45. stressDuplex(t)
  46. }
  47. func stressDuplex(t *testing.T) {
  48. ca, cb, err := pipeMemory()
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. defer func() {
  53. err = ca.Close()
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. err = cb.Close()
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. }()
  62. opt := test.Options{
  63. MsgSize: 2048,
  64. MsgCount: 100,
  65. }
  66. err = test.StressDuplex(ca, cb, opt)
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. }
  71. func TestRoutineLeakOnClose(t *testing.T) {
  72. // Limit runtime in case of deadlocks
  73. lim := test.TimeOut(5 * time.Second)
  74. defer lim.Stop()
  75. // Check for leaking routines
  76. report := test.CheckRoutines(t)
  77. defer report()
  78. ca, cb, err := pipeMemory()
  79. if err != nil {
  80. t.Fatal(err)
  81. }
  82. if _, err := ca.Write(make([]byte, 100)); err != nil {
  83. t.Fatal(err)
  84. }
  85. if err := cb.Close(); err != nil {
  86. t.Fatal(err)
  87. }
  88. if err := ca.Close(); err != nil {
  89. t.Fatal(err)
  90. }
  91. // Packet is sent, but not read.
  92. // inboundLoop routine should not be leaked.
  93. }
  94. func TestReadWriteDeadline(t *testing.T) {
  95. // Limit runtime in case of deadlocks
  96. lim := test.TimeOut(5 * time.Second)
  97. defer lim.Stop()
  98. // Check for leaking routines
  99. report := test.CheckRoutines(t)
  100. defer report()
  101. ca, cb, err := pipeMemory()
  102. if err != nil {
  103. t.Fatal(err)
  104. }
  105. if err := ca.SetDeadline(time.Unix(0, 1)); err != nil {
  106. t.Fatal(err)
  107. }
  108. _, werr := ca.Write(make([]byte, 100))
  109. if e, ok := werr.(net.Error); ok {
  110. if !e.Timeout() {
  111. t.Error("Deadline exceeded Write must return Timeout error")
  112. }
  113. if !e.Temporary() {
  114. t.Error("Deadline exceeded Write must return Temporary error")
  115. }
  116. } else {
  117. t.Error("Write must return net.Error error")
  118. }
  119. _, rerr := ca.Read(make([]byte, 100))
  120. if e, ok := rerr.(net.Error); ok {
  121. if !e.Timeout() {
  122. t.Error("Deadline exceeded Read must return Timeout error")
  123. }
  124. if !e.Temporary() {
  125. t.Error("Deadline exceeded Read must return Temporary error")
  126. }
  127. } else {
  128. t.Error("Read must return net.Error error")
  129. }
  130. if err := ca.SetDeadline(time.Time{}); err != nil {
  131. t.Error(err)
  132. }
  133. if err := ca.Close(); err != nil {
  134. t.Error(err)
  135. }
  136. if err := cb.Close(); err != nil {
  137. t.Error(err)
  138. }
  139. if _, err := ca.Write(make([]byte, 100)); !errors.Is(err, ErrConnClosed) {
  140. t.Errorf("Write must return %v after close, got %v", ErrConnClosed, err)
  141. }
  142. if _, err := ca.Read(make([]byte, 100)); !errors.Is(err, io.EOF) {
  143. t.Errorf("Read must return %v after close, got %v", io.EOF, err)
  144. }
  145. }
  146. func TestSequenceNumberOverflow(t *testing.T) {
  147. // Limit runtime in case of deadlocks
  148. lim := test.TimeOut(5 * time.Second)
  149. defer lim.Stop()
  150. // Check for leaking routines
  151. report := test.CheckRoutines(t)
  152. defer report()
  153. t.Run("ApplicationData", func(t *testing.T) {
  154. ca, cb, err := pipeMemory()
  155. if err != nil {
  156. t.Fatal(err)
  157. }
  158. atomic.StoreUint64(&ca.state.localSequenceNumber[1], recordlayer.MaxSequenceNumber)
  159. if _, werr := ca.Write(make([]byte, 100)); werr != nil {
  160. t.Errorf("Write must send message with maximum sequence number, but errord: %v", werr)
  161. }
  162. if _, werr := ca.Write(make([]byte, 100)); !errors.Is(werr, errSequenceNumberOverflow) {
  163. t.Errorf("Write must abandonsend message with maximum sequence number, but errord: %v", werr)
  164. }
  165. if err := ca.Close(); err != nil {
  166. t.Error(err)
  167. }
  168. if err := cb.Close(); err != nil {
  169. t.Error(err)
  170. }
  171. })
  172. t.Run("Handshake", func(t *testing.T) {
  173. ca, cb, err := pipeMemory()
  174. if err != nil {
  175. t.Fatal(err)
  176. }
  177. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  178. defer cancel()
  179. atomic.StoreUint64(&ca.state.localSequenceNumber[0], recordlayer.MaxSequenceNumber+1)
  180. // Try to send handshake packet.
  181. if werr := ca.writePackets(ctx, []*packet{
  182. {
  183. record: &recordlayer.RecordLayer{
  184. Header: recordlayer.Header{
  185. Version: protocol.Version1_2,
  186. },
  187. Content: &handshake.Handshake{
  188. Message: &handshake.MessageClientHello{
  189. Version: protocol.Version1_2,
  190. Cookie: make([]byte, 64),
  191. CipherSuiteIDs: cipherSuiteIDs(defaultCipherSuites()),
  192. CompressionMethods: defaultCompressionMethods(),
  193. },
  194. },
  195. },
  196. },
  197. }); !errors.Is(werr, errSequenceNumberOverflow) {
  198. t.Errorf("Connection must fail on handshake packet reaches maximum sequence number")
  199. }
  200. if err := ca.Close(); err != nil {
  201. t.Error(err)
  202. }
  203. if err := cb.Close(); err != nil {
  204. t.Error(err)
  205. }
  206. })
  207. }
  208. func pipeMemory() (*Conn, *Conn, error) {
  209. // In memory pipe
  210. ca, cb := dpipe.Pipe()
  211. return pipeConn(ca, cb)
  212. }
  213. func pipeConn(ca, cb net.Conn) (*Conn, *Conn, error) {
  214. type result struct {
  215. c *Conn
  216. err error
  217. }
  218. c := make(chan result)
  219. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  220. defer cancel()
  221. // Setup client
  222. go func() {
  223. client, err := testClient(ctx, ca, &Config{SRTPProtectionProfiles: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80}}, true)
  224. c <- result{client, err}
  225. }()
  226. // Setup server
  227. server, err := testServer(ctx, cb, &Config{SRTPProtectionProfiles: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80}}, true)
  228. if err != nil {
  229. return nil, nil, err
  230. }
  231. // Receive client
  232. res := <-c
  233. if res.err != nil {
  234. return nil, nil, res.err
  235. }
  236. return res.c, server, nil
  237. }
  238. func testClient(ctx context.Context, c net.Conn, cfg *Config, generateCertificate bool) (*Conn, error) {
  239. if generateCertificate {
  240. clientCert, err := selfsign.GenerateSelfSigned()
  241. if err != nil {
  242. return nil, err
  243. }
  244. cfg.Certificates = []tls.Certificate{clientCert}
  245. }
  246. cfg.InsecureSkipVerify = true
  247. return ClientWithContext(ctx, c, cfg)
  248. }
  249. func testServer(ctx context.Context, c net.Conn, cfg *Config, generateCertificate bool) (*Conn, error) {
  250. if generateCertificate {
  251. serverCert, err := selfsign.GenerateSelfSigned()
  252. if err != nil {
  253. return nil, err
  254. }
  255. cfg.Certificates = []tls.Certificate{serverCert}
  256. }
  257. return ServerWithContext(ctx, c, cfg)
  258. }
  259. func TestHandshakeWithAlert(t *testing.T) {
  260. // Limit runtime in case of deadlocks
  261. lim := test.TimeOut(time.Second * 20)
  262. defer lim.Stop()
  263. // Check for leaking routines
  264. report := test.CheckRoutines(t)
  265. defer report()
  266. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  267. defer cancel()
  268. cases := map[string]struct {
  269. configServer, configClient *Config
  270. errServer, errClient error
  271. }{
  272. "CipherSuiteNoIntersection": {
  273. configServer: &Config{
  274. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  275. },
  276. configClient: &Config{
  277. CipherSuites: []CipherSuiteID{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  278. },
  279. errServer: errCipherSuiteNoIntersection,
  280. errClient: &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  281. },
  282. "SignatureSchemesNoIntersection": {
  283. configServer: &Config{
  284. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  285. SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP256AndSHA256},
  286. },
  287. configClient: &Config{
  288. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  289. SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP521AndSHA512},
  290. },
  291. errServer: &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  292. errClient: errNoAvailableSignatureSchemes,
  293. },
  294. }
  295. for name, testCase := range cases {
  296. testCase := testCase
  297. t.Run(name, func(t *testing.T) {
  298. clientErr := make(chan error, 1)
  299. ca, cb := dpipe.Pipe()
  300. go func() {
  301. _, err := testClient(ctx, ca, testCase.configClient, true)
  302. clientErr <- err
  303. }()
  304. _, errServer := testServer(ctx, cb, testCase.configServer, true)
  305. if !errors.Is(errServer, testCase.errServer) {
  306. t.Fatalf("Server error exp(%v) failed(%v)", testCase.errServer, errServer)
  307. }
  308. errClient := <-clientErr
  309. if !errors.Is(errClient, testCase.errClient) {
  310. t.Fatalf("Client error exp(%v) failed(%v)", testCase.errClient, errClient)
  311. }
  312. })
  313. }
  314. }
  315. func TestExportKeyingMaterial(t *testing.T) {
  316. // Check for leaking routines
  317. report := test.CheckRoutines(t)
  318. defer report()
  319. var rand [28]byte
  320. exportLabel := "EXTRACTOR-dtls_srtp"
  321. expectedServerKey := []byte{0x61, 0x09, 0x9d, 0x7d, 0xcb, 0x08, 0x52, 0x2c, 0xe7, 0x7b}
  322. expectedClientKey := []byte{0x87, 0xf0, 0x40, 0x02, 0xf6, 0x1c, 0xf1, 0xfe, 0x8c, 0x77}
  323. c := &Conn{
  324. state: State{
  325. localRandom: handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand},
  326. remoteRandom: handshake.Random{GMTUnixTime: time.Unix(1000, 0), RandomBytes: rand},
  327. localSequenceNumber: []uint64{0, 0},
  328. cipherSuite: &ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{},
  329. },
  330. }
  331. c.setLocalEpoch(0)
  332. c.setRemoteEpoch(0)
  333. state := c.ConnectionState()
  334. _, err := state.ExportKeyingMaterial(exportLabel, nil, 0)
  335. if !errors.Is(err, errHandshakeInProgress) {
  336. t.Errorf("ExportKeyingMaterial when epoch == 0: expected '%s' actual '%s'", errHandshakeInProgress, err)
  337. }
  338. c.setLocalEpoch(1)
  339. state = c.ConnectionState()
  340. _, err = state.ExportKeyingMaterial(exportLabel, []byte{0x00}, 0)
  341. if !errors.Is(err, errContextUnsupported) {
  342. t.Errorf("ExportKeyingMaterial with context: expected '%s' actual '%s'", errContextUnsupported, err)
  343. }
  344. for k := range invalidKeyingLabels() {
  345. state = c.ConnectionState()
  346. _, err = state.ExportKeyingMaterial(k, nil, 0)
  347. if !errors.Is(err, errReservedExportKeyingMaterial) {
  348. t.Errorf("ExportKeyingMaterial reserved label: expected '%s' actual '%s'", errReservedExportKeyingMaterial, err)
  349. }
  350. }
  351. state = c.ConnectionState()
  352. keyingMaterial, err := state.ExportKeyingMaterial(exportLabel, nil, 10)
  353. if err != nil {
  354. t.Errorf("ExportKeyingMaterial as server: unexpected error '%s'", err)
  355. } else if !bytes.Equal(keyingMaterial, expectedServerKey) {
  356. t.Errorf("ExportKeyingMaterial client export: expected (% 02x) actual (% 02x)", expectedServerKey, keyingMaterial)
  357. }
  358. c.state.isClient = true
  359. state = c.ConnectionState()
  360. keyingMaterial, err = state.ExportKeyingMaterial(exportLabel, nil, 10)
  361. if err != nil {
  362. t.Errorf("ExportKeyingMaterial as server: unexpected error '%s'", err)
  363. } else if !bytes.Equal(keyingMaterial, expectedClientKey) {
  364. t.Errorf("ExportKeyingMaterial client export: expected (% 02x) actual (% 02x)", expectedClientKey, keyingMaterial)
  365. }
  366. }
  367. func TestPSK(t *testing.T) {
  368. // Limit runtime in case of deadlocks
  369. lim := test.TimeOut(time.Second * 20)
  370. defer lim.Stop()
  371. // Check for leaking routines
  372. report := test.CheckRoutines(t)
  373. defer report()
  374. for _, test := range []struct {
  375. Name string
  376. ServerIdentity []byte
  377. CipherSuites []CipherSuiteID
  378. }{
  379. {
  380. Name: "Server identity specified",
  381. ServerIdentity: []byte("Test Identity"),
  382. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  383. },
  384. {
  385. Name: "Server identity nil",
  386. ServerIdentity: nil,
  387. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  388. },
  389. {
  390. Name: "TLS_PSK_WITH_AES_128_CBC_SHA256",
  391. ServerIdentity: nil,
  392. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CBC_SHA256},
  393. },
  394. } {
  395. test := test
  396. t.Run(test.Name, func(t *testing.T) {
  397. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  398. defer cancel()
  399. clientIdentity := []byte("Client Identity")
  400. type result struct {
  401. c *Conn
  402. err error
  403. }
  404. clientRes := make(chan result, 1)
  405. ca, cb := dpipe.Pipe()
  406. go func() {
  407. conf := &Config{
  408. PSK: func(hint []byte) ([]byte, error) {
  409. if !bytes.Equal(test.ServerIdentity, hint) { // nolint
  410. return nil, fmt.Errorf("TestPSK: Client got invalid identity expected(% 02x) actual(% 02x)", test.ServerIdentity, hint) // nolint
  411. }
  412. return []byte{0xAB, 0xC1, 0x23}, nil
  413. },
  414. PSKIdentityHint: clientIdentity,
  415. CipherSuites: test.CipherSuites,
  416. }
  417. c, err := testClient(ctx, ca, conf, false)
  418. clientRes <- result{c, err}
  419. }()
  420. config := &Config{
  421. PSK: func(hint []byte) ([]byte, error) {
  422. if !bytes.Equal(clientIdentity, hint) {
  423. return nil, fmt.Errorf("%w: expected(% 02x) actual(% 02x)", errTestPSKInvalidIdentity, clientIdentity, hint)
  424. }
  425. return []byte{0xAB, 0xC1, 0x23}, nil
  426. },
  427. PSKIdentityHint: test.ServerIdentity,
  428. CipherSuites: test.CipherSuites,
  429. }
  430. server, err := testServer(ctx, cb, config, false)
  431. if err != nil {
  432. t.Fatalf("TestPSK: Server failed(%v)", err)
  433. }
  434. actualPSKIdentityHint := server.ConnectionState().IdentityHint
  435. if !bytes.Equal(actualPSKIdentityHint, clientIdentity) {
  436. t.Errorf("TestPSK: Server ClientPSKIdentity Mismatch '%s': expected(%v) actual(%v)", test.Name, clientIdentity, actualPSKIdentityHint)
  437. }
  438. defer func() {
  439. _ = server.Close()
  440. }()
  441. res := <-clientRes
  442. if res.err != nil {
  443. t.Fatal(res.err)
  444. }
  445. _ = res.c.Close()
  446. })
  447. }
  448. }
  449. func TestPSKHintFail(t *testing.T) {
  450. // Check for leaking routines
  451. report := test.CheckRoutines(t)
  452. defer report()
  453. serverAlertError := &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InternalError}}
  454. pskRejected := errPSKRejected
  455. // Limit runtime in case of deadlocks
  456. lim := test.TimeOut(time.Second * 20)
  457. defer lim.Stop()
  458. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  459. defer cancel()
  460. clientErr := make(chan error, 1)
  461. ca, cb := dpipe.Pipe()
  462. go func() {
  463. conf := &Config{
  464. PSK: func(hint []byte) ([]byte, error) {
  465. return nil, pskRejected
  466. },
  467. PSKIdentityHint: []byte{},
  468. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  469. }
  470. _, err := testClient(ctx, ca, conf, false)
  471. clientErr <- err
  472. }()
  473. config := &Config{
  474. PSK: func(hint []byte) ([]byte, error) {
  475. return nil, pskRejected
  476. },
  477. PSKIdentityHint: []byte{},
  478. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  479. }
  480. if _, err := testServer(ctx, cb, config, false); !errors.Is(err, serverAlertError) {
  481. t.Fatalf("TestPSK: Server error exp(%v) failed(%v)", serverAlertError, err)
  482. }
  483. if err := <-clientErr; !errors.Is(err, pskRejected) {
  484. t.Fatalf("TestPSK: Client error exp(%v) failed(%v)", pskRejected, err)
  485. }
  486. }
  487. func TestClientTimeout(t *testing.T) {
  488. // Limit runtime in case of deadlocks
  489. lim := test.TimeOut(time.Second * 20)
  490. defer lim.Stop()
  491. // Check for leaking routines
  492. report := test.CheckRoutines(t)
  493. defer report()
  494. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  495. defer cancel()
  496. clientErr := make(chan error, 1)
  497. ca, _ := dpipe.Pipe()
  498. go func() {
  499. conf := &Config{}
  500. c, err := testClient(ctx, ca, conf, true)
  501. if err == nil {
  502. _ = c.Close()
  503. }
  504. clientErr <- err
  505. }()
  506. // no server!
  507. err := <-clientErr
  508. if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {
  509. t.Fatalf("Client error exp(Temporary network error) failed(%v)", err)
  510. }
  511. }
  512. func TestSRTPConfiguration(t *testing.T) {
  513. // Check for leaking routines
  514. report := test.CheckRoutines(t)
  515. defer report()
  516. for _, test := range []struct {
  517. Name string
  518. ClientSRTP []SRTPProtectionProfile
  519. ServerSRTP []SRTPProtectionProfile
  520. ExpectedProfile SRTPProtectionProfile
  521. WantClientError error
  522. WantServerError error
  523. }{
  524. {
  525. Name: "No SRTP in use",
  526. ClientSRTP: nil,
  527. ServerSRTP: nil,
  528. ExpectedProfile: 0,
  529. WantClientError: nil,
  530. WantServerError: nil,
  531. },
  532. {
  533. Name: "SRTP both ends",
  534. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  535. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  536. ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
  537. WantClientError: nil,
  538. WantServerError: nil,
  539. },
  540. {
  541. Name: "SRTP client only",
  542. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  543. ServerSRTP: nil,
  544. ExpectedProfile: 0,
  545. WantClientError: &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  546. WantServerError: errServerNoMatchingSRTPProfile,
  547. },
  548. {
  549. Name: "SRTP server only",
  550. ClientSRTP: nil,
  551. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  552. ExpectedProfile: 0,
  553. WantClientError: nil,
  554. WantServerError: nil,
  555. },
  556. {
  557. Name: "Multiple Suites",
  558. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
  559. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
  560. ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
  561. WantClientError: nil,
  562. WantServerError: nil,
  563. },
  564. {
  565. Name: "Multiple Suites, Client Chooses",
  566. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
  567. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_32, SRTP_AES128_CM_HMAC_SHA1_80},
  568. ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
  569. WantClientError: nil,
  570. WantServerError: nil,
  571. },
  572. } {
  573. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  574. defer cancel()
  575. ca, cb := dpipe.Pipe()
  576. type result struct {
  577. c *Conn
  578. err error
  579. }
  580. c := make(chan result)
  581. go func() {
  582. client, err := testClient(ctx, ca, &Config{SRTPProtectionProfiles: test.ClientSRTP}, true)
  583. c <- result{client, err}
  584. }()
  585. server, err := testServer(ctx, cb, &Config{SRTPProtectionProfiles: test.ServerSRTP}, true)
  586. if !errors.Is(err, test.WantServerError) {
  587. t.Errorf("TestSRTPConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
  588. }
  589. if err == nil {
  590. defer func() {
  591. _ = server.Close()
  592. }()
  593. }
  594. res := <-c
  595. if res.err == nil {
  596. defer func() {
  597. _ = res.c.Close()
  598. }()
  599. }
  600. if !errors.Is(res.err, test.WantClientError) {
  601. t.Fatalf("TestSRTPConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
  602. }
  603. if res.c == nil {
  604. return
  605. }
  606. actualClientSRTP, _ := res.c.SelectedSRTPProtectionProfile()
  607. if actualClientSRTP != test.ExpectedProfile {
  608. t.Errorf("TestSRTPConfiguration: Client SRTPProtectionProfile Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ExpectedProfile, actualClientSRTP)
  609. }
  610. actualServerSRTP, _ := server.SelectedSRTPProtectionProfile()
  611. if actualServerSRTP != test.ExpectedProfile {
  612. t.Errorf("TestSRTPConfiguration: Server SRTPProtectionProfile Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ExpectedProfile, actualServerSRTP)
  613. }
  614. }
  615. }
  616. func TestClientCertificate(t *testing.T) {
  617. // Check for leaking routines
  618. report := test.CheckRoutines(t)
  619. defer report()
  620. srvCert, err := selfsign.GenerateSelfSigned()
  621. if err != nil {
  622. t.Fatal(err)
  623. }
  624. srvCAPool := x509.NewCertPool()
  625. srvCertificate, err := x509.ParseCertificate(srvCert.Certificate[0])
  626. if err != nil {
  627. t.Fatal(err)
  628. }
  629. srvCAPool.AddCert(srvCertificate)
  630. cert, err := selfsign.GenerateSelfSigned()
  631. if err != nil {
  632. t.Fatal(err)
  633. }
  634. certificate, err := x509.ParseCertificate(cert.Certificate[0])
  635. if err != nil {
  636. t.Fatal(err)
  637. }
  638. caPool := x509.NewCertPool()
  639. caPool.AddCert(certificate)
  640. t.Run("parallel", func(t *testing.T) { // sync routines to check routine leak
  641. tests := map[string]struct {
  642. clientCfg *Config
  643. serverCfg *Config
  644. wantErr bool
  645. }{
  646. "NoClientCert": {
  647. clientCfg: &Config{RootCAs: srvCAPool},
  648. serverCfg: &Config{
  649. Certificates: []tls.Certificate{srvCert},
  650. ClientAuth: NoClientCert,
  651. ClientCAs: caPool,
  652. },
  653. },
  654. "NoClientCert_cert": {
  655. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  656. serverCfg: &Config{
  657. Certificates: []tls.Certificate{srvCert},
  658. ClientAuth: RequireAnyClientCert,
  659. },
  660. },
  661. "RequestClientCert_cert": {
  662. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  663. serverCfg: &Config{
  664. Certificates: []tls.Certificate{srvCert},
  665. ClientAuth: RequestClientCert,
  666. },
  667. },
  668. "RequestClientCert_no_cert": {
  669. clientCfg: &Config{RootCAs: srvCAPool},
  670. serverCfg: &Config{
  671. Certificates: []tls.Certificate{srvCert},
  672. ClientAuth: RequestClientCert,
  673. ClientCAs: caPool,
  674. },
  675. },
  676. "RequireAnyClientCert": {
  677. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  678. serverCfg: &Config{
  679. Certificates: []tls.Certificate{srvCert},
  680. ClientAuth: RequireAnyClientCert,
  681. },
  682. },
  683. "RequireAnyClientCert_error": {
  684. clientCfg: &Config{RootCAs: srvCAPool},
  685. serverCfg: &Config{
  686. Certificates: []tls.Certificate{srvCert},
  687. ClientAuth: RequireAnyClientCert,
  688. },
  689. wantErr: true,
  690. },
  691. "VerifyClientCertIfGiven_no_cert": {
  692. clientCfg: &Config{RootCAs: srvCAPool},
  693. serverCfg: &Config{
  694. Certificates: []tls.Certificate{srvCert},
  695. ClientAuth: VerifyClientCertIfGiven,
  696. ClientCAs: caPool,
  697. },
  698. },
  699. "VerifyClientCertIfGiven_cert": {
  700. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  701. serverCfg: &Config{
  702. Certificates: []tls.Certificate{srvCert},
  703. ClientAuth: VerifyClientCertIfGiven,
  704. ClientCAs: caPool,
  705. },
  706. },
  707. "VerifyClientCertIfGiven_error": {
  708. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  709. serverCfg: &Config{
  710. Certificates: []tls.Certificate{srvCert},
  711. ClientAuth: VerifyClientCertIfGiven,
  712. },
  713. wantErr: true,
  714. },
  715. "RequireAndVerifyClientCert": {
  716. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  717. serverCfg: &Config{
  718. Certificates: []tls.Certificate{srvCert},
  719. ClientAuth: RequireAndVerifyClientCert,
  720. ClientCAs: caPool,
  721. },
  722. },
  723. }
  724. for name, tt := range tests {
  725. tt := tt
  726. t.Run(name, func(t *testing.T) {
  727. t.Parallel()
  728. ca, cb := dpipe.Pipe()
  729. type result struct {
  730. c *Conn
  731. err error
  732. }
  733. c := make(chan result)
  734. go func() {
  735. client, err := Client(ca, tt.clientCfg)
  736. c <- result{client, err}
  737. }()
  738. server, err := Server(cb, tt.serverCfg)
  739. res := <-c
  740. defer func() {
  741. if err == nil {
  742. _ = server.Close()
  743. }
  744. if res.err == nil {
  745. _ = res.c.Close()
  746. }
  747. }()
  748. if tt.wantErr {
  749. if err != nil {
  750. // Error expected, test succeeded
  751. return
  752. }
  753. t.Error("Error expected")
  754. }
  755. if err != nil {
  756. t.Errorf("Server failed(%v)", err)
  757. }
  758. if res.err != nil {
  759. t.Errorf("Client failed(%v)", res.err)
  760. }
  761. actualClientCert := server.ConnectionState().PeerCertificates
  762. if tt.serverCfg.ClientAuth == RequireAnyClientCert || tt.serverCfg.ClientAuth == RequireAndVerifyClientCert {
  763. if actualClientCert == nil {
  764. t.Errorf("Client did not provide a certificate")
  765. }
  766. if len(actualClientCert) != len(tt.clientCfg.Certificates[0].Certificate) || !bytes.Equal(tt.clientCfg.Certificates[0].Certificate[0], actualClientCert[0]) {
  767. t.Errorf("Client certificate was not communicated correctly")
  768. }
  769. }
  770. if tt.serverCfg.ClientAuth == NoClientCert {
  771. if actualClientCert != nil {
  772. t.Errorf("Client certificate wasn't expected")
  773. }
  774. }
  775. actualServerCert := res.c.ConnectionState().PeerCertificates
  776. if actualServerCert == nil {
  777. t.Errorf("Server did not provide a certificate")
  778. }
  779. if len(actualServerCert) != len(tt.serverCfg.Certificates[0].Certificate) || !bytes.Equal(tt.serverCfg.Certificates[0].Certificate[0], actualServerCert[0]) {
  780. t.Errorf("Server certificate was not communicated correctly")
  781. }
  782. })
  783. }
  784. })
  785. }
  786. func TestExtendedMasterSecret(t *testing.T) {
  787. // Check for leaking routines
  788. report := test.CheckRoutines(t)
  789. defer report()
  790. tests := map[string]struct {
  791. clientCfg *Config
  792. serverCfg *Config
  793. expectedClientErr error
  794. expectedServerErr error
  795. }{
  796. "Request_Request_ExtendedMasterSecret": {
  797. clientCfg: &Config{
  798. ExtendedMasterSecret: RequestExtendedMasterSecret,
  799. },
  800. serverCfg: &Config{
  801. ExtendedMasterSecret: RequestExtendedMasterSecret,
  802. },
  803. expectedClientErr: nil,
  804. expectedServerErr: nil,
  805. },
  806. "Request_Require_ExtendedMasterSecret": {
  807. clientCfg: &Config{
  808. ExtendedMasterSecret: RequestExtendedMasterSecret,
  809. },
  810. serverCfg: &Config{
  811. ExtendedMasterSecret: RequireExtendedMasterSecret,
  812. },
  813. expectedClientErr: nil,
  814. expectedServerErr: nil,
  815. },
  816. "Request_Disable_ExtendedMasterSecret": {
  817. clientCfg: &Config{
  818. ExtendedMasterSecret: RequestExtendedMasterSecret,
  819. },
  820. serverCfg: &Config{
  821. ExtendedMasterSecret: DisableExtendedMasterSecret,
  822. },
  823. expectedClientErr: nil,
  824. expectedServerErr: nil,
  825. },
  826. "Require_Request_ExtendedMasterSecret": {
  827. clientCfg: &Config{
  828. ExtendedMasterSecret: RequireExtendedMasterSecret,
  829. },
  830. serverCfg: &Config{
  831. ExtendedMasterSecret: RequestExtendedMasterSecret,
  832. },
  833. expectedClientErr: nil,
  834. expectedServerErr: nil,
  835. },
  836. "Require_Require_ExtendedMasterSecret": {
  837. clientCfg: &Config{
  838. ExtendedMasterSecret: RequireExtendedMasterSecret,
  839. },
  840. serverCfg: &Config{
  841. ExtendedMasterSecret: RequireExtendedMasterSecret,
  842. },
  843. expectedClientErr: nil,
  844. expectedServerErr: nil,
  845. },
  846. "Require_Disable_ExtendedMasterSecret": {
  847. clientCfg: &Config{
  848. ExtendedMasterSecret: RequireExtendedMasterSecret,
  849. },
  850. serverCfg: &Config{
  851. ExtendedMasterSecret: DisableExtendedMasterSecret,
  852. },
  853. expectedClientErr: errClientRequiredButNoServerEMS,
  854. expectedServerErr: &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  855. },
  856. "Disable_Request_ExtendedMasterSecret": {
  857. clientCfg: &Config{
  858. ExtendedMasterSecret: DisableExtendedMasterSecret,
  859. },
  860. serverCfg: &Config{
  861. ExtendedMasterSecret: RequestExtendedMasterSecret,
  862. },
  863. expectedClientErr: nil,
  864. expectedServerErr: nil,
  865. },
  866. "Disable_Require_ExtendedMasterSecret": {
  867. clientCfg: &Config{
  868. ExtendedMasterSecret: DisableExtendedMasterSecret,
  869. },
  870. serverCfg: &Config{
  871. ExtendedMasterSecret: RequireExtendedMasterSecret,
  872. },
  873. expectedClientErr: &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  874. expectedServerErr: errServerRequiredButNoClientEMS,
  875. },
  876. "Disable_Disable_ExtendedMasterSecret": {
  877. clientCfg: &Config{
  878. ExtendedMasterSecret: DisableExtendedMasterSecret,
  879. },
  880. serverCfg: &Config{
  881. ExtendedMasterSecret: DisableExtendedMasterSecret,
  882. },
  883. expectedClientErr: nil,
  884. expectedServerErr: nil,
  885. },
  886. }
  887. for name, tt := range tests {
  888. tt := tt
  889. t.Run(name, func(t *testing.T) {
  890. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  891. defer cancel()
  892. ca, cb := dpipe.Pipe()
  893. type result struct {
  894. c *Conn
  895. err error
  896. }
  897. c := make(chan result)
  898. go func() {
  899. client, err := testClient(ctx, ca, tt.clientCfg, true)
  900. c <- result{client, err}
  901. }()
  902. server, err := testServer(ctx, cb, tt.serverCfg, true)
  903. res := <-c
  904. defer func() {
  905. if err == nil {
  906. _ = server.Close()
  907. }
  908. if res.err == nil {
  909. _ = res.c.Close()
  910. }
  911. }()
  912. if !errors.Is(res.err, tt.expectedClientErr) {
  913. t.Errorf("Client error expected: \"%v\" but got \"%v\"", tt.expectedClientErr, res.err)
  914. }
  915. if !errors.Is(err, tt.expectedServerErr) {
  916. t.Errorf("Server error expected: \"%v\" but got \"%v\"", tt.expectedServerErr, err)
  917. }
  918. })
  919. }
  920. }
  921. func TestServerCertificate(t *testing.T) {
  922. // Check for leaking routines
  923. report := test.CheckRoutines(t)
  924. defer report()
  925. cert, err := selfsign.GenerateSelfSigned()
  926. if err != nil {
  927. t.Fatal(err)
  928. }
  929. certificate, err := x509.ParseCertificate(cert.Certificate[0])
  930. if err != nil {
  931. t.Fatal(err)
  932. }
  933. caPool := x509.NewCertPool()
  934. caPool.AddCert(certificate)
  935. t.Run("parallel", func(t *testing.T) { // sync routines to check routine leak
  936. tests := map[string]struct {
  937. clientCfg *Config
  938. serverCfg *Config
  939. wantErr bool
  940. }{
  941. "no_ca": {
  942. clientCfg: &Config{},
  943. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  944. wantErr: true,
  945. },
  946. "good_ca": {
  947. clientCfg: &Config{RootCAs: caPool},
  948. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  949. },
  950. "no_ca_skip_verify": {
  951. clientCfg: &Config{InsecureSkipVerify: true},
  952. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  953. },
  954. "good_ca_skip_verify_custom_verify_peer": {
  955. clientCfg: &Config{RootCAs: caPool, Certificates: []tls.Certificate{cert}},
  956. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: RequireAnyClientCert, VerifyPeerCertificate: func(cert [][]byte, chain [][]*x509.Certificate) error {
  957. if len(chain) != 0 {
  958. return errNotExpectedChain
  959. }
  960. return nil
  961. }},
  962. },
  963. "good_ca_verify_custom_verify_peer": {
  964. clientCfg: &Config{RootCAs: caPool, Certificates: []tls.Certificate{cert}},
  965. serverCfg: &Config{ClientCAs: caPool, Certificates: []tls.Certificate{cert}, ClientAuth: RequireAndVerifyClientCert, VerifyPeerCertificate: func(cert [][]byte, chain [][]*x509.Certificate) error {
  966. if len(chain) == 0 {
  967. return errExpecedChain
  968. }
  969. return nil
  970. }},
  971. },
  972. "good_ca_custom_verify_peer": {
  973. clientCfg: &Config{
  974. RootCAs: caPool,
  975. VerifyPeerCertificate: func([][]byte, [][]*x509.Certificate) error {
  976. return errWrongCert
  977. },
  978. },
  979. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  980. wantErr: true,
  981. },
  982. "server_name": {
  983. clientCfg: &Config{RootCAs: caPool, ServerName: certificate.Subject.CommonName},
  984. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  985. },
  986. "server_name_error": {
  987. clientCfg: &Config{RootCAs: caPool, ServerName: "barfoo"},
  988. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  989. wantErr: true,
  990. },
  991. }
  992. for name, tt := range tests {
  993. tt := tt
  994. t.Run(name, func(t *testing.T) {
  995. t.Parallel()
  996. ca, cb := dpipe.Pipe()
  997. type result struct {
  998. c *Conn
  999. err error
  1000. }
  1001. srvCh := make(chan result)
  1002. go func() {
  1003. s, err := Server(cb, tt.serverCfg)
  1004. srvCh <- result{s, err}
  1005. }()
  1006. cli, err := Client(ca, tt.clientCfg)
  1007. if err == nil {
  1008. _ = cli.Close()
  1009. }
  1010. if !tt.wantErr && err != nil {
  1011. t.Errorf("Client failed(%v)", err)
  1012. }
  1013. if tt.wantErr && err == nil {
  1014. t.Fatal("Error expected")
  1015. }
  1016. srv := <-srvCh
  1017. if srv.err == nil {
  1018. _ = srv.c.Close()
  1019. }
  1020. })
  1021. }
  1022. })
  1023. }
  1024. func TestCipherSuiteConfiguration(t *testing.T) {
  1025. // Check for leaking routines
  1026. report := test.CheckRoutines(t)
  1027. defer report()
  1028. for _, test := range []struct {
  1029. Name string
  1030. ClientCipherSuites []CipherSuiteID
  1031. ServerCipherSuites []CipherSuiteID
  1032. WantClientError error
  1033. WantServerError error
  1034. WantSelectedCipherSuite CipherSuiteID
  1035. }{
  1036. {
  1037. Name: "No CipherSuites specified",
  1038. ClientCipherSuites: nil,
  1039. ServerCipherSuites: nil,
  1040. WantClientError: nil,
  1041. WantServerError: nil,
  1042. },
  1043. {
  1044. Name: "Invalid CipherSuite",
  1045. ClientCipherSuites: []CipherSuiteID{0x00},
  1046. ServerCipherSuites: []CipherSuiteID{0x00},
  1047. WantClientError: &invalidCipherSuite{0x00},
  1048. WantServerError: &invalidCipherSuite{0x00},
  1049. },
  1050. {
  1051. Name: "Valid CipherSuites specified",
  1052. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1053. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1054. WantClientError: nil,
  1055. WantServerError: nil,
  1056. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1057. },
  1058. {
  1059. Name: "CipherSuites mismatch",
  1060. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1061. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  1062. WantClientError: &errAlert{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  1063. WantServerError: errCipherSuiteNoIntersection,
  1064. },
  1065. {
  1066. Name: "Valid CipherSuites CCM specified",
  1067. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM},
  1068. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM},
  1069. WantClientError: nil,
  1070. WantServerError: nil,
  1071. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
  1072. },
  1073. {
  1074. Name: "Valid CipherSuites CCM-8 specified",
  1075. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8},
  1076. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8},
  1077. WantClientError: nil,
  1078. WantServerError: nil,
  1079. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
  1080. },
  1081. {
  1082. Name: "Server supports subset of client suites",
  1083. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  1084. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  1085. WantClientError: nil,
  1086. WantServerError: nil,
  1087. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  1088. },
  1089. } {
  1090. test := test
  1091. t.Run(test.Name, func(t *testing.T) {
  1092. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1093. defer cancel()
  1094. ca, cb := dpipe.Pipe()
  1095. type result struct {
  1096. c *Conn
  1097. err error
  1098. }
  1099. c := make(chan result)
  1100. go func() {
  1101. client, err := testClient(ctx, ca, &Config{CipherSuites: test.ClientCipherSuites}, true)
  1102. c <- result{client, err}
  1103. }()
  1104. server, err := testServer(ctx, cb, &Config{CipherSuites: test.ServerCipherSuites}, true)
  1105. if err == nil {
  1106. defer func() {
  1107. _ = server.Close()
  1108. }()
  1109. }
  1110. if !errors.Is(err, test.WantServerError) {
  1111. t.Errorf("TestCipherSuiteConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
  1112. }
  1113. res := <-c
  1114. if res.err == nil {
  1115. _ = server.Close()
  1116. }
  1117. if !errors.Is(res.err, test.WantClientError) {
  1118. t.Errorf("TestSRTPConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
  1119. }
  1120. if test.WantSelectedCipherSuite != 0x00 && res.c.state.cipherSuite.ID() != test.WantSelectedCipherSuite {
  1121. t.Errorf("TestCipherSuiteConfiguration: Server Selected Bad Cipher Suite '%s': expected(%v) actual(%v)", test.Name, test.WantSelectedCipherSuite, res.c.state.cipherSuite.ID())
  1122. }
  1123. })
  1124. }
  1125. }
  1126. func TestCertificateAndPSKServer(t *testing.T) {
  1127. // Check for leaking routines
  1128. report := test.CheckRoutines(t)
  1129. defer report()
  1130. for _, test := range []struct {
  1131. Name string
  1132. ClientPSK bool
  1133. }{
  1134. {
  1135. Name: "Client uses PKI",
  1136. ClientPSK: false,
  1137. },
  1138. {
  1139. Name: "Client uses PSK",
  1140. ClientPSK: true,
  1141. },
  1142. } {
  1143. test := test
  1144. t.Run(test.Name, func(t *testing.T) {
  1145. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1146. defer cancel()
  1147. ca, cb := dpipe.Pipe()
  1148. type result struct {
  1149. c *Conn
  1150. err error
  1151. }
  1152. c := make(chan result)
  1153. go func() {
  1154. config := &Config{CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}}
  1155. if test.ClientPSK {
  1156. config.PSK = func([]byte) ([]byte, error) {
  1157. return []byte{0x00, 0x01, 0x02}, nil
  1158. }
  1159. config.PSKIdentityHint = []byte{0x00}
  1160. config.CipherSuites = []CipherSuiteID{TLS_PSK_WITH_AES_128_GCM_SHA256}
  1161. }
  1162. client, err := testClient(ctx, ca, config, false)
  1163. c <- result{client, err}
  1164. }()
  1165. config := &Config{
  1166. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_PSK_WITH_AES_128_GCM_SHA256},
  1167. PSK: func([]byte) ([]byte, error) {
  1168. return []byte{0x00, 0x01, 0x02}, nil
  1169. },
  1170. }
  1171. server, err := testServer(ctx, cb, config, true)
  1172. if err == nil {
  1173. defer func() {
  1174. _ = server.Close()
  1175. }()
  1176. } else {
  1177. t.Errorf("TestCertificateAndPSKServer: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, nil, err)
  1178. }
  1179. res := <-c
  1180. if res.err == nil {
  1181. _ = server.Close()
  1182. } else {
  1183. t.Errorf("TestCertificateAndPSKServer: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, nil, res.err)
  1184. }
  1185. })
  1186. }
  1187. }
  1188. func TestPSKConfiguration(t *testing.T) {
  1189. // Check for leaking routines
  1190. report := test.CheckRoutines(t)
  1191. defer report()
  1192. for _, test := range []struct {
  1193. Name string
  1194. ClientHasCertificate bool
  1195. ServerHasCertificate bool
  1196. ClientPSK PSKCallback
  1197. ServerPSK PSKCallback
  1198. ClientPSKIdentity []byte
  1199. ServerPSKIdentity []byte
  1200. WantClientError error
  1201. WantServerError error
  1202. }{
  1203. {
  1204. Name: "PSK and no certificate specified",
  1205. ClientHasCertificate: false,
  1206. ServerHasCertificate: false,
  1207. ClientPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1208. ServerPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1209. ClientPSKIdentity: []byte{0x00},
  1210. ServerPSKIdentity: []byte{0x00},
  1211. WantClientError: errNoAvailablePSKCipherSuite,
  1212. WantServerError: errNoAvailablePSKCipherSuite,
  1213. },
  1214. {
  1215. Name: "PSK and certificate specified",
  1216. ClientHasCertificate: true,
  1217. ServerHasCertificate: true,
  1218. ClientPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1219. ServerPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1220. ClientPSKIdentity: []byte{0x00},
  1221. ServerPSKIdentity: []byte{0x00},
  1222. WantClientError: errNoAvailablePSKCipherSuite,
  1223. WantServerError: errNoAvailablePSKCipherSuite,
  1224. },
  1225. {
  1226. Name: "PSK and no identity specified",
  1227. ClientHasCertificate: false,
  1228. ServerHasCertificate: false,
  1229. ClientPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1230. ServerPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1231. ClientPSKIdentity: nil,
  1232. ServerPSKIdentity: nil,
  1233. WantClientError: errPSKAndIdentityMustBeSetForClient,
  1234. WantServerError: errNoAvailablePSKCipherSuite,
  1235. },
  1236. {
  1237. Name: "No PSK and identity specified",
  1238. ClientHasCertificate: false,
  1239. ServerHasCertificate: false,
  1240. ClientPSK: nil,
  1241. ServerPSK: nil,
  1242. ClientPSKIdentity: []byte{0x00},
  1243. ServerPSKIdentity: []byte{0x00},
  1244. WantClientError: errIdentityNoPSK,
  1245. WantServerError: errIdentityNoPSK,
  1246. },
  1247. } {
  1248. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1249. defer cancel()
  1250. ca, cb := dpipe.Pipe()
  1251. type result struct {
  1252. c *Conn
  1253. err error
  1254. }
  1255. c := make(chan result)
  1256. go func() {
  1257. client, err := testClient(ctx, ca, &Config{PSK: test.ClientPSK, PSKIdentityHint: test.ClientPSKIdentity}, test.ClientHasCertificate)
  1258. c <- result{client, err}
  1259. }()
  1260. _, err := testServer(ctx, cb, &Config{PSK: test.ServerPSK, PSKIdentityHint: test.ServerPSKIdentity}, test.ServerHasCertificate)
  1261. if err != nil || test.WantServerError != nil {
  1262. if !(err != nil && test.WantServerError != nil && err.Error() == test.WantServerError.Error()) {
  1263. t.Fatalf("TestPSKConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
  1264. }
  1265. }
  1266. res := <-c
  1267. if res.err != nil || test.WantClientError != nil {
  1268. if !(res.err != nil && test.WantClientError != nil && res.err.Error() == test.WantClientError.Error()) {
  1269. t.Fatalf("TestPSKConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
  1270. }
  1271. }
  1272. }
  1273. }
  1274. func TestServerTimeout(t *testing.T) {
  1275. // Limit runtime in case of deadlocks
  1276. lim := test.TimeOut(time.Second * 20)
  1277. defer lim.Stop()
  1278. // Check for leaking routines
  1279. report := test.CheckRoutines(t)
  1280. defer report()
  1281. cookie := make([]byte, 20)
  1282. _, err := rand.Read(cookie)
  1283. if err != nil {
  1284. t.Fatal(err)
  1285. }
  1286. var rand [28]byte
  1287. random := handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand}
  1288. cipherSuites := []CipherSuite{
  1289. &ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{},
  1290. &ciphersuite.TLSEcdheRsaWithAes128GcmSha256{},
  1291. }
  1292. extensions := []extension.Extension{
  1293. &extension.SupportedSignatureAlgorithms{
  1294. SignatureHashAlgorithms: []signaturehash.Algorithm{
  1295. {Hash: hash.SHA256, Signature: signature.ECDSA},
  1296. {Hash: hash.SHA384, Signature: signature.ECDSA},
  1297. {Hash: hash.SHA512, Signature: signature.ECDSA},
  1298. {Hash: hash.SHA256, Signature: signature.RSA},
  1299. {Hash: hash.SHA384, Signature: signature.RSA},
  1300. {Hash: hash.SHA512, Signature: signature.RSA},
  1301. },
  1302. },
  1303. &extension.SupportedEllipticCurves{
  1304. EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384},
  1305. },
  1306. &extension.SupportedPointFormats{
  1307. PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
  1308. },
  1309. }
  1310. record := &recordlayer.RecordLayer{
  1311. Header: recordlayer.Header{
  1312. SequenceNumber: 0,
  1313. Version: protocol.Version1_2,
  1314. },
  1315. Content: &handshake.Handshake{
  1316. // sequenceNumber and messageSequence line up, may need to be re-evaluated
  1317. Header: handshake.Header{
  1318. MessageSequence: 0,
  1319. },
  1320. Message: &handshake.MessageClientHello{
  1321. Version: protocol.Version1_2,
  1322. Cookie: cookie,
  1323. Random: random,
  1324. CipherSuiteIDs: cipherSuiteIDs(cipherSuites),
  1325. CompressionMethods: defaultCompressionMethods(),
  1326. Extensions: extensions,
  1327. },
  1328. },
  1329. }
  1330. packet, err := record.Marshal()
  1331. if err != nil {
  1332. t.Fatal(err)
  1333. }
  1334. ca, cb := dpipe.Pipe()
  1335. defer func() {
  1336. err := ca.Close()
  1337. if err != nil {
  1338. t.Fatal(err)
  1339. }
  1340. }()
  1341. // Client reader
  1342. caReadChan := make(chan []byte, 1000)
  1343. go func() {
  1344. for {
  1345. data := make([]byte, 8192)
  1346. n, err := ca.Read(data)
  1347. if err != nil {
  1348. return
  1349. }
  1350. caReadChan <- data[:n]
  1351. }
  1352. }()
  1353. // Start sending ClientHello packets until server responds with first packet
  1354. go func() {
  1355. for {
  1356. select {
  1357. case <-time.After(10 * time.Millisecond):
  1358. _, err := ca.Write(packet)
  1359. if err != nil {
  1360. return
  1361. }
  1362. case <-caReadChan:
  1363. // Once we receive the first reply from the server, stop
  1364. return
  1365. }
  1366. }
  1367. }()
  1368. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  1369. defer cancel()
  1370. config := &Config{
  1371. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1372. FlightInterval: 100 * time.Millisecond,
  1373. }
  1374. _, serverErr := testServer(ctx, cb, config, true)
  1375. if netErr, ok := serverErr.(net.Error); !ok || !netErr.Timeout() {
  1376. t.Fatalf("Client error exp(Temporary network error) failed(%v)", serverErr)
  1377. }
  1378. // Wait a little longer to ensure no additional messages have been sent by the server
  1379. time.Sleep(300 * time.Millisecond)
  1380. select {
  1381. case msg := <-caReadChan:
  1382. t.Fatalf("Expected no additional messages from server, got: %+v", msg)
  1383. default:
  1384. }
  1385. }
  1386. func TestProtocolVersionValidation(t *testing.T) {
  1387. // Limit runtime in case of deadlocks
  1388. lim := test.TimeOut(time.Second * 20)
  1389. defer lim.Stop()
  1390. // Check for leaking routines
  1391. report := test.CheckRoutines(t)
  1392. defer report()
  1393. cookie := make([]byte, 20)
  1394. if _, err := rand.Read(cookie); err != nil {
  1395. t.Fatal(err)
  1396. }
  1397. var rand [28]byte
  1398. random := handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand}
  1399. localKeypair, err := elliptic.GenerateKeypair(elliptic.X25519)
  1400. if err != nil {
  1401. t.Fatal(err)
  1402. }
  1403. config := &Config{
  1404. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1405. FlightInterval: 100 * time.Millisecond,
  1406. }
  1407. t.Run("Server", func(t *testing.T) {
  1408. serverCases := map[string]struct {
  1409. records []*recordlayer.RecordLayer
  1410. }{
  1411. "ClientHelloVersion": {
  1412. records: []*recordlayer.RecordLayer{
  1413. {
  1414. Header: recordlayer.Header{
  1415. Version: protocol.Version1_2,
  1416. },
  1417. Content: &handshake.Handshake{
  1418. Message: &handshake.MessageClientHello{
  1419. Version: protocol.Version{Major: 0xfe, Minor: 0xff}, // try to downgrade
  1420. Cookie: cookie,
  1421. Random: random,
  1422. CipherSuiteIDs: []uint16{uint16((&ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{}).ID())},
  1423. CompressionMethods: defaultCompressionMethods(),
  1424. },
  1425. },
  1426. },
  1427. },
  1428. },
  1429. "SecondsClientHelloVersion": {
  1430. records: []*recordlayer.RecordLayer{
  1431. {
  1432. Header: recordlayer.Header{
  1433. Version: protocol.Version1_2,
  1434. },
  1435. Content: &handshake.Handshake{
  1436. Message: &handshake.MessageClientHello{
  1437. Version: protocol.Version1_2,
  1438. Cookie: cookie,
  1439. Random: random,
  1440. CipherSuiteIDs: []uint16{uint16((&ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{}).ID())},
  1441. CompressionMethods: defaultCompressionMethods(),
  1442. },
  1443. },
  1444. },
  1445. {
  1446. Header: recordlayer.Header{
  1447. Version: protocol.Version1_2,
  1448. SequenceNumber: 1,
  1449. },
  1450. Content: &handshake.Handshake{
  1451. Header: handshake.Header{
  1452. MessageSequence: 1,
  1453. },
  1454. Message: &handshake.MessageClientHello{
  1455. Version: protocol.Version{Major: 0xfe, Minor: 0xff}, // try to downgrade
  1456. Cookie: cookie,
  1457. Random: random,
  1458. CipherSuiteIDs: []uint16{uint16((&ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{}).ID())},
  1459. CompressionMethods: defaultCompressionMethods(),
  1460. },
  1461. },
  1462. },
  1463. },
  1464. },
  1465. }
  1466. for name, c := range serverCases {
  1467. c := c
  1468. t.Run(name, func(t *testing.T) {
  1469. ca, cb := dpipe.Pipe()
  1470. defer func() {
  1471. err := ca.Close()
  1472. if err != nil {
  1473. t.Error(err)
  1474. }
  1475. }()
  1476. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  1477. defer cancel()
  1478. var wg sync.WaitGroup
  1479. wg.Add(1)
  1480. defer wg.Wait()
  1481. go func() {
  1482. defer wg.Done()
  1483. if _, err := testServer(ctx, cb, config, true); !errors.Is(err, errUnsupportedProtocolVersion) {
  1484. t.Errorf("Client error exp(%v) failed(%v)", errUnsupportedProtocolVersion, err)
  1485. }
  1486. }()
  1487. time.Sleep(50 * time.Millisecond)
  1488. resp := make([]byte, 1024)
  1489. for _, record := range c.records {
  1490. packet, err := record.Marshal()
  1491. if err != nil {
  1492. t.Fatal(err)
  1493. }
  1494. if _, werr := ca.Write(packet); werr != nil {
  1495. t.Fatal(werr)
  1496. }
  1497. n, rerr := ca.Read(resp[:cap(resp)])
  1498. if rerr != nil {
  1499. t.Fatal(rerr)
  1500. }
  1501. resp = resp[:n]
  1502. }
  1503. h := &recordlayer.Header{}
  1504. if err := h.Unmarshal(resp); err != nil {
  1505. t.Fatal("Failed to unmarshal response")
  1506. }
  1507. if h.ContentType != protocol.ContentTypeAlert {
  1508. t.Errorf("Peer must return alert to unsupported protocol version")
  1509. }
  1510. })
  1511. }
  1512. })
  1513. t.Run("Client", func(t *testing.T) {
  1514. clientCases := map[string]struct {
  1515. records []*recordlayer.RecordLayer
  1516. }{
  1517. "ServerHelloVersion": {
  1518. records: []*recordlayer.RecordLayer{
  1519. {
  1520. Header: recordlayer.Header{
  1521. Version: protocol.Version1_2,
  1522. },
  1523. Content: &handshake.Handshake{
  1524. Message: &handshake.MessageHelloVerifyRequest{
  1525. Version: protocol.Version1_2,
  1526. Cookie: cookie,
  1527. },
  1528. },
  1529. },
  1530. {
  1531. Header: recordlayer.Header{
  1532. Version: protocol.Version1_2,
  1533. SequenceNumber: 1,
  1534. },
  1535. Content: &handshake.Handshake{
  1536. Header: handshake.Header{
  1537. MessageSequence: 1,
  1538. },
  1539. Message: &handshake.MessageServerHello{
  1540. Version: protocol.Version{Major: 0xfe, Minor: 0xff}, // try to downgrade
  1541. Random: random,
  1542. CipherSuiteID: func() *uint16 { id := uint16(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256); return &id }(),
  1543. CompressionMethod: defaultCompressionMethods()[0],
  1544. },
  1545. },
  1546. },
  1547. {
  1548. Header: recordlayer.Header{
  1549. Version: protocol.Version1_2,
  1550. SequenceNumber: 2,
  1551. },
  1552. Content: &handshake.Handshake{
  1553. Header: handshake.Header{
  1554. MessageSequence: 2,
  1555. },
  1556. Message: &handshake.MessageCertificate{},
  1557. },
  1558. },
  1559. {
  1560. Header: recordlayer.Header{
  1561. Version: protocol.Version1_2,
  1562. SequenceNumber: 3,
  1563. },
  1564. Content: &handshake.Handshake{
  1565. Header: handshake.Header{
  1566. MessageSequence: 3,
  1567. },
  1568. Message: &handshake.MessageServerKeyExchange{
  1569. EllipticCurveType: elliptic.CurveTypeNamedCurve,
  1570. NamedCurve: elliptic.X25519,
  1571. PublicKey: localKeypair.PublicKey,
  1572. HashAlgorithm: hash.SHA256,
  1573. SignatureAlgorithm: signature.ECDSA,
  1574. Signature: make([]byte, 64),
  1575. },
  1576. },
  1577. },
  1578. {
  1579. Header: recordlayer.Header{
  1580. Version: protocol.Version1_2,
  1581. SequenceNumber: 4,
  1582. },
  1583. Content: &handshake.Handshake{
  1584. Header: handshake.Header{
  1585. MessageSequence: 4,
  1586. },
  1587. Message: &handshake.MessageServerHelloDone{},
  1588. },
  1589. },
  1590. },
  1591. },
  1592. }
  1593. for name, c := range clientCases {
  1594. c := c
  1595. t.Run(name, func(t *testing.T) {
  1596. ca, cb := dpipe.Pipe()
  1597. defer func() {
  1598. err := ca.Close()
  1599. if err != nil {
  1600. t.Error(err)
  1601. }
  1602. }()
  1603. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  1604. defer cancel()
  1605. var wg sync.WaitGroup
  1606. wg.Add(1)
  1607. defer wg.Wait()
  1608. go func() {
  1609. defer wg.Done()
  1610. if _, err := testClient(ctx, cb, config, true); !errors.Is(err, errUnsupportedProtocolVersion) {
  1611. t.Errorf("Server error exp(%v) failed(%v)", errUnsupportedProtocolVersion, err)
  1612. }
  1613. }()
  1614. time.Sleep(50 * time.Millisecond)
  1615. for _, record := range c.records {
  1616. if _, err := ca.Read(make([]byte, 1024)); err != nil {
  1617. t.Fatal(err)
  1618. }
  1619. packet, err := record.Marshal()
  1620. if err != nil {
  1621. t.Fatal(err)
  1622. }
  1623. if _, err := ca.Write(packet); err != nil {
  1624. t.Fatal(err)
  1625. }
  1626. }
  1627. resp := make([]byte, 1024)
  1628. n, err := ca.Read(resp)
  1629. if err != nil {
  1630. t.Fatal(err)
  1631. }
  1632. resp = resp[:n]
  1633. h := &recordlayer.Header{}
  1634. if err := h.Unmarshal(resp); err != nil {
  1635. t.Fatal("Failed to unmarshal response")
  1636. }
  1637. if h.ContentType != protocol.ContentTypeAlert {
  1638. t.Errorf("Peer must return alert to unsupported protocol version")
  1639. }
  1640. })
  1641. }
  1642. })
  1643. }
  1644. func TestMultipleHelloVerifyRequest(t *testing.T) {
  1645. // Limit runtime in case of deadlocks
  1646. lim := test.TimeOut(time.Second * 20)
  1647. defer lim.Stop()
  1648. // Check for leaking routines
  1649. report := test.CheckRoutines(t)
  1650. defer report()
  1651. cookies := [][]byte{
  1652. // first clientHello contains an empty cookie
  1653. {},
  1654. }
  1655. var packets [][]byte
  1656. for i := 0; i < 2; i++ {
  1657. cookie := make([]byte, 20)
  1658. if _, err := rand.Read(cookie); err != nil {
  1659. t.Fatal(err)
  1660. }
  1661. cookies = append(cookies, cookie)
  1662. record := &recordlayer.RecordLayer{
  1663. Header: recordlayer.Header{
  1664. SequenceNumber: uint64(i),
  1665. Version: protocol.Version1_2,
  1666. },
  1667. Content: &handshake.Handshake{
  1668. Header: handshake.Header{
  1669. MessageSequence: uint16(i),
  1670. },
  1671. Message: &handshake.MessageHelloVerifyRequest{
  1672. Version: protocol.Version1_2,
  1673. Cookie: cookie,
  1674. },
  1675. },
  1676. }
  1677. packet, err := record.Marshal()
  1678. if err != nil {
  1679. t.Fatal(err)
  1680. }
  1681. packets = append(packets, packet)
  1682. }
  1683. ca, cb := dpipe.Pipe()
  1684. defer func() {
  1685. err := ca.Close()
  1686. if err != nil {
  1687. t.Error(err)
  1688. }
  1689. }()
  1690. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  1691. defer cancel()
  1692. var wg sync.WaitGroup
  1693. wg.Add(1)
  1694. defer wg.Wait()
  1695. go func() {
  1696. defer wg.Done()
  1697. _, _ = testClient(ctx, ca, &Config{}, false)
  1698. }()
  1699. for i, cookie := range cookies {
  1700. // read client hello
  1701. resp := make([]byte, 1024)
  1702. n, err := cb.Read(resp)
  1703. if err != nil {
  1704. t.Fatal(err)
  1705. }
  1706. record := &recordlayer.RecordLayer{}
  1707. if err := record.Unmarshal(resp[:n]); err != nil {
  1708. t.Fatal(err)
  1709. }
  1710. clientHello := record.Content.(*handshake.Handshake).Message.(*handshake.MessageClientHello)
  1711. if !bytes.Equal(clientHello.Cookie, cookie) {
  1712. t.Fatalf("Wrong cookie, expected: %x, got: %x", clientHello.Cookie, cookie)
  1713. }
  1714. if len(packets) <= i {
  1715. break
  1716. }
  1717. // write hello verify request
  1718. if _, err := cb.Write(packets[i]); err != nil {
  1719. t.Fatal(err)
  1720. }
  1721. }
  1722. cancel()
  1723. }
  1724. // Assert that a DTLS Server always responds with RenegotiationInfo if
  1725. // a ClientHello contained that extension or not
  1726. func TestRenegotationInfo(t *testing.T) {
  1727. // Limit runtime in case of deadlocks
  1728. lim := test.TimeOut(10 * time.Second)
  1729. defer lim.Stop()
  1730. // Check for leaking routines
  1731. report := test.CheckRoutines(t)
  1732. defer report()
  1733. resp := make([]byte, 1024)
  1734. for _, testCase := range []struct {
  1735. Name string
  1736. SendRenegotiationInfo bool
  1737. }{
  1738. {
  1739. "Include RenegotiationInfo",
  1740. true,
  1741. },
  1742. {
  1743. "No RenegotiationInfo",
  1744. false,
  1745. },
  1746. } {
  1747. test := testCase
  1748. t.Run(test.Name, func(t *testing.T) {
  1749. sendClientHello := func(cookie []byte, ca net.Conn, sequenceNumber uint64) {
  1750. extensions := []extension.Extension{}
  1751. if test.SendRenegotiationInfo {
  1752. extensions = append(extensions, &extension.RenegotiationInfo{
  1753. RenegotiatedConnection: 0,
  1754. })
  1755. }
  1756. packet, err := (&recordlayer.RecordLayer{
  1757. Header: recordlayer.Header{
  1758. Version: protocol.Version1_2,
  1759. SequenceNumber: sequenceNumber,
  1760. },
  1761. Content: &handshake.Handshake{
  1762. Header: handshake.Header{
  1763. MessageSequence: uint16(sequenceNumber),
  1764. },
  1765. Message: &handshake.MessageClientHello{
  1766. Version: protocol.Version1_2,
  1767. Cookie: cookie,
  1768. CipherSuiteIDs: cipherSuiteIDs(defaultCipherSuites()),
  1769. CompressionMethods: defaultCompressionMethods(),
  1770. Extensions: extensions,
  1771. },
  1772. },
  1773. }).Marshal()
  1774. if err != nil {
  1775. t.Fatal(err)
  1776. }
  1777. if _, err = ca.Write(packet); err != nil {
  1778. t.Fatal(err)
  1779. }
  1780. }
  1781. ca, cb := dpipe.Pipe()
  1782. defer func() {
  1783. if err := ca.Close(); err != nil {
  1784. t.Error(err)
  1785. }
  1786. }()
  1787. ctx, cancel := context.WithCancel(context.Background())
  1788. defer cancel()
  1789. go func() {
  1790. if _, err := testServer(ctx, cb, &Config{}, true); !errors.Is(err, context.Canceled) {
  1791. t.Error(err)
  1792. }
  1793. }()
  1794. time.Sleep(50 * time.Millisecond)
  1795. sendClientHello([]byte{}, ca, 0)
  1796. n, err := ca.Read(resp)
  1797. if err != nil {
  1798. t.Fatal(err)
  1799. }
  1800. r := &recordlayer.RecordLayer{}
  1801. if err = r.Unmarshal(resp[:n]); err != nil {
  1802. t.Fatal(err)
  1803. }
  1804. helloVerifyRequest := r.Content.(*handshake.Handshake).Message.(*handshake.MessageHelloVerifyRequest)
  1805. sendClientHello(helloVerifyRequest.Cookie, ca, 1)
  1806. if n, err = ca.Read(resp); err != nil {
  1807. t.Fatal(err)
  1808. }
  1809. messages, err := recordlayer.UnpackDatagram(resp[:n])
  1810. if err != nil {
  1811. t.Fatal(err)
  1812. }
  1813. if err := r.Unmarshal(messages[0]); err != nil {
  1814. t.Fatal(err)
  1815. }
  1816. serverHello := r.Content.(*handshake.Handshake).Message.(*handshake.MessageServerHello)
  1817. gotNegotationInfo := false
  1818. for _, v := range serverHello.Extensions {
  1819. if _, ok := v.(*extension.RenegotiationInfo); ok {
  1820. gotNegotationInfo = true
  1821. }
  1822. }
  1823. if !gotNegotationInfo {
  1824. t.Fatalf("Received ServerHello without RenegotiationInfo")
  1825. }
  1826. })
  1827. }
  1828. }