conn_test.go 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package dtls
  4. import (
  5. "bytes"
  6. "context"
  7. "crypto"
  8. "crypto/ecdsa"
  9. cryptoElliptic "crypto/elliptic"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/tls"
  13. "crypto/x509"
  14. "encoding/hex"
  15. "errors"
  16. "fmt"
  17. "io"
  18. "net"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. "github.com/pion/dtls/v2/internal/ciphersuite"
  25. "github.com/pion/dtls/v2/pkg/crypto/elliptic"
  26. "github.com/pion/dtls/v2/pkg/crypto/hash"
  27. "github.com/pion/dtls/v2/pkg/crypto/selfsign"
  28. "github.com/pion/dtls/v2/pkg/crypto/signature"
  29. "github.com/pion/dtls/v2/pkg/crypto/signaturehash"
  30. "github.com/pion/dtls/v2/pkg/protocol"
  31. "github.com/pion/dtls/v2/pkg/protocol/alert"
  32. "github.com/pion/dtls/v2/pkg/protocol/extension"
  33. "github.com/pion/dtls/v2/pkg/protocol/handshake"
  34. "github.com/pion/dtls/v2/pkg/protocol/recordlayer"
  35. "github.com/pion/logging"
  36. "github.com/pion/transport/v2/dpipe"
  37. "github.com/pion/transport/v2/test"
  38. )
  39. var (
  40. errTestPSKInvalidIdentity = errors.New("TestPSK: Server got invalid identity")
  41. errPSKRejected = errors.New("PSK Rejected")
  42. errNotExpectedChain = errors.New("not expected chain")
  43. errExpecedChain = errors.New("expected chain")
  44. errWrongCert = errors.New("wrong cert")
  45. )
  46. func TestStressDuplex(t *testing.T) {
  47. // Limit runtime in case of deadlocks
  48. lim := test.TimeOut(time.Second * 20)
  49. defer lim.Stop()
  50. // Check for leaking routines
  51. report := test.CheckRoutines(t)
  52. defer report()
  53. // Run the test
  54. stressDuplex(t)
  55. }
  56. func stressDuplex(t *testing.T) {
  57. ca, cb, err := pipeMemory()
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. defer func() {
  62. err = ca.Close()
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. err = cb.Close()
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. }()
  71. opt := test.Options{
  72. MsgSize: 2048,
  73. MsgCount: 100,
  74. }
  75. err = test.StressDuplex(ca, cb, opt)
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. }
  80. func TestRoutineLeakOnClose(t *testing.T) {
  81. // Limit runtime in case of deadlocks
  82. lim := test.TimeOut(5 * time.Second)
  83. defer lim.Stop()
  84. // Check for leaking routines
  85. report := test.CheckRoutines(t)
  86. defer report()
  87. ca, cb, err := pipeMemory()
  88. if err != nil {
  89. t.Fatal(err)
  90. }
  91. if _, err := ca.Write(make([]byte, 100)); err != nil {
  92. t.Fatal(err)
  93. }
  94. if err := cb.Close(); err != nil {
  95. t.Fatal(err)
  96. }
  97. if err := ca.Close(); err != nil {
  98. t.Fatal(err)
  99. }
  100. // Packet is sent, but not read.
  101. // inboundLoop routine should not be leaked.
  102. }
  103. func TestReadWriteDeadline(t *testing.T) {
  104. // Limit runtime in case of deadlocks
  105. lim := test.TimeOut(5 * time.Second)
  106. defer lim.Stop()
  107. // Check for leaking routines
  108. report := test.CheckRoutines(t)
  109. defer report()
  110. var e net.Error
  111. ca, cb, err := pipeMemory()
  112. if err != nil {
  113. t.Fatal(err)
  114. }
  115. if err := ca.SetDeadline(time.Unix(0, 1)); err != nil {
  116. t.Fatal(err)
  117. }
  118. _, werr := ca.Write(make([]byte, 100))
  119. if errors.As(werr, &e) {
  120. if !e.Timeout() {
  121. t.Error("Deadline exceeded Write must return Timeout error")
  122. }
  123. if !e.Temporary() { //nolint:staticcheck
  124. t.Error("Deadline exceeded Write must return Temporary error")
  125. }
  126. } else {
  127. t.Error("Write must return net.Error error")
  128. }
  129. _, rerr := ca.Read(make([]byte, 100))
  130. if errors.As(rerr, &e) {
  131. if !e.Timeout() {
  132. t.Error("Deadline exceeded Read must return Timeout error")
  133. }
  134. if !e.Temporary() { //nolint:staticcheck
  135. t.Error("Deadline exceeded Read must return Temporary error")
  136. }
  137. } else {
  138. t.Error("Read must return net.Error error")
  139. }
  140. if err := ca.SetDeadline(time.Time{}); err != nil {
  141. t.Error(err)
  142. }
  143. if err := ca.Close(); err != nil {
  144. t.Error(err)
  145. }
  146. if err := cb.Close(); err != nil {
  147. t.Error(err)
  148. }
  149. if _, err := ca.Write(make([]byte, 100)); !errors.Is(err, ErrConnClosed) {
  150. t.Errorf("Write must return %v after close, got %v", ErrConnClosed, err)
  151. }
  152. if _, err := ca.Read(make([]byte, 100)); !errors.Is(err, io.EOF) {
  153. t.Errorf("Read must return %v after close, got %v", io.EOF, err)
  154. }
  155. }
  156. func TestSequenceNumberOverflow(t *testing.T) {
  157. // Limit runtime in case of deadlocks
  158. lim := test.TimeOut(5 * time.Second)
  159. defer lim.Stop()
  160. // Check for leaking routines
  161. report := test.CheckRoutines(t)
  162. defer report()
  163. t.Run("ApplicationData", func(t *testing.T) {
  164. ca, cb, err := pipeMemory()
  165. if err != nil {
  166. t.Fatal(err)
  167. }
  168. atomic.StoreUint64(&ca.state.localSequenceNumber[1], recordlayer.MaxSequenceNumber)
  169. if _, werr := ca.Write(make([]byte, 100)); werr != nil {
  170. t.Errorf("Write must send message with maximum sequence number, but errord: %v", werr)
  171. }
  172. if _, werr := ca.Write(make([]byte, 100)); !errors.Is(werr, errSequenceNumberOverflow) {
  173. t.Errorf("Write must abandonsend message with maximum sequence number, but errord: %v", werr)
  174. }
  175. if err := ca.Close(); err != nil {
  176. t.Error(err)
  177. }
  178. if err := cb.Close(); err != nil {
  179. t.Error(err)
  180. }
  181. })
  182. t.Run("Handshake", func(t *testing.T) {
  183. ca, cb, err := pipeMemory()
  184. if err != nil {
  185. t.Fatal(err)
  186. }
  187. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  188. defer cancel()
  189. atomic.StoreUint64(&ca.state.localSequenceNumber[0], recordlayer.MaxSequenceNumber+1)
  190. // Try to send handshake packet.
  191. if werr := ca.writePackets(ctx, []*packet{
  192. {
  193. record: &recordlayer.RecordLayer{
  194. Header: recordlayer.Header{
  195. Version: protocol.Version1_2,
  196. },
  197. Content: &handshake.Handshake{
  198. Message: &handshake.MessageClientHello{
  199. Version: protocol.Version1_2,
  200. Cookie: make([]byte, 64),
  201. CipherSuiteIDs: cipherSuiteIDs(defaultCipherSuites()),
  202. CompressionMethods: defaultCompressionMethods(),
  203. },
  204. },
  205. },
  206. },
  207. }); !errors.Is(werr, errSequenceNumberOverflow) {
  208. t.Errorf("Connection must fail on handshake packet reaches maximum sequence number")
  209. }
  210. if err := ca.Close(); err != nil {
  211. t.Error(err)
  212. }
  213. if err := cb.Close(); err != nil {
  214. t.Error(err)
  215. }
  216. })
  217. }
  218. func pipeMemory() (*Conn, *Conn, error) {
  219. // In memory pipe
  220. ca, cb := dpipe.Pipe()
  221. return pipeConn(ca, cb)
  222. }
  223. func pipeConn(ca, cb net.Conn) (*Conn, *Conn, error) {
  224. type result struct {
  225. c *Conn
  226. err error
  227. }
  228. c := make(chan result)
  229. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  230. defer cancel()
  231. // Setup client
  232. go func() {
  233. client, err := testClient(ctx, ca, &Config{SRTPProtectionProfiles: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80}}, true)
  234. c <- result{client, err}
  235. }()
  236. // Setup server
  237. server, err := testServer(ctx, cb, &Config{SRTPProtectionProfiles: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80}}, true)
  238. if err != nil {
  239. return nil, nil, err
  240. }
  241. // Receive client
  242. res := <-c
  243. if res.err != nil {
  244. _ = server.Close()
  245. return nil, nil, res.err
  246. }
  247. return res.c, server, nil
  248. }
  249. func testClient(ctx context.Context, c net.Conn, cfg *Config, generateCertificate bool) (*Conn, error) {
  250. if generateCertificate {
  251. clientCert, err := selfsign.GenerateSelfSigned()
  252. if err != nil {
  253. return nil, err
  254. }
  255. cfg.Certificates = []tls.Certificate{clientCert}
  256. }
  257. cfg.InsecureSkipVerify = true
  258. return ClientWithContext(ctx, c, cfg)
  259. }
  260. func testServer(ctx context.Context, c net.Conn, cfg *Config, generateCertificate bool) (*Conn, error) {
  261. if generateCertificate {
  262. serverCert, err := selfsign.GenerateSelfSigned()
  263. if err != nil {
  264. return nil, err
  265. }
  266. cfg.Certificates = []tls.Certificate{serverCert}
  267. }
  268. return ServerWithContext(ctx, c, cfg)
  269. }
  270. func sendClientHello(cookie []byte, ca net.Conn, sequenceNumber uint64, extensions []extension.Extension) error {
  271. packet, err := (&recordlayer.RecordLayer{
  272. Header: recordlayer.Header{
  273. Version: protocol.Version1_2,
  274. SequenceNumber: sequenceNumber,
  275. },
  276. Content: &handshake.Handshake{
  277. Header: handshake.Header{
  278. MessageSequence: uint16(sequenceNumber),
  279. },
  280. Message: &handshake.MessageClientHello{
  281. Version: protocol.Version1_2,
  282. Cookie: cookie,
  283. CipherSuiteIDs: cipherSuiteIDs(defaultCipherSuites()),
  284. CompressionMethods: defaultCompressionMethods(),
  285. Extensions: extensions,
  286. },
  287. },
  288. }).Marshal()
  289. if err != nil {
  290. return err
  291. }
  292. if _, err = ca.Write(packet); err != nil {
  293. return err
  294. }
  295. return nil
  296. }
  297. func TestHandshakeWithAlert(t *testing.T) {
  298. // Limit runtime in case of deadlocks
  299. lim := test.TimeOut(time.Second * 20)
  300. defer lim.Stop()
  301. // Check for leaking routines
  302. report := test.CheckRoutines(t)
  303. defer report()
  304. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  305. defer cancel()
  306. cases := map[string]struct {
  307. configServer, configClient *Config
  308. errServer, errClient error
  309. }{
  310. "CipherSuiteNoIntersection": {
  311. configServer: &Config{
  312. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  313. },
  314. configClient: &Config{
  315. CipherSuites: []CipherSuiteID{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  316. },
  317. errServer: errCipherSuiteNoIntersection,
  318. errClient: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  319. },
  320. "SignatureSchemesNoIntersection": {
  321. configServer: &Config{
  322. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  323. SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP256AndSHA256},
  324. },
  325. configClient: &Config{
  326. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  327. SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP521AndSHA512},
  328. },
  329. errServer: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  330. errClient: errNoAvailableSignatureSchemes,
  331. },
  332. }
  333. for name, testCase := range cases {
  334. testCase := testCase
  335. t.Run(name, func(t *testing.T) {
  336. clientErr := make(chan error, 1)
  337. ca, cb := dpipe.Pipe()
  338. go func() {
  339. _, err := testClient(ctx, ca, testCase.configClient, true)
  340. clientErr <- err
  341. }()
  342. _, errServer := testServer(ctx, cb, testCase.configServer, true)
  343. if !errors.Is(errServer, testCase.errServer) {
  344. t.Fatalf("Server error exp(%v) failed(%v)", testCase.errServer, errServer)
  345. }
  346. errClient := <-clientErr
  347. if !errors.Is(errClient, testCase.errClient) {
  348. t.Fatalf("Client error exp(%v) failed(%v)", testCase.errClient, errClient)
  349. }
  350. })
  351. }
  352. }
  353. func TestHandshakeWithInvalidRecord(t *testing.T) {
  354. // Limit runtime in case of deadlocks
  355. lim := test.TimeOut(time.Second * 20)
  356. defer lim.Stop()
  357. // Check for leaking routines
  358. report := test.CheckRoutines(t)
  359. defer report()
  360. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  361. defer cancel()
  362. type result struct {
  363. c *Conn
  364. err error
  365. }
  366. clientErr := make(chan result, 1)
  367. ca, cb := dpipe.Pipe()
  368. caWithInvalidRecord := &connWithCallback{Conn: ca}
  369. var msgSeq atomic.Int32
  370. // Send invalid record after first message
  371. caWithInvalidRecord.onWrite = func(b []byte) {
  372. if msgSeq.Add(1) == 2 {
  373. if _, err := ca.Write([]byte{0x01, 0x02}); err != nil {
  374. t.Fatal(err)
  375. }
  376. }
  377. }
  378. go func() {
  379. client, err := testClient(ctx, caWithInvalidRecord, &Config{
  380. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  381. }, true)
  382. clientErr <- result{client, err}
  383. }()
  384. server, errServer := testServer(ctx, cb, &Config{
  385. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  386. }, true)
  387. errClient := <-clientErr
  388. defer func() {
  389. if server != nil {
  390. if err := server.Close(); err != nil {
  391. t.Fatal(err)
  392. }
  393. }
  394. if errClient.c != nil {
  395. if err := errClient.c.Close(); err != nil {
  396. t.Fatal(err)
  397. }
  398. }
  399. }()
  400. if errServer != nil {
  401. t.Fatalf("Server failed(%v)", errServer)
  402. }
  403. if errClient.err != nil {
  404. t.Fatalf("Client failed(%v)", errClient.err)
  405. }
  406. }
  407. func TestExportKeyingMaterial(t *testing.T) {
  408. // Check for leaking routines
  409. report := test.CheckRoutines(t)
  410. defer report()
  411. var rand [28]byte
  412. exportLabel := "EXTRACTOR-dtls_srtp"
  413. expectedServerKey := []byte{0x61, 0x09, 0x9d, 0x7d, 0xcb, 0x08, 0x52, 0x2c, 0xe7, 0x7b}
  414. expectedClientKey := []byte{0x87, 0xf0, 0x40, 0x02, 0xf6, 0x1c, 0xf1, 0xfe, 0x8c, 0x77}
  415. c := &Conn{
  416. state: State{
  417. localRandom: handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand},
  418. remoteRandom: handshake.Random{GMTUnixTime: time.Unix(1000, 0), RandomBytes: rand},
  419. localSequenceNumber: []uint64{0, 0},
  420. cipherSuite: &ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{},
  421. },
  422. }
  423. c.setLocalEpoch(0)
  424. c.setRemoteEpoch(0)
  425. state := c.ConnectionState()
  426. _, err := state.ExportKeyingMaterial(exportLabel, nil, 0)
  427. if !errors.Is(err, errHandshakeInProgress) {
  428. t.Errorf("ExportKeyingMaterial when epoch == 0: expected '%s' actual '%s'", errHandshakeInProgress, err)
  429. }
  430. c.setLocalEpoch(1)
  431. state = c.ConnectionState()
  432. _, err = state.ExportKeyingMaterial(exportLabel, []byte{0x00}, 0)
  433. if !errors.Is(err, errContextUnsupported) {
  434. t.Errorf("ExportKeyingMaterial with context: expected '%s' actual '%s'", errContextUnsupported, err)
  435. }
  436. for k := range invalidKeyingLabels() {
  437. state = c.ConnectionState()
  438. _, err = state.ExportKeyingMaterial(k, nil, 0)
  439. if !errors.Is(err, errReservedExportKeyingMaterial) {
  440. t.Errorf("ExportKeyingMaterial reserved label: expected '%s' actual '%s'", errReservedExportKeyingMaterial, err)
  441. }
  442. }
  443. state = c.ConnectionState()
  444. keyingMaterial, err := state.ExportKeyingMaterial(exportLabel, nil, 10)
  445. if err != nil {
  446. t.Errorf("ExportKeyingMaterial as server: unexpected error '%s'", err)
  447. } else if !bytes.Equal(keyingMaterial, expectedServerKey) {
  448. t.Errorf("ExportKeyingMaterial client export: expected (% 02x) actual (% 02x)", expectedServerKey, keyingMaterial)
  449. }
  450. c.state.isClient = true
  451. state = c.ConnectionState()
  452. keyingMaterial, err = state.ExportKeyingMaterial(exportLabel, nil, 10)
  453. if err != nil {
  454. t.Errorf("ExportKeyingMaterial as server: unexpected error '%s'", err)
  455. } else if !bytes.Equal(keyingMaterial, expectedClientKey) {
  456. t.Errorf("ExportKeyingMaterial client export: expected (% 02x) actual (% 02x)", expectedClientKey, keyingMaterial)
  457. }
  458. }
  459. func TestPSK(t *testing.T) {
  460. // Limit runtime in case of deadlocks
  461. lim := test.TimeOut(time.Second * 20)
  462. defer lim.Stop()
  463. // Check for leaking routines
  464. report := test.CheckRoutines(t)
  465. defer report()
  466. for _, test := range []struct {
  467. Name string
  468. ServerIdentity []byte
  469. CipherSuites []CipherSuiteID
  470. ClientVerifyConnection func(*State) error
  471. ServerVerifyConnection func(*State) error
  472. WantFail bool
  473. ExpectedServerErr string
  474. ExpectedClientErr string
  475. }{
  476. {
  477. Name: "Server identity specified",
  478. ServerIdentity: []byte("Test Identity"),
  479. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  480. },
  481. {
  482. Name: "Server identity specified - Server verify connection fails",
  483. ServerIdentity: []byte("Test Identity"),
  484. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  485. ServerVerifyConnection: func(s *State) error {
  486. return errExample
  487. },
  488. WantFail: true,
  489. ExpectedServerErr: errExample.Error(),
  490. ExpectedClientErr: alert.BadCertificate.String(),
  491. },
  492. {
  493. Name: "Server identity specified - Client verify connection fails",
  494. ServerIdentity: []byte("Test Identity"),
  495. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  496. ClientVerifyConnection: func(s *State) error {
  497. return errExample
  498. },
  499. WantFail: true,
  500. ExpectedServerErr: alert.BadCertificate.String(),
  501. ExpectedClientErr: errExample.Error(),
  502. },
  503. {
  504. Name: "Server identity nil",
  505. ServerIdentity: nil,
  506. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  507. },
  508. {
  509. Name: "TLS_PSK_WITH_AES_128_CBC_SHA256",
  510. ServerIdentity: nil,
  511. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CBC_SHA256},
  512. },
  513. {
  514. Name: "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256",
  515. ServerIdentity: nil,
  516. CipherSuites: []CipherSuiteID{TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256},
  517. },
  518. } {
  519. test := test
  520. t.Run(test.Name, func(t *testing.T) {
  521. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  522. defer cancel()
  523. clientIdentity := []byte("Client Identity")
  524. type result struct {
  525. c *Conn
  526. err error
  527. }
  528. clientRes := make(chan result, 1)
  529. ca, cb := dpipe.Pipe()
  530. go func() {
  531. conf := &Config{
  532. PSK: func(hint []byte) ([]byte, error) {
  533. if !bytes.Equal(test.ServerIdentity, hint) {
  534. return nil, fmt.Errorf("TestPSK: Client got invalid identity expected(% 02x) actual(% 02x)", test.ServerIdentity, hint) //nolint:goerr113
  535. }
  536. return []byte{0xAB, 0xC1, 0x23}, nil
  537. },
  538. PSKIdentityHint: clientIdentity,
  539. CipherSuites: test.CipherSuites,
  540. VerifyConnection: test.ClientVerifyConnection,
  541. }
  542. c, err := testClient(ctx, ca, conf, false)
  543. clientRes <- result{c, err}
  544. }()
  545. config := &Config{
  546. PSK: func(hint []byte) ([]byte, error) {
  547. if !bytes.Equal(clientIdentity, hint) {
  548. return nil, fmt.Errorf("%w: expected(% 02x) actual(% 02x)", errTestPSKInvalidIdentity, clientIdentity, hint)
  549. }
  550. return []byte{0xAB, 0xC1, 0x23}, nil
  551. },
  552. PSKIdentityHint: test.ServerIdentity,
  553. CipherSuites: test.CipherSuites,
  554. VerifyConnection: test.ServerVerifyConnection,
  555. }
  556. server, err := testServer(ctx, cb, config, false)
  557. if test.WantFail {
  558. res := <-clientRes
  559. if err == nil || !strings.Contains(err.Error(), test.ExpectedServerErr) {
  560. t.Fatalf("TestPSK: Server expected(%v) actual(%v)", test.ExpectedServerErr, err)
  561. }
  562. if res.err == nil || !strings.Contains(res.err.Error(), test.ExpectedClientErr) {
  563. t.Fatalf("TestPSK: Client expected(%v) actual(%v)", test.ExpectedClientErr, res.err)
  564. }
  565. return
  566. }
  567. if err != nil {
  568. t.Fatalf("TestPSK: Server failed(%v)", err)
  569. }
  570. actualPSKIdentityHint := server.ConnectionState().IdentityHint
  571. if !bytes.Equal(actualPSKIdentityHint, clientIdentity) {
  572. t.Errorf("TestPSK: Server ClientPSKIdentity Mismatch '%s': expected(%v) actual(%v)", test.Name, clientIdentity, actualPSKIdentityHint)
  573. }
  574. defer func() {
  575. _ = server.Close()
  576. }()
  577. res := <-clientRes
  578. if res.err != nil {
  579. t.Fatal(res.err)
  580. }
  581. _ = res.c.Close()
  582. })
  583. }
  584. }
  585. func TestPSKHintFail(t *testing.T) {
  586. // Check for leaking routines
  587. report := test.CheckRoutines(t)
  588. defer report()
  589. serverAlertError := &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InternalError}}
  590. pskRejected := errPSKRejected
  591. // Limit runtime in case of deadlocks
  592. lim := test.TimeOut(time.Second * 20)
  593. defer lim.Stop()
  594. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  595. defer cancel()
  596. clientErr := make(chan error, 1)
  597. ca, cb := dpipe.Pipe()
  598. go func() {
  599. conf := &Config{
  600. PSK: func(hint []byte) ([]byte, error) {
  601. return nil, pskRejected
  602. },
  603. PSKIdentityHint: []byte{},
  604. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  605. }
  606. _, err := testClient(ctx, ca, conf, false)
  607. clientErr <- err
  608. }()
  609. config := &Config{
  610. PSK: func(hint []byte) ([]byte, error) {
  611. return nil, pskRejected
  612. },
  613. PSKIdentityHint: []byte{},
  614. CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
  615. }
  616. if _, err := testServer(ctx, cb, config, false); !errors.Is(err, serverAlertError) {
  617. t.Fatalf("TestPSK: Server error exp(%v) failed(%v)", serverAlertError, err)
  618. }
  619. if err := <-clientErr; !errors.Is(err, pskRejected) {
  620. t.Fatalf("TestPSK: Client error exp(%v) failed(%v)", pskRejected, err)
  621. }
  622. }
  623. func TestClientTimeout(t *testing.T) {
  624. // Limit runtime in case of deadlocks
  625. lim := test.TimeOut(time.Second * 20)
  626. defer lim.Stop()
  627. // Check for leaking routines
  628. report := test.CheckRoutines(t)
  629. defer report()
  630. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  631. defer cancel()
  632. clientErr := make(chan error, 1)
  633. ca, _ := dpipe.Pipe()
  634. go func() {
  635. conf := &Config{}
  636. c, err := testClient(ctx, ca, conf, true)
  637. if err == nil {
  638. _ = c.Close() //nolint:contextcheck
  639. }
  640. clientErr <- err
  641. }()
  642. // no server!
  643. err := <-clientErr
  644. var netErr net.Error
  645. if !errors.As(err, &netErr) || !netErr.Timeout() {
  646. t.Fatalf("Client error exp(Temporary network error) failed(%v)", err)
  647. }
  648. }
  649. func TestSRTPConfiguration(t *testing.T) {
  650. // Check for leaking routines
  651. report := test.CheckRoutines(t)
  652. defer report()
  653. for _, test := range []struct {
  654. Name string
  655. ClientSRTP []SRTPProtectionProfile
  656. ServerSRTP []SRTPProtectionProfile
  657. ExpectedProfile SRTPProtectionProfile
  658. WantClientError error
  659. WantServerError error
  660. }{
  661. {
  662. Name: "No SRTP in use",
  663. ClientSRTP: nil,
  664. ServerSRTP: nil,
  665. ExpectedProfile: 0,
  666. WantClientError: nil,
  667. WantServerError: nil,
  668. },
  669. {
  670. Name: "SRTP both ends",
  671. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  672. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  673. ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
  674. WantClientError: nil,
  675. WantServerError: nil,
  676. },
  677. {
  678. Name: "SRTP client only",
  679. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  680. ServerSRTP: nil,
  681. ExpectedProfile: 0,
  682. WantClientError: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  683. WantServerError: errServerNoMatchingSRTPProfile,
  684. },
  685. {
  686. Name: "SRTP server only",
  687. ClientSRTP: nil,
  688. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
  689. ExpectedProfile: 0,
  690. WantClientError: nil,
  691. WantServerError: nil,
  692. },
  693. {
  694. Name: "Multiple Suites",
  695. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
  696. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
  697. ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
  698. WantClientError: nil,
  699. WantServerError: nil,
  700. },
  701. {
  702. Name: "Multiple Suites, Client Chooses",
  703. ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
  704. ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_32, SRTP_AES128_CM_HMAC_SHA1_80},
  705. ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
  706. WantClientError: nil,
  707. WantServerError: nil,
  708. },
  709. } {
  710. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  711. defer cancel()
  712. ca, cb := dpipe.Pipe()
  713. type result struct {
  714. c *Conn
  715. err error
  716. }
  717. c := make(chan result)
  718. go func() {
  719. client, err := testClient(ctx, ca, &Config{SRTPProtectionProfiles: test.ClientSRTP}, true)
  720. c <- result{client, err}
  721. }()
  722. server, err := testServer(ctx, cb, &Config{SRTPProtectionProfiles: test.ServerSRTP}, true)
  723. if !errors.Is(err, test.WantServerError) {
  724. t.Errorf("TestSRTPConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
  725. }
  726. if err == nil {
  727. defer func() {
  728. _ = server.Close()
  729. }()
  730. }
  731. res := <-c
  732. if res.err == nil {
  733. defer func() {
  734. _ = res.c.Close()
  735. }()
  736. }
  737. if !errors.Is(res.err, test.WantClientError) {
  738. t.Fatalf("TestSRTPConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
  739. }
  740. if res.c == nil {
  741. return
  742. }
  743. actualClientSRTP, _ := res.c.SelectedSRTPProtectionProfile()
  744. if actualClientSRTP != test.ExpectedProfile {
  745. t.Errorf("TestSRTPConfiguration: Client SRTPProtectionProfile Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ExpectedProfile, actualClientSRTP)
  746. }
  747. actualServerSRTP, _ := server.SelectedSRTPProtectionProfile()
  748. if actualServerSRTP != test.ExpectedProfile {
  749. t.Errorf("TestSRTPConfiguration: Server SRTPProtectionProfile Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ExpectedProfile, actualServerSRTP)
  750. }
  751. }
  752. }
  753. func TestClientCertificate(t *testing.T) {
  754. // Check for leaking routines
  755. report := test.CheckRoutines(t)
  756. defer report()
  757. srvCert, err := selfsign.GenerateSelfSigned()
  758. if err != nil {
  759. t.Fatal(err)
  760. }
  761. srvCAPool := x509.NewCertPool()
  762. srvCertificate, err := x509.ParseCertificate(srvCert.Certificate[0])
  763. if err != nil {
  764. t.Fatal(err)
  765. }
  766. srvCAPool.AddCert(srvCertificate)
  767. cert, err := selfsign.GenerateSelfSigned()
  768. if err != nil {
  769. t.Fatal(err)
  770. }
  771. certificate, err := x509.ParseCertificate(cert.Certificate[0])
  772. if err != nil {
  773. t.Fatal(err)
  774. }
  775. caPool := x509.NewCertPool()
  776. caPool.AddCert(certificate)
  777. t.Run("parallel", func(t *testing.T) { // sync routines to check routine leak
  778. tests := map[string]struct {
  779. clientCfg *Config
  780. serverCfg *Config
  781. wantErr bool
  782. }{
  783. "NoClientCert": {
  784. clientCfg: &Config{RootCAs: srvCAPool},
  785. serverCfg: &Config{
  786. Certificates: []tls.Certificate{srvCert},
  787. ClientAuth: NoClientCert,
  788. ClientCAs: caPool,
  789. },
  790. },
  791. "NoClientCert_ServerVerifyConnectionFails": {
  792. clientCfg: &Config{RootCAs: srvCAPool},
  793. serverCfg: &Config{
  794. Certificates: []tls.Certificate{srvCert},
  795. ClientAuth: NoClientCert,
  796. ClientCAs: caPool,
  797. VerifyConnection: func(s *State) error {
  798. return errExample
  799. },
  800. },
  801. wantErr: true,
  802. },
  803. "NoClientCert_ClientVerifyConnectionFails": {
  804. clientCfg: &Config{RootCAs: srvCAPool, VerifyConnection: func(s *State) error {
  805. return errExample
  806. }},
  807. serverCfg: &Config{
  808. Certificates: []tls.Certificate{srvCert},
  809. ClientAuth: NoClientCert,
  810. ClientCAs: caPool,
  811. },
  812. wantErr: true,
  813. },
  814. "NoClientCert_cert": {
  815. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  816. serverCfg: &Config{
  817. Certificates: []tls.Certificate{srvCert},
  818. ClientAuth: RequireAnyClientCert,
  819. },
  820. },
  821. "RequestClientCert_cert": {
  822. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  823. serverCfg: &Config{
  824. Certificates: []tls.Certificate{srvCert},
  825. ClientAuth: RequestClientCert,
  826. },
  827. },
  828. "RequestClientCert_no_cert": {
  829. clientCfg: &Config{RootCAs: srvCAPool},
  830. serverCfg: &Config{
  831. Certificates: []tls.Certificate{srvCert},
  832. ClientAuth: RequestClientCert,
  833. ClientCAs: caPool,
  834. },
  835. },
  836. "RequireAnyClientCert": {
  837. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  838. serverCfg: &Config{
  839. Certificates: []tls.Certificate{srvCert},
  840. ClientAuth: RequireAnyClientCert,
  841. },
  842. },
  843. "RequireAnyClientCert_error": {
  844. clientCfg: &Config{RootCAs: srvCAPool},
  845. serverCfg: &Config{
  846. Certificates: []tls.Certificate{srvCert},
  847. ClientAuth: RequireAnyClientCert,
  848. },
  849. wantErr: true,
  850. },
  851. "VerifyClientCertIfGiven_no_cert": {
  852. clientCfg: &Config{RootCAs: srvCAPool},
  853. serverCfg: &Config{
  854. Certificates: []tls.Certificate{srvCert},
  855. ClientAuth: VerifyClientCertIfGiven,
  856. ClientCAs: caPool,
  857. },
  858. },
  859. "VerifyClientCertIfGiven_cert": {
  860. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  861. serverCfg: &Config{
  862. Certificates: []tls.Certificate{srvCert},
  863. ClientAuth: VerifyClientCertIfGiven,
  864. ClientCAs: caPool,
  865. },
  866. },
  867. "VerifyClientCertIfGiven_error": {
  868. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}},
  869. serverCfg: &Config{
  870. Certificates: []tls.Certificate{srvCert},
  871. ClientAuth: VerifyClientCertIfGiven,
  872. },
  873. wantErr: true,
  874. },
  875. "RequireAndVerifyClientCert": {
  876. clientCfg: &Config{RootCAs: srvCAPool, Certificates: []tls.Certificate{cert}, VerifyConnection: func(s *State) error {
  877. if ok := bytes.Equal(s.PeerCertificates[0], srvCertificate.Raw); !ok {
  878. return errExample
  879. }
  880. return nil
  881. }},
  882. serverCfg: &Config{
  883. Certificates: []tls.Certificate{srvCert},
  884. ClientAuth: RequireAndVerifyClientCert,
  885. ClientCAs: caPool,
  886. VerifyConnection: func(s *State) error {
  887. if ok := bytes.Equal(s.PeerCertificates[0], certificate.Raw); !ok {
  888. return errExample
  889. }
  890. return nil
  891. },
  892. },
  893. },
  894. "RequireAndVerifyClientCert_callbacks": {
  895. clientCfg: &Config{
  896. RootCAs: srvCAPool,
  897. // Certificates: []tls.Certificate{cert},
  898. GetClientCertificate: func(cri *CertificateRequestInfo) (*tls.Certificate, error) { return &cert, nil },
  899. },
  900. serverCfg: &Config{
  901. GetCertificate: func(chi *ClientHelloInfo) (*tls.Certificate, error) { return &srvCert, nil },
  902. // Certificates: []tls.Certificate{srvCert},
  903. ClientAuth: RequireAndVerifyClientCert,
  904. ClientCAs: caPool,
  905. },
  906. },
  907. }
  908. for name, tt := range tests {
  909. tt := tt
  910. t.Run(name, func(t *testing.T) {
  911. ca, cb := dpipe.Pipe()
  912. type result struct {
  913. c *Conn
  914. err error
  915. }
  916. c := make(chan result)
  917. go func() {
  918. client, err := Client(ca, tt.clientCfg)
  919. c <- result{client, err}
  920. }()
  921. server, err := Server(cb, tt.serverCfg)
  922. res := <-c
  923. defer func() {
  924. if err == nil {
  925. _ = server.Close()
  926. }
  927. if res.err == nil {
  928. _ = res.c.Close()
  929. }
  930. }()
  931. if tt.wantErr {
  932. if err != nil {
  933. // Error expected, test succeeded
  934. return
  935. }
  936. t.Error("Error expected")
  937. }
  938. if err != nil {
  939. t.Errorf("Server failed(%v)", err)
  940. }
  941. if res.err != nil {
  942. t.Errorf("Client failed(%v)", res.err)
  943. }
  944. actualClientCert := server.ConnectionState().PeerCertificates
  945. if tt.serverCfg.ClientAuth == RequireAnyClientCert || tt.serverCfg.ClientAuth == RequireAndVerifyClientCert {
  946. if actualClientCert == nil {
  947. t.Errorf("Client did not provide a certificate")
  948. }
  949. var cfgCert [][]byte
  950. if len(tt.clientCfg.Certificates) > 0 {
  951. cfgCert = tt.clientCfg.Certificates[0].Certificate
  952. }
  953. if tt.clientCfg.GetClientCertificate != nil {
  954. crt, err := tt.clientCfg.GetClientCertificate(&CertificateRequestInfo{})
  955. if err != nil {
  956. t.Errorf("Server configuration did not provide a certificate")
  957. }
  958. cfgCert = crt.Certificate
  959. }
  960. if len(cfgCert) == 0 || !bytes.Equal(cfgCert[0], actualClientCert[0]) {
  961. t.Errorf("Client certificate was not communicated correctly")
  962. }
  963. }
  964. if tt.serverCfg.ClientAuth == NoClientCert {
  965. if actualClientCert != nil {
  966. t.Errorf("Client certificate wasn't expected")
  967. }
  968. }
  969. actualServerCert := res.c.ConnectionState().PeerCertificates
  970. if actualServerCert == nil {
  971. t.Errorf("Server did not provide a certificate")
  972. }
  973. var cfgCert [][]byte
  974. if len(tt.serverCfg.Certificates) > 0 {
  975. cfgCert = tt.serverCfg.Certificates[0].Certificate
  976. }
  977. if tt.serverCfg.GetCertificate != nil {
  978. crt, err := tt.serverCfg.GetCertificate(&ClientHelloInfo{})
  979. if err != nil {
  980. t.Errorf("Server configuration did not provide a certificate")
  981. }
  982. cfgCert = crt.Certificate
  983. }
  984. if len(cfgCert) == 0 || !bytes.Equal(cfgCert[0], actualServerCert[0]) {
  985. t.Errorf("Server certificate was not communicated correctly")
  986. }
  987. })
  988. }
  989. })
  990. }
  991. func TestExtendedMasterSecret(t *testing.T) {
  992. // Check for leaking routines
  993. report := test.CheckRoutines(t)
  994. defer report()
  995. tests := map[string]struct {
  996. clientCfg *Config
  997. serverCfg *Config
  998. expectedClientErr error
  999. expectedServerErr error
  1000. }{
  1001. "Request_Request_ExtendedMasterSecret": {
  1002. clientCfg: &Config{
  1003. ExtendedMasterSecret: RequestExtendedMasterSecret,
  1004. },
  1005. serverCfg: &Config{
  1006. ExtendedMasterSecret: RequestExtendedMasterSecret,
  1007. },
  1008. expectedClientErr: nil,
  1009. expectedServerErr: nil,
  1010. },
  1011. "Request_Require_ExtendedMasterSecret": {
  1012. clientCfg: &Config{
  1013. ExtendedMasterSecret: RequestExtendedMasterSecret,
  1014. },
  1015. serverCfg: &Config{
  1016. ExtendedMasterSecret: RequireExtendedMasterSecret,
  1017. },
  1018. expectedClientErr: nil,
  1019. expectedServerErr: nil,
  1020. },
  1021. "Request_Disable_ExtendedMasterSecret": {
  1022. clientCfg: &Config{
  1023. ExtendedMasterSecret: RequestExtendedMasterSecret,
  1024. },
  1025. serverCfg: &Config{
  1026. ExtendedMasterSecret: DisableExtendedMasterSecret,
  1027. },
  1028. expectedClientErr: nil,
  1029. expectedServerErr: nil,
  1030. },
  1031. "Require_Request_ExtendedMasterSecret": {
  1032. clientCfg: &Config{
  1033. ExtendedMasterSecret: RequireExtendedMasterSecret,
  1034. },
  1035. serverCfg: &Config{
  1036. ExtendedMasterSecret: RequestExtendedMasterSecret,
  1037. },
  1038. expectedClientErr: nil,
  1039. expectedServerErr: nil,
  1040. },
  1041. "Require_Require_ExtendedMasterSecret": {
  1042. clientCfg: &Config{
  1043. ExtendedMasterSecret: RequireExtendedMasterSecret,
  1044. },
  1045. serverCfg: &Config{
  1046. ExtendedMasterSecret: RequireExtendedMasterSecret,
  1047. },
  1048. expectedClientErr: nil,
  1049. expectedServerErr: nil,
  1050. },
  1051. "Require_Disable_ExtendedMasterSecret": {
  1052. clientCfg: &Config{
  1053. ExtendedMasterSecret: RequireExtendedMasterSecret,
  1054. },
  1055. serverCfg: &Config{
  1056. ExtendedMasterSecret: DisableExtendedMasterSecret,
  1057. },
  1058. expectedClientErr: errClientRequiredButNoServerEMS,
  1059. expectedServerErr: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  1060. },
  1061. "Disable_Request_ExtendedMasterSecret": {
  1062. clientCfg: &Config{
  1063. ExtendedMasterSecret: DisableExtendedMasterSecret,
  1064. },
  1065. serverCfg: &Config{
  1066. ExtendedMasterSecret: RequestExtendedMasterSecret,
  1067. },
  1068. expectedClientErr: nil,
  1069. expectedServerErr: nil,
  1070. },
  1071. "Disable_Require_ExtendedMasterSecret": {
  1072. clientCfg: &Config{
  1073. ExtendedMasterSecret: DisableExtendedMasterSecret,
  1074. },
  1075. serverCfg: &Config{
  1076. ExtendedMasterSecret: RequireExtendedMasterSecret,
  1077. },
  1078. expectedClientErr: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  1079. expectedServerErr: errServerRequiredButNoClientEMS,
  1080. },
  1081. "Disable_Disable_ExtendedMasterSecret": {
  1082. clientCfg: &Config{
  1083. ExtendedMasterSecret: DisableExtendedMasterSecret,
  1084. },
  1085. serverCfg: &Config{
  1086. ExtendedMasterSecret: DisableExtendedMasterSecret,
  1087. },
  1088. expectedClientErr: nil,
  1089. expectedServerErr: nil,
  1090. },
  1091. }
  1092. for name, tt := range tests {
  1093. tt := tt
  1094. t.Run(name, func(t *testing.T) {
  1095. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1096. defer cancel()
  1097. ca, cb := dpipe.Pipe()
  1098. type result struct {
  1099. c *Conn
  1100. err error
  1101. }
  1102. c := make(chan result)
  1103. go func() {
  1104. client, err := testClient(ctx, ca, tt.clientCfg, true)
  1105. c <- result{client, err}
  1106. }()
  1107. server, err := testServer(ctx, cb, tt.serverCfg, true)
  1108. res := <-c
  1109. defer func() {
  1110. if err == nil {
  1111. _ = server.Close()
  1112. }
  1113. if res.err == nil {
  1114. _ = res.c.Close()
  1115. }
  1116. }()
  1117. if !errors.Is(res.err, tt.expectedClientErr) {
  1118. t.Errorf("Client error expected: \"%v\" but got \"%v\"", tt.expectedClientErr, res.err)
  1119. }
  1120. if !errors.Is(err, tt.expectedServerErr) {
  1121. t.Errorf("Server error expected: \"%v\" but got \"%v\"", tt.expectedServerErr, err)
  1122. }
  1123. })
  1124. }
  1125. }
  1126. func TestServerCertificate(t *testing.T) {
  1127. // Check for leaking routines
  1128. report := test.CheckRoutines(t)
  1129. defer report()
  1130. cert, err := selfsign.GenerateSelfSigned()
  1131. if err != nil {
  1132. t.Fatal(err)
  1133. }
  1134. certificate, err := x509.ParseCertificate(cert.Certificate[0])
  1135. if err != nil {
  1136. t.Fatal(err)
  1137. }
  1138. caPool := x509.NewCertPool()
  1139. caPool.AddCert(certificate)
  1140. t.Run("parallel", func(t *testing.T) { // sync routines to check routine leak
  1141. tests := map[string]struct {
  1142. clientCfg *Config
  1143. serverCfg *Config
  1144. wantErr bool
  1145. }{
  1146. "no_ca": {
  1147. clientCfg: &Config{},
  1148. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  1149. wantErr: true,
  1150. },
  1151. "good_ca": {
  1152. clientCfg: &Config{RootCAs: caPool},
  1153. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  1154. },
  1155. "no_ca_skip_verify": {
  1156. clientCfg: &Config{InsecureSkipVerify: true},
  1157. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  1158. },
  1159. "good_ca_skip_verify_custom_verify_peer": {
  1160. clientCfg: &Config{RootCAs: caPool, Certificates: []tls.Certificate{cert}},
  1161. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: RequireAnyClientCert, VerifyPeerCertificate: func(cert [][]byte, chain [][]*x509.Certificate) error {
  1162. if len(chain) != 0 {
  1163. return errNotExpectedChain
  1164. }
  1165. return nil
  1166. }},
  1167. },
  1168. "good_ca_verify_custom_verify_peer": {
  1169. clientCfg: &Config{RootCAs: caPool, Certificates: []tls.Certificate{cert}},
  1170. serverCfg: &Config{ClientCAs: caPool, Certificates: []tls.Certificate{cert}, ClientAuth: RequireAndVerifyClientCert, VerifyPeerCertificate: func(cert [][]byte, chain [][]*x509.Certificate) error {
  1171. if len(chain) == 0 {
  1172. return errExpecedChain
  1173. }
  1174. return nil
  1175. }},
  1176. },
  1177. "good_ca_custom_verify_peer": {
  1178. clientCfg: &Config{
  1179. RootCAs: caPool,
  1180. VerifyPeerCertificate: func([][]byte, [][]*x509.Certificate) error {
  1181. return errWrongCert
  1182. },
  1183. },
  1184. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  1185. wantErr: true,
  1186. },
  1187. "server_name": {
  1188. clientCfg: &Config{RootCAs: caPool, ServerName: certificate.Subject.CommonName},
  1189. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  1190. },
  1191. "server_name_error": {
  1192. clientCfg: &Config{RootCAs: caPool, ServerName: "barfoo"},
  1193. serverCfg: &Config{Certificates: []tls.Certificate{cert}, ClientAuth: NoClientCert},
  1194. wantErr: true,
  1195. },
  1196. }
  1197. for name, tt := range tests {
  1198. tt := tt
  1199. t.Run(name, func(t *testing.T) {
  1200. ca, cb := dpipe.Pipe()
  1201. type result struct {
  1202. c *Conn
  1203. err error
  1204. }
  1205. srvCh := make(chan result)
  1206. go func() {
  1207. s, err := Server(cb, tt.serverCfg)
  1208. srvCh <- result{s, err}
  1209. }()
  1210. cli, err := Client(ca, tt.clientCfg)
  1211. if err == nil {
  1212. _ = cli.Close()
  1213. }
  1214. if !tt.wantErr && err != nil {
  1215. t.Errorf("Client failed(%v)", err)
  1216. }
  1217. if tt.wantErr && err == nil {
  1218. t.Fatal("Error expected")
  1219. }
  1220. srv := <-srvCh
  1221. if srv.err == nil {
  1222. _ = srv.c.Close()
  1223. }
  1224. })
  1225. }
  1226. })
  1227. }
  1228. func TestCipherSuiteConfiguration(t *testing.T) {
  1229. // Check for leaking routines
  1230. report := test.CheckRoutines(t)
  1231. defer report()
  1232. for _, test := range []struct {
  1233. Name string
  1234. ClientCipherSuites []CipherSuiteID
  1235. ServerCipherSuites []CipherSuiteID
  1236. WantClientError error
  1237. WantServerError error
  1238. WantSelectedCipherSuite CipherSuiteID
  1239. }{
  1240. {
  1241. Name: "No CipherSuites specified",
  1242. ClientCipherSuites: nil,
  1243. ServerCipherSuites: nil,
  1244. WantClientError: nil,
  1245. WantServerError: nil,
  1246. },
  1247. {
  1248. Name: "Invalid CipherSuite",
  1249. ClientCipherSuites: []CipherSuiteID{0x00},
  1250. ServerCipherSuites: []CipherSuiteID{0x00},
  1251. WantClientError: &invalidCipherSuiteError{0x00},
  1252. WantServerError: &invalidCipherSuiteError{0x00},
  1253. },
  1254. {
  1255. Name: "Valid CipherSuites specified",
  1256. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1257. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1258. WantClientError: nil,
  1259. WantServerError: nil,
  1260. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1261. },
  1262. {
  1263. Name: "CipherSuites mismatch",
  1264. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1265. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  1266. WantClientError: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
  1267. WantServerError: errCipherSuiteNoIntersection,
  1268. },
  1269. {
  1270. Name: "Valid CipherSuites CCM specified",
  1271. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM},
  1272. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM},
  1273. WantClientError: nil,
  1274. WantServerError: nil,
  1275. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
  1276. },
  1277. {
  1278. Name: "Valid CipherSuites CCM-8 specified",
  1279. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8},
  1280. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8},
  1281. WantClientError: nil,
  1282. WantServerError: nil,
  1283. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
  1284. },
  1285. {
  1286. Name: "Server supports subset of client suites",
  1287. ClientCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  1288. ServerCipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  1289. WantClientError: nil,
  1290. WantServerError: nil,
  1291. WantSelectedCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  1292. },
  1293. } {
  1294. test := test
  1295. t.Run(test.Name, func(t *testing.T) {
  1296. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1297. defer cancel()
  1298. ca, cb := dpipe.Pipe()
  1299. type result struct {
  1300. c *Conn
  1301. err error
  1302. }
  1303. c := make(chan result)
  1304. go func() {
  1305. client, err := testClient(ctx, ca, &Config{CipherSuites: test.ClientCipherSuites}, true)
  1306. c <- result{client, err}
  1307. }()
  1308. server, err := testServer(ctx, cb, &Config{CipherSuites: test.ServerCipherSuites}, true)
  1309. if err == nil {
  1310. defer func() {
  1311. _ = server.Close()
  1312. }()
  1313. }
  1314. if !errors.Is(err, test.WantServerError) {
  1315. t.Errorf("TestCipherSuiteConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
  1316. }
  1317. res := <-c
  1318. if res.err == nil {
  1319. _ = server.Close()
  1320. _ = res.c.Close()
  1321. }
  1322. if !errors.Is(res.err, test.WantClientError) {
  1323. t.Errorf("TestSRTPConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
  1324. }
  1325. if test.WantSelectedCipherSuite != 0x00 && res.c.state.cipherSuite.ID() != test.WantSelectedCipherSuite {
  1326. t.Errorf("TestCipherSuiteConfiguration: Server Selected Bad Cipher Suite '%s': expected(%v) actual(%v)", test.Name, test.WantSelectedCipherSuite, res.c.state.cipherSuite.ID())
  1327. }
  1328. })
  1329. }
  1330. }
  1331. func TestCertificateAndPSKServer(t *testing.T) {
  1332. // Check for leaking routines
  1333. report := test.CheckRoutines(t)
  1334. defer report()
  1335. for _, test := range []struct {
  1336. Name string
  1337. ClientPSK bool
  1338. }{
  1339. {
  1340. Name: "Client uses PKI",
  1341. ClientPSK: false,
  1342. },
  1343. {
  1344. Name: "Client uses PSK",
  1345. ClientPSK: true,
  1346. },
  1347. } {
  1348. test := test
  1349. t.Run(test.Name, func(t *testing.T) {
  1350. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1351. defer cancel()
  1352. ca, cb := dpipe.Pipe()
  1353. type result struct {
  1354. c *Conn
  1355. err error
  1356. }
  1357. c := make(chan result)
  1358. go func() {
  1359. config := &Config{CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}}
  1360. if test.ClientPSK {
  1361. config.PSK = func([]byte) ([]byte, error) {
  1362. return []byte{0x00, 0x01, 0x02}, nil
  1363. }
  1364. config.PSKIdentityHint = []byte{0x00}
  1365. config.CipherSuites = []CipherSuiteID{TLS_PSK_WITH_AES_128_GCM_SHA256}
  1366. }
  1367. client, err := testClient(ctx, ca, config, false)
  1368. c <- result{client, err}
  1369. }()
  1370. config := &Config{
  1371. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_PSK_WITH_AES_128_GCM_SHA256},
  1372. PSK: func([]byte) ([]byte, error) {
  1373. return []byte{0x00, 0x01, 0x02}, nil
  1374. },
  1375. }
  1376. server, err := testServer(ctx, cb, config, true)
  1377. if err == nil {
  1378. defer func() {
  1379. _ = server.Close()
  1380. }()
  1381. } else {
  1382. t.Errorf("TestCertificateAndPSKServer: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, nil, err)
  1383. }
  1384. res := <-c
  1385. if res.err == nil {
  1386. _ = server.Close()
  1387. _ = res.c.Close()
  1388. } else {
  1389. t.Errorf("TestCertificateAndPSKServer: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, nil, res.err)
  1390. }
  1391. })
  1392. }
  1393. }
  1394. func TestPSKConfiguration(t *testing.T) {
  1395. // Check for leaking routines
  1396. report := test.CheckRoutines(t)
  1397. defer report()
  1398. for _, test := range []struct {
  1399. Name string
  1400. ClientHasCertificate bool
  1401. ServerHasCertificate bool
  1402. ClientPSK PSKCallback
  1403. ServerPSK PSKCallback
  1404. ClientPSKIdentity []byte
  1405. ServerPSKIdentity []byte
  1406. WantClientError error
  1407. WantServerError error
  1408. }{
  1409. {
  1410. Name: "PSK and no certificate specified",
  1411. ClientHasCertificate: false,
  1412. ServerHasCertificate: false,
  1413. ClientPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1414. ServerPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1415. ClientPSKIdentity: []byte{0x00},
  1416. ServerPSKIdentity: []byte{0x00},
  1417. WantClientError: errNoAvailablePSKCipherSuite,
  1418. WantServerError: errNoAvailablePSKCipherSuite,
  1419. },
  1420. {
  1421. Name: "PSK and certificate specified",
  1422. ClientHasCertificate: true,
  1423. ServerHasCertificate: true,
  1424. ClientPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1425. ServerPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1426. ClientPSKIdentity: []byte{0x00},
  1427. ServerPSKIdentity: []byte{0x00},
  1428. WantClientError: errNoAvailablePSKCipherSuite,
  1429. WantServerError: errNoAvailablePSKCipherSuite,
  1430. },
  1431. {
  1432. Name: "PSK and no identity specified",
  1433. ClientHasCertificate: false,
  1434. ServerHasCertificate: false,
  1435. ClientPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1436. ServerPSK: func([]byte) ([]byte, error) { return []byte{0x00, 0x01, 0x02}, nil },
  1437. ClientPSKIdentity: nil,
  1438. ServerPSKIdentity: nil,
  1439. WantClientError: errPSKAndIdentityMustBeSetForClient,
  1440. WantServerError: errNoAvailablePSKCipherSuite,
  1441. },
  1442. {
  1443. Name: "No PSK and identity specified",
  1444. ClientHasCertificate: false,
  1445. ServerHasCertificate: false,
  1446. ClientPSK: nil,
  1447. ServerPSK: nil,
  1448. ClientPSKIdentity: []byte{0x00},
  1449. ServerPSKIdentity: []byte{0x00},
  1450. WantClientError: errIdentityNoPSK,
  1451. WantServerError: errIdentityNoPSK,
  1452. },
  1453. } {
  1454. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  1455. defer cancel()
  1456. ca, cb := dpipe.Pipe()
  1457. type result struct {
  1458. c *Conn
  1459. err error
  1460. }
  1461. c := make(chan result)
  1462. go func() {
  1463. client, err := testClient(ctx, ca, &Config{PSK: test.ClientPSK, PSKIdentityHint: test.ClientPSKIdentity}, test.ClientHasCertificate)
  1464. c <- result{client, err}
  1465. }()
  1466. _, err := testServer(ctx, cb, &Config{PSK: test.ServerPSK, PSKIdentityHint: test.ServerPSKIdentity}, test.ServerHasCertificate)
  1467. if err != nil || test.WantServerError != nil {
  1468. if !(err != nil && test.WantServerError != nil && err.Error() == test.WantServerError.Error()) {
  1469. t.Fatalf("TestPSKConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
  1470. }
  1471. }
  1472. res := <-c
  1473. if res.err != nil || test.WantClientError != nil {
  1474. if !(res.err != nil && test.WantClientError != nil && res.err.Error() == test.WantClientError.Error()) {
  1475. t.Fatalf("TestPSKConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
  1476. }
  1477. }
  1478. }
  1479. }
  1480. func TestServerTimeout(t *testing.T) {
  1481. // Limit runtime in case of deadlocks
  1482. lim := test.TimeOut(time.Second * 20)
  1483. defer lim.Stop()
  1484. // Check for leaking routines
  1485. report := test.CheckRoutines(t)
  1486. defer report()
  1487. cookie := make([]byte, 20)
  1488. _, err := rand.Read(cookie)
  1489. if err != nil {
  1490. t.Fatal(err)
  1491. }
  1492. var rand [28]byte
  1493. random := handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand}
  1494. cipherSuites := []CipherSuite{
  1495. &ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{},
  1496. &ciphersuite.TLSEcdheRsaWithAes128GcmSha256{},
  1497. }
  1498. extensions := []extension.Extension{
  1499. &extension.SupportedSignatureAlgorithms{
  1500. SignatureHashAlgorithms: []signaturehash.Algorithm{
  1501. {Hash: hash.SHA256, Signature: signature.ECDSA},
  1502. {Hash: hash.SHA384, Signature: signature.ECDSA},
  1503. {Hash: hash.SHA512, Signature: signature.ECDSA},
  1504. {Hash: hash.SHA256, Signature: signature.RSA},
  1505. {Hash: hash.SHA384, Signature: signature.RSA},
  1506. {Hash: hash.SHA512, Signature: signature.RSA},
  1507. },
  1508. },
  1509. &extension.SupportedEllipticCurves{
  1510. EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384},
  1511. },
  1512. &extension.SupportedPointFormats{
  1513. PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
  1514. },
  1515. }
  1516. record := &recordlayer.RecordLayer{
  1517. Header: recordlayer.Header{
  1518. SequenceNumber: 0,
  1519. Version: protocol.Version1_2,
  1520. },
  1521. Content: &handshake.Handshake{
  1522. // sequenceNumber and messageSequence line up, may need to be re-evaluated
  1523. Header: handshake.Header{
  1524. MessageSequence: 0,
  1525. },
  1526. Message: &handshake.MessageClientHello{
  1527. Version: protocol.Version1_2,
  1528. Cookie: cookie,
  1529. Random: random,
  1530. CipherSuiteIDs: cipherSuiteIDs(cipherSuites),
  1531. CompressionMethods: defaultCompressionMethods(),
  1532. Extensions: extensions,
  1533. },
  1534. },
  1535. }
  1536. packet, err := record.Marshal()
  1537. if err != nil {
  1538. t.Fatal(err)
  1539. }
  1540. ca, cb := dpipe.Pipe()
  1541. defer func() {
  1542. err := ca.Close()
  1543. if err != nil {
  1544. t.Fatal(err)
  1545. }
  1546. }()
  1547. // Client reader
  1548. caReadChan := make(chan []byte, 1000)
  1549. go func() {
  1550. for {
  1551. data := make([]byte, 8192)
  1552. n, err := ca.Read(data)
  1553. if err != nil {
  1554. return
  1555. }
  1556. caReadChan <- data[:n]
  1557. }
  1558. }()
  1559. // Start sending ClientHello packets until server responds with first packet
  1560. go func() {
  1561. for {
  1562. select {
  1563. case <-time.After(10 * time.Millisecond):
  1564. _, err := ca.Write(packet)
  1565. if err != nil {
  1566. return
  1567. }
  1568. case <-caReadChan:
  1569. // Once we receive the first reply from the server, stop
  1570. return
  1571. }
  1572. }
  1573. }()
  1574. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  1575. defer cancel()
  1576. config := &Config{
  1577. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1578. FlightInterval: 100 * time.Millisecond,
  1579. }
  1580. _, serverErr := testServer(ctx, cb, config, true)
  1581. var netErr net.Error
  1582. if !errors.As(serverErr, &netErr) || !netErr.Timeout() {
  1583. t.Fatalf("Client error exp(Temporary network error) failed(%v)", serverErr)
  1584. }
  1585. // Wait a little longer to ensure no additional messages have been sent by the server
  1586. time.Sleep(300 * time.Millisecond)
  1587. select {
  1588. case msg := <-caReadChan:
  1589. t.Fatalf("Expected no additional messages from server, got: %+v", msg)
  1590. default:
  1591. }
  1592. }
  1593. func TestProtocolVersionValidation(t *testing.T) {
  1594. // Limit runtime in case of deadlocks
  1595. lim := test.TimeOut(time.Second * 20)
  1596. defer lim.Stop()
  1597. // Check for leaking routines
  1598. report := test.CheckRoutines(t)
  1599. defer report()
  1600. cookie := make([]byte, 20)
  1601. if _, err := rand.Read(cookie); err != nil {
  1602. t.Fatal(err)
  1603. }
  1604. var rand [28]byte
  1605. random := handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand}
  1606. config := &Config{
  1607. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1608. FlightInterval: 100 * time.Millisecond,
  1609. }
  1610. t.Run("Server", func(t *testing.T) {
  1611. serverCases := map[string]struct {
  1612. records []*recordlayer.RecordLayer
  1613. }{
  1614. "ClientHelloVersion": {
  1615. records: []*recordlayer.RecordLayer{
  1616. {
  1617. Header: recordlayer.Header{
  1618. Version: protocol.Version1_2,
  1619. },
  1620. Content: &handshake.Handshake{
  1621. Message: &handshake.MessageClientHello{
  1622. Version: protocol.Version{Major: 0xfe, Minor: 0xff}, // try to downgrade
  1623. Cookie: cookie,
  1624. Random: random,
  1625. CipherSuiteIDs: []uint16{uint16((&ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{}).ID())},
  1626. CompressionMethods: defaultCompressionMethods(),
  1627. },
  1628. },
  1629. },
  1630. },
  1631. },
  1632. "SecondsClientHelloVersion": {
  1633. records: []*recordlayer.RecordLayer{
  1634. {
  1635. Header: recordlayer.Header{
  1636. Version: protocol.Version1_2,
  1637. },
  1638. Content: &handshake.Handshake{
  1639. Message: &handshake.MessageClientHello{
  1640. Version: protocol.Version1_2,
  1641. Cookie: cookie,
  1642. Random: random,
  1643. CipherSuiteIDs: []uint16{uint16((&ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{}).ID())},
  1644. CompressionMethods: defaultCompressionMethods(),
  1645. },
  1646. },
  1647. },
  1648. {
  1649. Header: recordlayer.Header{
  1650. Version: protocol.Version1_2,
  1651. SequenceNumber: 1,
  1652. },
  1653. Content: &handshake.Handshake{
  1654. Header: handshake.Header{
  1655. MessageSequence: 1,
  1656. },
  1657. Message: &handshake.MessageClientHello{
  1658. Version: protocol.Version{Major: 0xfe, Minor: 0xff}, // try to downgrade
  1659. Cookie: cookie,
  1660. Random: random,
  1661. CipherSuiteIDs: []uint16{uint16((&ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{}).ID())},
  1662. CompressionMethods: defaultCompressionMethods(),
  1663. },
  1664. },
  1665. },
  1666. },
  1667. },
  1668. }
  1669. for name, c := range serverCases {
  1670. c := c
  1671. t.Run(name, func(t *testing.T) {
  1672. ca, cb := dpipe.Pipe()
  1673. defer func() {
  1674. err := ca.Close()
  1675. if err != nil {
  1676. t.Error(err)
  1677. }
  1678. }()
  1679. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  1680. defer cancel()
  1681. var wg sync.WaitGroup
  1682. wg.Add(1)
  1683. defer wg.Wait()
  1684. go func() {
  1685. defer wg.Done()
  1686. if _, err := testServer(ctx, cb, config, true); !errors.Is(err, errUnsupportedProtocolVersion) {
  1687. t.Errorf("Client error exp(%v) failed(%v)", errUnsupportedProtocolVersion, err)
  1688. }
  1689. }()
  1690. time.Sleep(50 * time.Millisecond)
  1691. resp := make([]byte, 1024)
  1692. for _, record := range c.records {
  1693. packet, err := record.Marshal()
  1694. if err != nil {
  1695. t.Fatal(err)
  1696. }
  1697. if _, werr := ca.Write(packet); werr != nil {
  1698. t.Fatal(werr)
  1699. }
  1700. n, rerr := ca.Read(resp[:cap(resp)])
  1701. if rerr != nil {
  1702. t.Fatal(rerr)
  1703. }
  1704. resp = resp[:n]
  1705. }
  1706. h := &recordlayer.Header{}
  1707. if err := h.Unmarshal(resp); err != nil {
  1708. t.Fatal("Failed to unmarshal response")
  1709. }
  1710. if h.ContentType != protocol.ContentTypeAlert {
  1711. t.Errorf("Peer must return alert to unsupported protocol version")
  1712. }
  1713. })
  1714. }
  1715. })
  1716. t.Run("Client", func(t *testing.T) {
  1717. clientCases := map[string]struct {
  1718. records []*recordlayer.RecordLayer
  1719. }{
  1720. "ServerHelloVersion": {
  1721. records: []*recordlayer.RecordLayer{
  1722. {
  1723. Header: recordlayer.Header{
  1724. Version: protocol.Version1_2,
  1725. },
  1726. Content: &handshake.Handshake{
  1727. Message: &handshake.MessageHelloVerifyRequest{
  1728. Version: protocol.Version1_2,
  1729. Cookie: cookie,
  1730. },
  1731. },
  1732. },
  1733. {
  1734. Header: recordlayer.Header{
  1735. Version: protocol.Version1_2,
  1736. SequenceNumber: 1,
  1737. },
  1738. Content: &handshake.Handshake{
  1739. Header: handshake.Header{
  1740. MessageSequence: 1,
  1741. },
  1742. Message: &handshake.MessageServerHello{
  1743. Version: protocol.Version{Major: 0xfe, Minor: 0xff}, // try to downgrade
  1744. Random: random,
  1745. CipherSuiteID: func() *uint16 { id := uint16(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256); return &id }(),
  1746. CompressionMethod: defaultCompressionMethods()[0],
  1747. },
  1748. },
  1749. },
  1750. },
  1751. },
  1752. }
  1753. for name, c := range clientCases {
  1754. c := c
  1755. t.Run(name, func(t *testing.T) {
  1756. ca, cb := dpipe.Pipe()
  1757. defer func() {
  1758. err := ca.Close()
  1759. if err != nil {
  1760. t.Error(err)
  1761. }
  1762. }()
  1763. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  1764. defer cancel()
  1765. var wg sync.WaitGroup
  1766. wg.Add(1)
  1767. defer wg.Wait()
  1768. go func() {
  1769. defer wg.Done()
  1770. if _, err := testClient(ctx, cb, config, true); !errors.Is(err, errUnsupportedProtocolVersion) {
  1771. t.Errorf("Server error exp(%v) failed(%v)", errUnsupportedProtocolVersion, err)
  1772. }
  1773. }()
  1774. time.Sleep(50 * time.Millisecond)
  1775. for _, record := range c.records {
  1776. if _, err := ca.Read(make([]byte, 1024)); err != nil {
  1777. t.Fatal(err)
  1778. }
  1779. packet, err := record.Marshal()
  1780. if err != nil {
  1781. t.Fatal(err)
  1782. }
  1783. if _, err := ca.Write(packet); err != nil {
  1784. t.Fatal(err)
  1785. }
  1786. }
  1787. resp := make([]byte, 1024)
  1788. n, err := ca.Read(resp)
  1789. if err != nil {
  1790. t.Fatal(err)
  1791. }
  1792. resp = resp[:n]
  1793. h := &recordlayer.Header{}
  1794. if err := h.Unmarshal(resp); err != nil {
  1795. t.Fatal("Failed to unmarshal response")
  1796. }
  1797. if h.ContentType != protocol.ContentTypeAlert {
  1798. t.Errorf("Peer must return alert to unsupported protocol version")
  1799. }
  1800. })
  1801. }
  1802. })
  1803. }
  1804. func TestMultipleHelloVerifyRequest(t *testing.T) {
  1805. // Limit runtime in case of deadlocks
  1806. lim := test.TimeOut(time.Second * 20)
  1807. defer lim.Stop()
  1808. // Check for leaking routines
  1809. report := test.CheckRoutines(t)
  1810. defer report()
  1811. cookies := [][]byte{
  1812. // first clientHello contains an empty cookie
  1813. {},
  1814. }
  1815. var packets [][]byte
  1816. for i := 0; i < 2; i++ {
  1817. cookie := make([]byte, 20)
  1818. if _, err := rand.Read(cookie); err != nil {
  1819. t.Fatal(err)
  1820. }
  1821. cookies = append(cookies, cookie)
  1822. record := &recordlayer.RecordLayer{
  1823. Header: recordlayer.Header{
  1824. SequenceNumber: uint64(i),
  1825. Version: protocol.Version1_2,
  1826. },
  1827. Content: &handshake.Handshake{
  1828. Header: handshake.Header{
  1829. MessageSequence: uint16(i),
  1830. },
  1831. Message: &handshake.MessageHelloVerifyRequest{
  1832. Version: protocol.Version1_2,
  1833. Cookie: cookie,
  1834. },
  1835. },
  1836. }
  1837. packet, err := record.Marshal()
  1838. if err != nil {
  1839. t.Fatal(err)
  1840. }
  1841. packets = append(packets, packet)
  1842. }
  1843. ca, cb := dpipe.Pipe()
  1844. defer func() {
  1845. err := ca.Close()
  1846. if err != nil {
  1847. t.Error(err)
  1848. }
  1849. }()
  1850. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  1851. defer cancel()
  1852. var wg sync.WaitGroup
  1853. wg.Add(1)
  1854. defer wg.Wait()
  1855. go func() {
  1856. defer wg.Done()
  1857. _, _ = testClient(ctx, ca, &Config{}, false)
  1858. }()
  1859. for i, cookie := range cookies {
  1860. // read client hello
  1861. resp := make([]byte, 1024)
  1862. n, err := cb.Read(resp)
  1863. if err != nil {
  1864. t.Fatal(err)
  1865. }
  1866. record := &recordlayer.RecordLayer{}
  1867. if err := record.Unmarshal(resp[:n]); err != nil {
  1868. t.Fatal(err)
  1869. }
  1870. clientHello, ok := record.Content.(*handshake.Handshake).Message.(*handshake.MessageClientHello)
  1871. if !ok {
  1872. t.Fatal("Failed to cast MessageClientHello")
  1873. }
  1874. if !bytes.Equal(clientHello.Cookie, cookie) {
  1875. t.Fatalf("Wrong cookie, expected: %x, got: %x", clientHello.Cookie, cookie)
  1876. }
  1877. if len(packets) <= i {
  1878. break
  1879. }
  1880. // write hello verify request
  1881. if _, err := cb.Write(packets[i]); err != nil {
  1882. t.Fatal(err)
  1883. }
  1884. }
  1885. cancel()
  1886. }
  1887. // Assert that a DTLS Server always responds with RenegotiationInfo if
  1888. // a ClientHello contained that extension or not
  1889. func TestRenegotationInfo(t *testing.T) {
  1890. // Limit runtime in case of deadlocks
  1891. lim := test.TimeOut(10 * time.Second)
  1892. defer lim.Stop()
  1893. // Check for leaking routines
  1894. report := test.CheckRoutines(t)
  1895. defer report()
  1896. resp := make([]byte, 1024)
  1897. for _, testCase := range []struct {
  1898. Name string
  1899. SendRenegotiationInfo bool
  1900. }{
  1901. {
  1902. "Include RenegotiationInfo",
  1903. true,
  1904. },
  1905. {
  1906. "No RenegotiationInfo",
  1907. false,
  1908. },
  1909. } {
  1910. test := testCase
  1911. t.Run(test.Name, func(t *testing.T) {
  1912. ca, cb := dpipe.Pipe()
  1913. defer func() {
  1914. if err := ca.Close(); err != nil {
  1915. t.Error(err)
  1916. }
  1917. }()
  1918. ctx, cancel := context.WithCancel(context.Background())
  1919. defer cancel()
  1920. go func() {
  1921. if _, err := testServer(ctx, cb, &Config{}, true); !errors.Is(err, context.Canceled) {
  1922. t.Error(err)
  1923. }
  1924. }()
  1925. time.Sleep(50 * time.Millisecond)
  1926. extensions := []extension.Extension{}
  1927. if test.SendRenegotiationInfo {
  1928. extensions = append(extensions, &extension.RenegotiationInfo{
  1929. RenegotiatedConnection: 0,
  1930. })
  1931. }
  1932. err := sendClientHello([]byte{}, ca, 0, extensions)
  1933. if err != nil {
  1934. t.Fatal(err)
  1935. }
  1936. n, err := ca.Read(resp)
  1937. if err != nil {
  1938. t.Fatal(err)
  1939. }
  1940. r := &recordlayer.RecordLayer{}
  1941. if err = r.Unmarshal(resp[:n]); err != nil {
  1942. t.Fatal(err)
  1943. }
  1944. helloVerifyRequest, ok := r.Content.(*handshake.Handshake).Message.(*handshake.MessageHelloVerifyRequest)
  1945. if !ok {
  1946. t.Fatal("Failed to cast MessageHelloVerifyRequest")
  1947. }
  1948. err = sendClientHello(helloVerifyRequest.Cookie, ca, 1, extensions)
  1949. if err != nil {
  1950. t.Fatal(err)
  1951. }
  1952. if n, err = ca.Read(resp); err != nil {
  1953. t.Fatal(err)
  1954. }
  1955. messages, err := recordlayer.UnpackDatagram(resp[:n])
  1956. if err != nil {
  1957. t.Fatal(err)
  1958. }
  1959. if err := r.Unmarshal(messages[0]); err != nil {
  1960. t.Fatal(err)
  1961. }
  1962. serverHello, ok := r.Content.(*handshake.Handshake).Message.(*handshake.MessageServerHello)
  1963. if !ok {
  1964. t.Fatal("Failed to cast MessageServerHello")
  1965. }
  1966. gotNegotationInfo := false
  1967. for _, v := range serverHello.Extensions {
  1968. if _, ok := v.(*extension.RenegotiationInfo); ok {
  1969. gotNegotationInfo = true
  1970. }
  1971. }
  1972. if !gotNegotationInfo {
  1973. t.Fatalf("Received ServerHello without RenegotiationInfo")
  1974. }
  1975. })
  1976. }
  1977. }
  1978. func TestServerNameIndicationExtension(t *testing.T) {
  1979. // Limit runtime in case of deadlocks
  1980. lim := test.TimeOut(time.Second * 20)
  1981. defer lim.Stop()
  1982. // Check for leaking routines
  1983. report := test.CheckRoutines(t)
  1984. defer report()
  1985. for _, test := range []struct {
  1986. Name string
  1987. ServerName string
  1988. Expected []byte
  1989. IncludeSNI bool
  1990. }{
  1991. {
  1992. Name: "Server name is a valid hostname",
  1993. ServerName: "example.com",
  1994. Expected: []byte("example.com"),
  1995. IncludeSNI: true,
  1996. },
  1997. {
  1998. Name: "Server name is an IP literal",
  1999. ServerName: "1.2.3.4",
  2000. Expected: []byte(""),
  2001. IncludeSNI: false,
  2002. },
  2003. {
  2004. Name: "Server name is empty",
  2005. ServerName: "",
  2006. Expected: []byte(""),
  2007. IncludeSNI: false,
  2008. },
  2009. } {
  2010. test := test
  2011. t.Run(test.Name, func(t *testing.T) {
  2012. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2013. defer cancel()
  2014. ca, cb := dpipe.Pipe()
  2015. go func() {
  2016. conf := &Config{
  2017. ServerName: test.ServerName,
  2018. }
  2019. _, _ = testClient(ctx, ca, conf, false)
  2020. }()
  2021. // Receive ClientHello
  2022. resp := make([]byte, 1024)
  2023. n, err := cb.Read(resp)
  2024. if err != nil {
  2025. t.Fatal(err)
  2026. }
  2027. r := &recordlayer.RecordLayer{}
  2028. if err = r.Unmarshal(resp[:n]); err != nil {
  2029. t.Fatal(err)
  2030. }
  2031. clientHello, ok := r.Content.(*handshake.Handshake).Message.(*handshake.MessageClientHello)
  2032. if !ok {
  2033. t.Fatal("Failed to cast MessageClientHello")
  2034. }
  2035. gotSNI := false
  2036. var actualServerName string
  2037. for _, v := range clientHello.Extensions {
  2038. if _, ok := v.(*extension.ServerName); ok {
  2039. gotSNI = true
  2040. extensionServerName, ok := v.(*extension.ServerName)
  2041. if !ok {
  2042. t.Fatal("Failed to cast extension.ServerName")
  2043. }
  2044. actualServerName = extensionServerName.ServerName
  2045. }
  2046. }
  2047. if gotSNI != test.IncludeSNI {
  2048. t.Errorf("TestSNI: unexpected SNI inclusion '%s': expected(%v) actual(%v)", test.Name, test.IncludeSNI, gotSNI)
  2049. }
  2050. if !bytes.Equal([]byte(actualServerName), test.Expected) {
  2051. t.Errorf("TestSNI: server name mismatch '%s': expected(%v) actual(%v)", test.Name, test.Expected, actualServerName)
  2052. }
  2053. })
  2054. }
  2055. }
  2056. func TestALPNExtension(t *testing.T) {
  2057. // Limit runtime in case of deadlocks
  2058. lim := test.TimeOut(time.Second * 20)
  2059. defer lim.Stop()
  2060. // Check for leaking routines
  2061. report := test.CheckRoutines(t)
  2062. defer report()
  2063. for _, test := range []struct {
  2064. Name string
  2065. ClientProtocolNameList []string
  2066. ServerProtocolNameList []string
  2067. ExpectedProtocol string
  2068. ExpectAlertFromClient bool
  2069. ExpectAlertFromServer bool
  2070. Alert alert.Description
  2071. }{
  2072. {
  2073. Name: "Negotiate a protocol",
  2074. ClientProtocolNameList: []string{"http/1.1", "spd/1"},
  2075. ServerProtocolNameList: []string{"spd/1"},
  2076. ExpectedProtocol: "spd/1",
  2077. ExpectAlertFromClient: false,
  2078. ExpectAlertFromServer: false,
  2079. Alert: 0,
  2080. },
  2081. {
  2082. Name: "Server doesn't support any",
  2083. ClientProtocolNameList: []string{"http/1.1", "spd/1"},
  2084. ServerProtocolNameList: []string{},
  2085. ExpectedProtocol: "",
  2086. ExpectAlertFromClient: false,
  2087. ExpectAlertFromServer: false,
  2088. Alert: 0,
  2089. },
  2090. {
  2091. Name: "Negotiate with higher server precedence",
  2092. ClientProtocolNameList: []string{"http/1.1", "spd/1", "http/3"},
  2093. ServerProtocolNameList: []string{"ssh/2", "http/3", "spd/1"},
  2094. ExpectedProtocol: "http/3",
  2095. ExpectAlertFromClient: false,
  2096. ExpectAlertFromServer: false,
  2097. Alert: 0,
  2098. },
  2099. {
  2100. Name: "Empty intersection",
  2101. ClientProtocolNameList: []string{"http/1.1", "http/3"},
  2102. ServerProtocolNameList: []string{"ssh/2", "spd/1"},
  2103. ExpectedProtocol: "",
  2104. ExpectAlertFromClient: false,
  2105. ExpectAlertFromServer: true,
  2106. Alert: alert.NoApplicationProtocol,
  2107. },
  2108. {
  2109. Name: "Multiple protocols in ServerHello",
  2110. ClientProtocolNameList: []string{"http/1.1"},
  2111. ServerProtocolNameList: []string{"http/1.1"},
  2112. ExpectedProtocol: "http/1.1",
  2113. ExpectAlertFromClient: true,
  2114. ExpectAlertFromServer: false,
  2115. Alert: alert.InternalError,
  2116. },
  2117. } {
  2118. test := test
  2119. t.Run(test.Name, func(t *testing.T) {
  2120. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2121. defer cancel()
  2122. ca, cb := dpipe.Pipe()
  2123. go func() {
  2124. conf := &Config{
  2125. SupportedProtocols: test.ClientProtocolNameList,
  2126. }
  2127. _, _ = testClient(ctx, ca, conf, false)
  2128. }()
  2129. // Receive ClientHello
  2130. resp := make([]byte, 1024)
  2131. n, err := cb.Read(resp)
  2132. if err != nil {
  2133. t.Fatal(err)
  2134. }
  2135. ctx2, cancel2 := context.WithTimeout(context.Background(), 10*time.Second)
  2136. defer cancel2()
  2137. ca2, cb2 := dpipe.Pipe()
  2138. go func() {
  2139. conf := &Config{
  2140. SupportedProtocols: test.ServerProtocolNameList,
  2141. }
  2142. if _, err2 := testServer(ctx2, cb2, conf, true); !errors.Is(err2, context.Canceled) {
  2143. if test.ExpectAlertFromServer { //nolint
  2144. // Assert the error type?
  2145. } else {
  2146. t.Error(err2)
  2147. }
  2148. }
  2149. }()
  2150. time.Sleep(50 * time.Millisecond)
  2151. // Forward ClientHello
  2152. if _, err = ca2.Write(resp[:n]); err != nil {
  2153. t.Fatal(err)
  2154. }
  2155. // Receive HelloVerify
  2156. resp2 := make([]byte, 1024)
  2157. n, err = ca2.Read(resp2)
  2158. if err != nil {
  2159. t.Fatal(err)
  2160. }
  2161. // Forward HelloVerify
  2162. if _, err = cb.Write(resp2[:n]); err != nil {
  2163. t.Fatal(err)
  2164. }
  2165. // Receive ClientHello
  2166. resp3 := make([]byte, 1024)
  2167. n, err = cb.Read(resp3)
  2168. if err != nil {
  2169. t.Fatal(err)
  2170. }
  2171. // Forward ClientHello
  2172. if _, err = ca2.Write(resp3[:n]); err != nil {
  2173. t.Fatal(err)
  2174. }
  2175. // Receive ServerHello
  2176. resp4 := make([]byte, 1024)
  2177. n, err = ca2.Read(resp4)
  2178. if err != nil {
  2179. t.Fatal(err)
  2180. }
  2181. messages, err := recordlayer.UnpackDatagram(resp4[:n])
  2182. if err != nil {
  2183. t.Fatal(err)
  2184. }
  2185. r := &recordlayer.RecordLayer{}
  2186. if err := r.Unmarshal(messages[0]); err != nil {
  2187. t.Fatal(err)
  2188. }
  2189. if test.ExpectAlertFromServer {
  2190. a, ok := r.Content.(*alert.Alert)
  2191. if !ok {
  2192. t.Fatal("Failed to cast alert.Alert")
  2193. }
  2194. if a.Description != test.Alert {
  2195. t.Errorf("ALPN %v: expected(%v) actual(%v)", test.Name, test.Alert, a.Description)
  2196. }
  2197. } else {
  2198. serverHello, ok := r.Content.(*handshake.Handshake).Message.(*handshake.MessageServerHello)
  2199. if !ok {
  2200. t.Fatal("Failed to cast handshake.MessageServerHello")
  2201. }
  2202. var negotiatedProtocol string
  2203. for _, v := range serverHello.Extensions {
  2204. if _, ok := v.(*extension.ALPN); ok {
  2205. e, ok := v.(*extension.ALPN)
  2206. if !ok {
  2207. t.Fatal("Failed to cast extension.ALPN")
  2208. }
  2209. negotiatedProtocol = e.ProtocolNameList[0]
  2210. // Manipulate ServerHello
  2211. if test.ExpectAlertFromClient {
  2212. e.ProtocolNameList = append(e.ProtocolNameList, "oops")
  2213. }
  2214. }
  2215. }
  2216. if negotiatedProtocol != test.ExpectedProtocol {
  2217. t.Errorf("ALPN %v: expected(%v) actual(%v)", test.Name, test.ExpectedProtocol, negotiatedProtocol)
  2218. }
  2219. s, err := r.Marshal()
  2220. if err != nil {
  2221. t.Fatal(err)
  2222. }
  2223. // Forward ServerHello
  2224. if _, err = cb.Write(s); err != nil {
  2225. t.Fatal(err)
  2226. }
  2227. if test.ExpectAlertFromClient {
  2228. resp5 := make([]byte, 1024)
  2229. n, err = cb.Read(resp5)
  2230. if err != nil {
  2231. t.Fatal(err)
  2232. }
  2233. r2 := &recordlayer.RecordLayer{}
  2234. if err := r2.Unmarshal(resp5[:n]); err != nil {
  2235. t.Fatal(err)
  2236. }
  2237. a, ok := r2.Content.(*alert.Alert)
  2238. if !ok {
  2239. t.Fatal("Failed to cast alert.Alert")
  2240. }
  2241. if a.Description != test.Alert {
  2242. t.Errorf("ALPN %v: expected(%v) actual(%v)", test.Name, test.Alert, a.Description)
  2243. }
  2244. }
  2245. }
  2246. time.Sleep(50 * time.Millisecond) // Give some time for returned errors
  2247. })
  2248. }
  2249. }
  2250. // Make sure the supported_groups extension is not included in the ServerHello
  2251. func TestSupportedGroupsExtension(t *testing.T) {
  2252. // Limit runtime in case of deadlocks
  2253. lim := test.TimeOut(time.Second * 20)
  2254. defer lim.Stop()
  2255. // Check for leaking routines
  2256. report := test.CheckRoutines(t)
  2257. defer report()
  2258. t.Run("ServerHello Supported Groups", func(t *testing.T) {
  2259. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2260. defer cancel()
  2261. ca, cb := dpipe.Pipe()
  2262. go func() {
  2263. if _, err := testServer(ctx, cb, &Config{}, true); !errors.Is(err, context.Canceled) {
  2264. t.Error(err)
  2265. }
  2266. }()
  2267. extensions := []extension.Extension{
  2268. &extension.SupportedEllipticCurves{
  2269. EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384},
  2270. },
  2271. &extension.SupportedPointFormats{
  2272. PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
  2273. },
  2274. }
  2275. time.Sleep(50 * time.Millisecond)
  2276. resp := make([]byte, 1024)
  2277. err := sendClientHello([]byte{}, ca, 0, extensions)
  2278. if err != nil {
  2279. t.Fatal(err)
  2280. }
  2281. // Receive ServerHello
  2282. n, err := ca.Read(resp)
  2283. if err != nil {
  2284. t.Fatal(err)
  2285. }
  2286. r := &recordlayer.RecordLayer{}
  2287. if err = r.Unmarshal(resp[:n]); err != nil {
  2288. t.Fatal(err)
  2289. }
  2290. helloVerifyRequest, ok := r.Content.(*handshake.Handshake).Message.(*handshake.MessageHelloVerifyRequest)
  2291. if !ok {
  2292. t.Fatal("Failed to cast MessageHelloVerifyRequest")
  2293. }
  2294. err = sendClientHello(helloVerifyRequest.Cookie, ca, 1, extensions)
  2295. if err != nil {
  2296. t.Fatal(err)
  2297. }
  2298. if n, err = ca.Read(resp); err != nil {
  2299. t.Fatal(err)
  2300. }
  2301. messages, err := recordlayer.UnpackDatagram(resp[:n])
  2302. if err != nil {
  2303. t.Fatal(err)
  2304. }
  2305. if err := r.Unmarshal(messages[0]); err != nil {
  2306. t.Fatal(err)
  2307. }
  2308. serverHello, ok := r.Content.(*handshake.Handshake).Message.(*handshake.MessageServerHello)
  2309. if !ok {
  2310. t.Fatal("Failed to cast MessageServerHello")
  2311. }
  2312. gotGroups := false
  2313. for _, v := range serverHello.Extensions {
  2314. if _, ok := v.(*extension.SupportedEllipticCurves); ok {
  2315. gotGroups = true
  2316. }
  2317. }
  2318. if gotGroups {
  2319. t.Errorf("TestSupportedGroups: supported_groups extension was sent in ServerHello")
  2320. }
  2321. })
  2322. }
  2323. func TestSessionResume(t *testing.T) {
  2324. // Limit runtime in case of deadlocks
  2325. lim := test.TimeOut(time.Second * 20)
  2326. defer lim.Stop()
  2327. // Check for leaking routines
  2328. report := test.CheckRoutines(t)
  2329. defer report()
  2330. t.Run("resumed", func(t *testing.T) {
  2331. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2332. defer cancel()
  2333. type result struct {
  2334. c *Conn
  2335. err error
  2336. }
  2337. clientRes := make(chan result, 1)
  2338. ss := &memSessStore{}
  2339. id, _ := hex.DecodeString("9b9fc92255634d9fb109febed42166717bb8ded8c738ba71bc7f2a0d9dae0306")
  2340. secret, _ := hex.DecodeString("2e942a37aca5241deb2295b5fcedac221c7078d2503d2b62aeb48c880d7da73c001238b708559686b9da6e829c05ead7")
  2341. s := Session{ID: id, Secret: secret}
  2342. ca, cb := dpipe.Pipe()
  2343. _ = ss.Set(id, s)
  2344. _ = ss.Set([]byte(ca.RemoteAddr().String()+"_example.com"), s)
  2345. go func() {
  2346. config := &Config{
  2347. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  2348. ServerName: "example.com",
  2349. SessionStore: ss,
  2350. MTU: 100,
  2351. }
  2352. c, err := testClient(ctx, ca, config, false)
  2353. clientRes <- result{c, err}
  2354. }()
  2355. config := &Config{
  2356. CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  2357. ServerName: "example.com",
  2358. SessionStore: ss,
  2359. MTU: 100,
  2360. }
  2361. server, err := testServer(ctx, cb, config, true)
  2362. if err != nil {
  2363. t.Fatalf("TestSessionResume: Server failed(%v)", err)
  2364. }
  2365. actualSessionID := server.ConnectionState().SessionID
  2366. actualMasterSecret := server.ConnectionState().masterSecret
  2367. if !bytes.Equal(actualSessionID, id) {
  2368. t.Errorf("TestSessionResumetion: SessionID Mismatch: expected(%v) actual(%v)", id, actualSessionID)
  2369. }
  2370. if !bytes.Equal(actualMasterSecret, secret) {
  2371. t.Errorf("TestSessionResumetion: masterSecret Mismatch: expected(%v) actual(%v)", secret, actualMasterSecret)
  2372. }
  2373. defer func() {
  2374. _ = server.Close()
  2375. }()
  2376. res := <-clientRes
  2377. if res.err != nil {
  2378. t.Fatal(res.err)
  2379. }
  2380. _ = res.c.Close()
  2381. })
  2382. t.Run("new session", func(t *testing.T) {
  2383. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2384. defer cancel()
  2385. type result struct {
  2386. c *Conn
  2387. err error
  2388. }
  2389. clientRes := make(chan result, 1)
  2390. s1 := &memSessStore{}
  2391. s2 := &memSessStore{}
  2392. ca, cb := dpipe.Pipe()
  2393. go func() {
  2394. config := &Config{
  2395. ServerName: "example.com",
  2396. SessionStore: s1,
  2397. }
  2398. c, err := testClient(ctx, ca, config, false)
  2399. clientRes <- result{c, err}
  2400. }()
  2401. config := &Config{
  2402. SessionStore: s2,
  2403. }
  2404. server, err := testServer(ctx, cb, config, true)
  2405. if err != nil {
  2406. t.Fatalf("TestSessionResumetion: Server failed(%v)", err)
  2407. }
  2408. actualSessionID := server.ConnectionState().SessionID
  2409. actualMasterSecret := server.ConnectionState().masterSecret
  2410. ss, _ := s2.Get(actualSessionID)
  2411. if !bytes.Equal(actualMasterSecret, ss.Secret) {
  2412. t.Errorf("TestSessionResumetion: masterSecret Mismatch: expected(%v) actual(%v)", ss.Secret, actualMasterSecret)
  2413. }
  2414. defer func() {
  2415. _ = server.Close()
  2416. }()
  2417. res := <-clientRes
  2418. if res.err != nil {
  2419. t.Fatal(res.err)
  2420. }
  2421. cs, _ := s1.Get([]byte(ca.RemoteAddr().String() + "_example.com"))
  2422. if !bytes.Equal(actualMasterSecret, cs.Secret) {
  2423. t.Errorf("TestSessionResumetion: masterSecret Mismatch: expected(%v) actual(%v)", ss.Secret, actualMasterSecret)
  2424. }
  2425. _ = res.c.Close()
  2426. })
  2427. }
  2428. type memSessStore struct {
  2429. sync.Map
  2430. }
  2431. func (ms *memSessStore) Set(key []byte, s Session) error {
  2432. k := hex.EncodeToString(key)
  2433. ms.Store(k, s)
  2434. return nil
  2435. }
  2436. func (ms *memSessStore) Get(key []byte) (Session, error) {
  2437. k := hex.EncodeToString(key)
  2438. v, ok := ms.Load(k)
  2439. if !ok {
  2440. return Session{}, nil
  2441. }
  2442. s, ok := v.(Session)
  2443. if !ok {
  2444. return Session{}, nil
  2445. }
  2446. return s, nil
  2447. }
  2448. func (ms *memSessStore) Del(key []byte) error {
  2449. k := hex.EncodeToString(key)
  2450. ms.Delete(k)
  2451. return nil
  2452. }
  2453. // Assert that the server only uses CipherSuites with a hash+signature that matches
  2454. // the certificate. As specified in rfc5246#section-7.4.3
  2455. func TestCipherSuiteMatchesCertificateType(t *testing.T) {
  2456. // Limit runtime in case of deadlocks
  2457. lim := test.TimeOut(time.Second * 20)
  2458. defer lim.Stop()
  2459. // Check for leaking routines
  2460. report := test.CheckRoutines(t)
  2461. defer report()
  2462. for _, test := range []struct {
  2463. Name string
  2464. cipherList []CipherSuiteID
  2465. expectedCipher CipherSuiteID
  2466. generateRSA bool
  2467. }{
  2468. {
  2469. Name: "ECDSA Certificate with RSA CipherSuite first",
  2470. cipherList: []CipherSuiteID{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  2471. expectedCipher: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  2472. },
  2473. {
  2474. Name: "RSA Certificate with ECDSA CipherSuite first",
  2475. cipherList: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  2476. expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  2477. generateRSA: true,
  2478. },
  2479. } {
  2480. test := test
  2481. t.Run(test.Name, func(t *testing.T) {
  2482. clientErr := make(chan error, 1)
  2483. client := make(chan *Conn, 1)
  2484. ca, cb := dpipe.Pipe()
  2485. go func() {
  2486. c, err := testClient(context.TODO(), ca, &Config{CipherSuites: test.cipherList}, false)
  2487. clientErr <- err
  2488. client <- c
  2489. }()
  2490. var (
  2491. priv crypto.PrivateKey
  2492. err error
  2493. )
  2494. if test.generateRSA {
  2495. if priv, err = rsa.GenerateKey(rand.Reader, 2048); err != nil {
  2496. t.Fatal(err)
  2497. }
  2498. } else {
  2499. if priv, err = ecdsa.GenerateKey(cryptoElliptic.P256(), rand.Reader); err != nil {
  2500. t.Fatal(err)
  2501. }
  2502. }
  2503. serverCert, err := selfsign.SelfSign(priv)
  2504. if err != nil {
  2505. t.Fatal(err)
  2506. }
  2507. if s, err := testServer(context.TODO(), cb, &Config{
  2508. CipherSuites: test.cipherList,
  2509. Certificates: []tls.Certificate{serverCert},
  2510. }, false); err != nil {
  2511. t.Fatal(err)
  2512. } else if err = s.Close(); err != nil {
  2513. t.Fatal(err)
  2514. }
  2515. if c, err := <-client, <-clientErr; err != nil {
  2516. t.Fatal(err)
  2517. } else if err := c.Close(); err != nil {
  2518. t.Fatal(err)
  2519. } else if c.ConnectionState().cipherSuite.ID() != test.expectedCipher {
  2520. t.Fatalf("Expected(%s) and Actual(%s) CipherSuite do not match", test.expectedCipher, c.ConnectionState().cipherSuite.ID())
  2521. }
  2522. })
  2523. }
  2524. }
  2525. // Test that we return the proper certificate if we are serving multiple ServerNames on a single Server
  2526. func TestMultipleServerCertificates(t *testing.T) {
  2527. fooCert, err := selfsign.GenerateSelfSignedWithDNS("foo")
  2528. if err != nil {
  2529. t.Fatal(err)
  2530. }
  2531. barCert, err := selfsign.GenerateSelfSignedWithDNS("bar")
  2532. if err != nil {
  2533. t.Fatal(err)
  2534. }
  2535. caPool := x509.NewCertPool()
  2536. for _, cert := range []tls.Certificate{fooCert, barCert} {
  2537. certificate, err := x509.ParseCertificate(cert.Certificate[0])
  2538. if err != nil {
  2539. t.Fatal(err)
  2540. }
  2541. caPool.AddCert(certificate)
  2542. }
  2543. for _, test := range []struct {
  2544. RequestServerName string
  2545. ExpectedDNSName string
  2546. }{
  2547. {
  2548. "foo",
  2549. "foo",
  2550. },
  2551. {
  2552. "bar",
  2553. "bar",
  2554. },
  2555. {
  2556. "invalid",
  2557. "foo",
  2558. },
  2559. } {
  2560. test := test
  2561. t.Run(test.RequestServerName, func(t *testing.T) {
  2562. clientErr := make(chan error, 2)
  2563. client := make(chan *Conn, 1)
  2564. ca, cb := dpipe.Pipe()
  2565. go func() {
  2566. c, err := testClient(context.TODO(), ca, &Config{
  2567. RootCAs: caPool,
  2568. ServerName: test.RequestServerName,
  2569. VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  2570. certificate, err := x509.ParseCertificate(rawCerts[0])
  2571. if err != nil {
  2572. return err
  2573. }
  2574. if certificate.DNSNames[0] != test.ExpectedDNSName {
  2575. return errWrongCert
  2576. }
  2577. return nil
  2578. },
  2579. }, false)
  2580. clientErr <- err
  2581. client <- c
  2582. }()
  2583. if s, err := testServer(context.TODO(), cb, &Config{Certificates: []tls.Certificate{fooCert, barCert}}, false); err != nil {
  2584. t.Fatal(err)
  2585. } else if err = s.Close(); err != nil {
  2586. t.Fatal(err)
  2587. }
  2588. if c, err := <-client, <-clientErr; err != nil {
  2589. t.Fatal(err)
  2590. } else if err := c.Close(); err != nil {
  2591. t.Fatal(err)
  2592. }
  2593. })
  2594. }
  2595. }
  2596. func TestEllipticCurveConfiguration(t *testing.T) {
  2597. // Check for leaking routines
  2598. report := test.CheckRoutines(t)
  2599. defer report()
  2600. for _, test := range []struct {
  2601. Name string
  2602. ConfigCurves []elliptic.Curve
  2603. HadnshakeCurves []elliptic.Curve
  2604. }{
  2605. {
  2606. Name: "Curve defaulting",
  2607. ConfigCurves: nil,
  2608. HadnshakeCurves: defaultCurves,
  2609. },
  2610. {
  2611. Name: "Single curve",
  2612. ConfigCurves: []elliptic.Curve{elliptic.X25519},
  2613. HadnshakeCurves: []elliptic.Curve{elliptic.X25519},
  2614. },
  2615. {
  2616. Name: "Multiple curves",
  2617. ConfigCurves: []elliptic.Curve{elliptic.P384, elliptic.X25519},
  2618. HadnshakeCurves: []elliptic.Curve{elliptic.P384, elliptic.X25519},
  2619. },
  2620. } {
  2621. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2622. defer cancel()
  2623. ca, cb := dpipe.Pipe()
  2624. type result struct {
  2625. c *Conn
  2626. err error
  2627. }
  2628. c := make(chan result)
  2629. go func() {
  2630. client, err := testClient(ctx, ca, &Config{CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, EllipticCurves: test.ConfigCurves}, true)
  2631. c <- result{client, err}
  2632. }()
  2633. server, err := testServer(ctx, cb, &Config{CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, EllipticCurves: test.ConfigCurves}, true)
  2634. if err != nil {
  2635. t.Fatalf("Server error: %v", err)
  2636. }
  2637. if len(test.ConfigCurves) == 0 && len(test.HadnshakeCurves) != len(server.fsm.cfg.ellipticCurves) {
  2638. t.Fatalf("Failed to default Elliptic curves, expected %d, got: %d", len(test.HadnshakeCurves), len(server.fsm.cfg.ellipticCurves))
  2639. }
  2640. if len(test.ConfigCurves) != 0 {
  2641. if len(test.HadnshakeCurves) != len(server.fsm.cfg.ellipticCurves) {
  2642. t.Fatalf("Failed to configure Elliptic curves, expect %d, got %d", len(test.HadnshakeCurves), len(server.fsm.cfg.ellipticCurves))
  2643. }
  2644. for i, c := range test.ConfigCurves {
  2645. if c != server.fsm.cfg.ellipticCurves[i] {
  2646. t.Fatalf("Failed to maintain Elliptic curve order, expected %s, got %s", c, server.fsm.cfg.ellipticCurves[i])
  2647. }
  2648. }
  2649. }
  2650. res := <-c
  2651. if res.err != nil {
  2652. t.Fatalf("Client error; %v", err)
  2653. }
  2654. defer func() {
  2655. err = server.Close()
  2656. if err != nil {
  2657. t.Fatal(err)
  2658. }
  2659. err = res.c.Close()
  2660. if err != nil {
  2661. t.Fatal(err)
  2662. }
  2663. }()
  2664. }
  2665. }
  2666. func TestSkipHelloVerify(t *testing.T) {
  2667. report := test.CheckRoutines(t)
  2668. defer report()
  2669. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  2670. defer cancel()
  2671. ca, cb := dpipe.Pipe()
  2672. certificate, err := selfsign.GenerateSelfSigned()
  2673. if err != nil {
  2674. t.Fatal(err)
  2675. }
  2676. gotHello := make(chan struct{})
  2677. go func() {
  2678. server, sErr := testServer(ctx, cb, &Config{
  2679. Certificates: []tls.Certificate{certificate},
  2680. LoggerFactory: logging.NewDefaultLoggerFactory(),
  2681. InsecureSkipVerifyHello: true,
  2682. }, false)
  2683. if sErr != nil {
  2684. t.Error(sErr)
  2685. return
  2686. }
  2687. buf := make([]byte, 1024)
  2688. if _, sErr = server.Read(buf); sErr != nil {
  2689. t.Error(sErr)
  2690. }
  2691. gotHello <- struct{}{}
  2692. if sErr = server.Close(); sErr != nil { //nolint:contextcheck
  2693. t.Error(sErr)
  2694. }
  2695. }()
  2696. client, err := testClient(ctx, ca, &Config{
  2697. LoggerFactory: logging.NewDefaultLoggerFactory(),
  2698. InsecureSkipVerify: true,
  2699. }, false)
  2700. if err != nil {
  2701. t.Fatal(err)
  2702. }
  2703. if _, err = client.Write([]byte("hello")); err != nil {
  2704. t.Error(err)
  2705. }
  2706. select {
  2707. case <-gotHello:
  2708. // OK
  2709. case <-time.After(time.Second * 5):
  2710. t.Error("timeout")
  2711. }
  2712. if err = client.Close(); err != nil {
  2713. t.Error(err)
  2714. }
  2715. }
  2716. type connWithCallback struct {
  2717. net.Conn
  2718. onWrite func([]byte)
  2719. }
  2720. func (c *connWithCallback) Write(b []byte) (int, error) {
  2721. if c.onWrite != nil {
  2722. c.onWrite(b)
  2723. }
  2724. return c.Conn.Write(b)
  2725. }