handshake_client_test.go 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/base64"
  11. "encoding/binary"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "math/big"
  17. "net"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "reflect"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "testing"
  26. "time"
  27. )
  28. // Note: see comment in handshake_test.go for details of how the reference
  29. // tests work.
  30. // opensslInputEvent enumerates possible inputs that can be sent to an `openssl
  31. // s_client` process.
  32. type opensslInputEvent int
  33. const (
  34. // opensslRenegotiate causes OpenSSL to request a renegotiation of the
  35. // connection.
  36. opensslRenegotiate opensslInputEvent = iota
  37. // opensslSendBanner causes OpenSSL to send the contents of
  38. // opensslSentinel on the connection.
  39. opensslSendSentinel
  40. // opensslKeyUpdate causes OpenSSL to send a key update message to the
  41. // client and request one back.
  42. opensslKeyUpdate
  43. )
  44. const opensslSentinel = "SENTINEL\n"
  45. type opensslInput chan opensslInputEvent
  46. func (i opensslInput) Read(buf []byte) (n int, err error) {
  47. for event := range i {
  48. switch event {
  49. case opensslRenegotiate:
  50. return copy(buf, []byte("R\n")), nil
  51. case opensslKeyUpdate:
  52. return copy(buf, []byte("K\n")), nil
  53. case opensslSendSentinel:
  54. return copy(buf, []byte(opensslSentinel)), nil
  55. default:
  56. panic("unknown event")
  57. }
  58. }
  59. return 0, io.EOF
  60. }
  61. // opensslOutputSink is an io.Writer that receives the stdout and stderr from an
  62. // `openssl` process and sends a value to handshakeComplete or readKeyUpdate
  63. // when certain messages are seen.
  64. type opensslOutputSink struct {
  65. handshakeComplete chan struct{}
  66. readKeyUpdate chan struct{}
  67. all []byte
  68. line []byte
  69. }
  70. func newOpensslOutputSink() *opensslOutputSink {
  71. return &opensslOutputSink{make(chan struct{}), make(chan struct{}), nil, nil}
  72. }
  73. // opensslEndOfHandshake is a message that the “openssl s_server” tool will
  74. // print when a handshake completes if run with “-state”.
  75. const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished"
  76. // opensslReadKeyUpdate is a message that the “openssl s_server” tool will
  77. // print when a KeyUpdate message is received if run with “-state”.
  78. const opensslReadKeyUpdate = "SSL_accept:TLSv1.3 read client key update"
  79. func (o *opensslOutputSink) Write(data []byte) (n int, err error) {
  80. o.line = append(o.line, data...)
  81. o.all = append(o.all, data...)
  82. for {
  83. line, next, ok := bytes.Cut(o.line, []byte("\n"))
  84. if !ok {
  85. break
  86. }
  87. if bytes.Equal([]byte(opensslEndOfHandshake), line) {
  88. o.handshakeComplete <- struct{}{}
  89. }
  90. if bytes.Equal([]byte(opensslReadKeyUpdate), line) {
  91. o.readKeyUpdate <- struct{}{}
  92. }
  93. o.line = next
  94. }
  95. return len(data), nil
  96. }
  97. func (o *opensslOutputSink) String() string {
  98. return string(o.all)
  99. }
  100. // clientTest represents a test of the TLS client handshake against a reference
  101. // implementation.
  102. type clientTest struct {
  103. // name is a freeform string identifying the test and the file in which
  104. // the expected results will be stored.
  105. name string
  106. // args, if not empty, contains a series of arguments for the
  107. // command to run for the reference server.
  108. args []string
  109. // config, if not nil, contains a custom Config to use for this test.
  110. config *Config
  111. // cert, if not empty, contains a DER-encoded certificate for the
  112. // reference server.
  113. cert []byte
  114. // key, if not nil, contains either a *rsa.PrivateKey, ed25519.PrivateKey or
  115. // *ecdsa.PrivateKey which is the private key for the reference server.
  116. key any
  117. // extensions, if not nil, contains a list of extension data to be returned
  118. // from the ServerHello. The data should be in standard TLS format with
  119. // a 2-byte uint16 type, 2-byte data length, followed by the extension data.
  120. extensions [][]byte
  121. // validate, if not nil, is a function that will be called with the
  122. // ConnectionState of the resulting connection. It returns a non-nil
  123. // error if the ConnectionState is unacceptable.
  124. validate func(ConnectionState) error
  125. // numRenegotiations is the number of times that the connection will be
  126. // renegotiated.
  127. numRenegotiations int
  128. // renegotiationExpectedToFail, if not zero, is the number of the
  129. // renegotiation attempt that is expected to fail.
  130. renegotiationExpectedToFail int
  131. // checkRenegotiationError, if not nil, is called with any error
  132. // arising from renegotiation. It can map expected errors to nil to
  133. // ignore them.
  134. checkRenegotiationError func(renegotiationNum int, err error) error
  135. // sendKeyUpdate will cause the server to send a KeyUpdate message.
  136. sendKeyUpdate bool
  137. }
  138. var serverCommand = []string{"openssl", "s_server", "-no_ticket", "-num_tickets", "0"}
  139. // connFromCommand starts the reference server process, connects to it and
  140. // returns a recordingConn for the connection. The stdin return value is an
  141. // opensslInput for the stdin of the child process. It must be closed before
  142. // Waiting for child.
  143. func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) {
  144. cert := testRSACertificate
  145. if len(test.cert) > 0 {
  146. cert = test.cert
  147. }
  148. certPath := tempFile(string(cert))
  149. defer os.Remove(certPath)
  150. var key any = testRSAPrivateKey
  151. if test.key != nil {
  152. key = test.key
  153. }
  154. derBytes, err := x509.MarshalPKCS8PrivateKey(key)
  155. if err != nil {
  156. panic(err)
  157. }
  158. var pemOut bytes.Buffer
  159. pem.Encode(&pemOut, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
  160. keyPath := tempFile(pemOut.String())
  161. defer os.Remove(keyPath)
  162. var command []string
  163. command = append(command, serverCommand...)
  164. command = append(command, test.args...)
  165. command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath)
  166. // serverPort contains the port that OpenSSL will listen on. OpenSSL
  167. // can't take "0" as an argument here so we have to pick a number and
  168. // hope that it's not in use on the machine. Since this only occurs
  169. // when -update is given and thus when there's a human watching the
  170. // test, this isn't too bad.
  171. const serverPort = 24323
  172. command = append(command, "-accept", strconv.Itoa(serverPort))
  173. if len(test.extensions) > 0 {
  174. var serverInfo bytes.Buffer
  175. for _, ext := range test.extensions {
  176. pem.Encode(&serverInfo, &pem.Block{
  177. Type: fmt.Sprintf("SERVERINFO FOR EXTENSION %d", binary.BigEndian.Uint16(ext)),
  178. Bytes: ext,
  179. })
  180. }
  181. serverInfoPath := tempFile(serverInfo.String())
  182. defer os.Remove(serverInfoPath)
  183. command = append(command, "-serverinfo", serverInfoPath)
  184. }
  185. if test.numRenegotiations > 0 || test.sendKeyUpdate {
  186. found := false
  187. for _, flag := range command[1:] {
  188. if flag == "-state" {
  189. found = true
  190. break
  191. }
  192. }
  193. if !found {
  194. panic("-state flag missing to OpenSSL, you need this if testing renegotiation or KeyUpdate")
  195. }
  196. }
  197. cmd := exec.Command(command[0], command[1:]...)
  198. stdin = opensslInput(make(chan opensslInputEvent))
  199. cmd.Stdin = stdin
  200. out := newOpensslOutputSink()
  201. cmd.Stdout = out
  202. cmd.Stderr = out
  203. if err := cmd.Start(); err != nil {
  204. return nil, nil, nil, nil, err
  205. }
  206. // OpenSSL does print an "ACCEPT" banner, but it does so *before*
  207. // opening the listening socket, so we can't use that to wait until it
  208. // has started listening. Thus we are forced to poll until we get a
  209. // connection.
  210. var tcpConn net.Conn
  211. for i := uint(0); i < 5; i++ {
  212. tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{
  213. IP: net.IPv4(127, 0, 0, 1),
  214. Port: serverPort,
  215. })
  216. if err == nil {
  217. break
  218. }
  219. time.Sleep((1 << i) * 5 * time.Millisecond)
  220. }
  221. if err != nil {
  222. close(stdin)
  223. cmd.Process.Kill()
  224. err = fmt.Errorf("error connecting to the OpenSSL server: %v (%v)\n\n%s", err, cmd.Wait(), out)
  225. return nil, nil, nil, nil, err
  226. }
  227. record := &recordingConn{
  228. Conn: tcpConn,
  229. }
  230. return record, cmd, stdin, out, nil
  231. }
  232. func (test *clientTest) dataPath() string {
  233. return filepath.Join("testdata", "Client-"+test.name)
  234. }
  235. func (test *clientTest) loadData() (flows [][]byte, err error) {
  236. in, err := os.Open(test.dataPath())
  237. if err != nil {
  238. return nil, err
  239. }
  240. defer in.Close()
  241. return parseTestData(in)
  242. }
  243. func (test *clientTest) run(t *testing.T, write bool) {
  244. var clientConn, serverConn net.Conn
  245. var recordingConn *recordingConn
  246. var childProcess *exec.Cmd
  247. var stdin opensslInput
  248. var stdout *opensslOutputSink
  249. if write {
  250. var err error
  251. recordingConn, childProcess, stdin, stdout, err = test.connFromCommand()
  252. if err != nil {
  253. t.Fatalf("Failed to start subcommand: %s", err)
  254. }
  255. clientConn = recordingConn
  256. defer func() {
  257. if t.Failed() {
  258. t.Logf("OpenSSL output:\n\n%s", stdout.all)
  259. }
  260. }()
  261. } else {
  262. clientConn, serverConn = localPipe(t)
  263. }
  264. doneChan := make(chan bool)
  265. defer func() {
  266. clientConn.Close()
  267. <-doneChan
  268. }()
  269. go func() {
  270. defer close(doneChan)
  271. config := test.config
  272. if config == nil {
  273. config = testConfig
  274. }
  275. client := Client(clientConn, config)
  276. defer client.Close()
  277. if _, err := client.Write([]byte("hello\n")); err != nil {
  278. t.Errorf("Client.Write failed: %s", err)
  279. return
  280. }
  281. for i := 1; i <= test.numRenegotiations; i++ {
  282. // The initial handshake will generate a
  283. // handshakeComplete signal which needs to be quashed.
  284. if i == 1 && write {
  285. <-stdout.handshakeComplete
  286. }
  287. // OpenSSL will try to interleave application data and
  288. // a renegotiation if we send both concurrently.
  289. // Therefore: ask OpensSSL to start a renegotiation, run
  290. // a goroutine to call client.Read and thus process the
  291. // renegotiation request, watch for OpenSSL's stdout to
  292. // indicate that the handshake is complete and,
  293. // finally, have OpenSSL write something to cause
  294. // client.Read to complete.
  295. if write {
  296. stdin <- opensslRenegotiate
  297. }
  298. signalChan := make(chan struct{})
  299. go func() {
  300. defer close(signalChan)
  301. buf := make([]byte, 256)
  302. n, err := client.Read(buf)
  303. if test.checkRenegotiationError != nil {
  304. newErr := test.checkRenegotiationError(i, err)
  305. if err != nil && newErr == nil {
  306. return
  307. }
  308. err = newErr
  309. }
  310. if err != nil {
  311. t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err)
  312. return
  313. }
  314. buf = buf[:n]
  315. if !bytes.Equal([]byte(opensslSentinel), buf) {
  316. t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
  317. }
  318. if expected := i + 1; client.handshakes != expected {
  319. t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes)
  320. }
  321. }()
  322. if write && test.renegotiationExpectedToFail != i {
  323. <-stdout.handshakeComplete
  324. stdin <- opensslSendSentinel
  325. }
  326. <-signalChan
  327. }
  328. if test.sendKeyUpdate {
  329. if write {
  330. <-stdout.handshakeComplete
  331. stdin <- opensslKeyUpdate
  332. }
  333. doneRead := make(chan struct{})
  334. go func() {
  335. defer close(doneRead)
  336. buf := make([]byte, 256)
  337. n, err := client.Read(buf)
  338. if err != nil {
  339. t.Errorf("Client.Read failed after KeyUpdate: %s", err)
  340. return
  341. }
  342. buf = buf[:n]
  343. if !bytes.Equal([]byte(opensslSentinel), buf) {
  344. t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
  345. }
  346. }()
  347. if write {
  348. // There's no real reason to wait for the client KeyUpdate to
  349. // send data with the new server keys, except that s_server
  350. // drops writes if they are sent at the wrong time.
  351. <-stdout.readKeyUpdate
  352. stdin <- opensslSendSentinel
  353. }
  354. <-doneRead
  355. if _, err := client.Write([]byte("hello again\n")); err != nil {
  356. t.Errorf("Client.Write failed: %s", err)
  357. return
  358. }
  359. }
  360. if test.validate != nil {
  361. if err := test.validate(client.ConnectionState()); err != nil {
  362. t.Errorf("validate callback returned error: %s", err)
  363. }
  364. }
  365. // If the server sent us an alert after our last flight, give it a
  366. // chance to arrive.
  367. if write && test.renegotiationExpectedToFail == 0 {
  368. if err := peekError(client); err != nil {
  369. t.Errorf("final Read returned an error: %s", err)
  370. }
  371. }
  372. }()
  373. if !write {
  374. flows, err := test.loadData()
  375. if err != nil {
  376. t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err)
  377. }
  378. for i, b := range flows {
  379. if i%2 == 1 {
  380. if *fast {
  381. serverConn.SetWriteDeadline(time.Now().Add(1 * time.Second))
  382. } else {
  383. serverConn.SetWriteDeadline(time.Now().Add(1 * time.Minute))
  384. }
  385. serverConn.Write(b)
  386. continue
  387. }
  388. bb := make([]byte, len(b))
  389. if *fast {
  390. serverConn.SetReadDeadline(time.Now().Add(1 * time.Second))
  391. } else {
  392. serverConn.SetReadDeadline(time.Now().Add(1 * time.Minute))
  393. }
  394. _, err := io.ReadFull(serverConn, bb)
  395. if err != nil {
  396. t.Fatalf("%s, flow %d: %s", test.name, i+1, err)
  397. }
  398. if !bytes.Equal(b, bb) {
  399. t.Fatalf("%s, flow %d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
  400. }
  401. }
  402. }
  403. <-doneChan
  404. if !write {
  405. serverConn.Close()
  406. }
  407. if write {
  408. path := test.dataPath()
  409. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  410. if err != nil {
  411. t.Fatalf("Failed to create output file: %s", err)
  412. }
  413. defer out.Close()
  414. recordingConn.Close()
  415. close(stdin)
  416. childProcess.Process.Kill()
  417. childProcess.Wait()
  418. if len(recordingConn.flows) < 3 {
  419. t.Fatalf("Client connection didn't work")
  420. }
  421. recordingConn.WriteTo(out)
  422. t.Logf("Wrote %s\n", path)
  423. }
  424. }
  425. // peekError does a read with a short timeout to check if the next read would
  426. // cause an error, for example if there is an alert waiting on the wire.
  427. func peekError(conn net.Conn) error {
  428. conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
  429. if n, err := conn.Read(make([]byte, 1)); n != 0 {
  430. return errors.New("unexpectedly read data")
  431. } else if err != nil {
  432. if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {
  433. return err
  434. }
  435. }
  436. return nil
  437. }
  438. func runClientTestForVersion(t *testing.T, template *clientTest, version, option string) {
  439. // Make a deep copy of the template before going parallel.
  440. test := *template
  441. if template.config != nil {
  442. test.config = template.config.Clone()
  443. }
  444. test.name = version + "-" + test.name
  445. test.args = append([]string{option}, test.args...)
  446. runTestAndUpdateIfNeeded(t, version, test.run, false)
  447. }
  448. func runClientTestTLS10(t *testing.T, template *clientTest) {
  449. runClientTestForVersion(t, template, "TLSv10", "-tls1")
  450. }
  451. func runClientTestTLS11(t *testing.T, template *clientTest) {
  452. runClientTestForVersion(t, template, "TLSv11", "-tls1_1")
  453. }
  454. func runClientTestTLS12(t *testing.T, template *clientTest) {
  455. runClientTestForVersion(t, template, "TLSv12", "-tls1_2")
  456. }
  457. func runClientTestTLS13(t *testing.T, template *clientTest) {
  458. runClientTestForVersion(t, template, "TLSv13", "-tls1_3")
  459. }
  460. func TestHandshakeClientRSARC4(t *testing.T) {
  461. test := &clientTest{
  462. name: "RSA-RC4",
  463. args: []string{"-cipher", "RC4-SHA"},
  464. }
  465. runClientTestTLS10(t, test)
  466. runClientTestTLS11(t, test)
  467. runClientTestTLS12(t, test)
  468. }
  469. func TestHandshakeClientRSAAES128GCM(t *testing.T) {
  470. test := &clientTest{
  471. name: "AES128-GCM-SHA256",
  472. args: []string{"-cipher", "AES128-GCM-SHA256"},
  473. }
  474. runClientTestTLS12(t, test)
  475. }
  476. func TestHandshakeClientRSAAES256GCM(t *testing.T) {
  477. test := &clientTest{
  478. name: "AES256-GCM-SHA384",
  479. args: []string{"-cipher", "AES256-GCM-SHA384"},
  480. }
  481. runClientTestTLS12(t, test)
  482. }
  483. func TestHandshakeClientECDHERSAAES(t *testing.T) {
  484. test := &clientTest{
  485. name: "ECDHE-RSA-AES",
  486. args: []string{"-cipher", "ECDHE-RSA-AES128-SHA"},
  487. }
  488. runClientTestTLS10(t, test)
  489. runClientTestTLS11(t, test)
  490. runClientTestTLS12(t, test)
  491. }
  492. func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
  493. test := &clientTest{
  494. name: "ECDHE-ECDSA-AES",
  495. args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA"},
  496. cert: testECDSACertificate,
  497. key: testECDSAPrivateKey,
  498. }
  499. runClientTestTLS10(t, test)
  500. runClientTestTLS11(t, test)
  501. runClientTestTLS12(t, test)
  502. }
  503. func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
  504. test := &clientTest{
  505. name: "ECDHE-ECDSA-AES-GCM",
  506. args: []string{"-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
  507. cert: testECDSACertificate,
  508. key: testECDSAPrivateKey,
  509. }
  510. runClientTestTLS12(t, test)
  511. }
  512. func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
  513. test := &clientTest{
  514. name: "ECDHE-ECDSA-AES256-GCM-SHA384",
  515. args: []string{"-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
  516. cert: testECDSACertificate,
  517. key: testECDSAPrivateKey,
  518. }
  519. runClientTestTLS12(t, test)
  520. }
  521. func TestHandshakeClientAES128CBCSHA256(t *testing.T) {
  522. test := &clientTest{
  523. name: "AES128-SHA256",
  524. args: []string{"-cipher", "AES128-SHA256"},
  525. }
  526. runClientTestTLS12(t, test)
  527. }
  528. func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) {
  529. test := &clientTest{
  530. name: "ECDHE-RSA-AES128-SHA256",
  531. args: []string{"-cipher", "ECDHE-RSA-AES128-SHA256"},
  532. }
  533. runClientTestTLS12(t, test)
  534. }
  535. func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) {
  536. test := &clientTest{
  537. name: "ECDHE-ECDSA-AES128-SHA256",
  538. args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA256"},
  539. cert: testECDSACertificate,
  540. key: testECDSAPrivateKey,
  541. }
  542. runClientTestTLS12(t, test)
  543. }
  544. func TestHandshakeClientX25519(t *testing.T) {
  545. config := testConfig.Clone()
  546. config.CurvePreferences = []CurveID{X25519}
  547. test := &clientTest{
  548. name: "X25519-ECDHE",
  549. args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "X25519"},
  550. config: config,
  551. }
  552. runClientTestTLS12(t, test)
  553. runClientTestTLS13(t, test)
  554. }
  555. func TestHandshakeClientP256(t *testing.T) {
  556. config := testConfig.Clone()
  557. config.CurvePreferences = []CurveID{CurveP256}
  558. test := &clientTest{
  559. name: "P256-ECDHE",
  560. args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
  561. config: config,
  562. }
  563. runClientTestTLS12(t, test)
  564. runClientTestTLS13(t, test)
  565. }
  566. func TestHandshakeClientHelloRetryRequest(t *testing.T) {
  567. config := testConfig.Clone()
  568. config.CurvePreferences = []CurveID{X25519, CurveP256}
  569. test := &clientTest{
  570. name: "HelloRetryRequest",
  571. args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
  572. config: config,
  573. }
  574. runClientTestTLS13(t, test)
  575. }
  576. func TestHandshakeClientECDHERSAChaCha20(t *testing.T) {
  577. config := testConfig.Clone()
  578. config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305}
  579. test := &clientTest{
  580. name: "ECDHE-RSA-CHACHA20-POLY1305",
  581. args: []string{"-cipher", "ECDHE-RSA-CHACHA20-POLY1305"},
  582. config: config,
  583. }
  584. runClientTestTLS12(t, test)
  585. }
  586. func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) {
  587. config := testConfig.Clone()
  588. config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305}
  589. test := &clientTest{
  590. name: "ECDHE-ECDSA-CHACHA20-POLY1305",
  591. args: []string{"-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"},
  592. config: config,
  593. cert: testECDSACertificate,
  594. key: testECDSAPrivateKey,
  595. }
  596. runClientTestTLS12(t, test)
  597. }
  598. func TestHandshakeClientAES128SHA256(t *testing.T) {
  599. test := &clientTest{
  600. name: "AES128-SHA256",
  601. args: []string{"-ciphersuites", "TLS_AES_128_GCM_SHA256"},
  602. }
  603. runClientTestTLS13(t, test)
  604. }
  605. func TestHandshakeClientAES256SHA384(t *testing.T) {
  606. test := &clientTest{
  607. name: "AES256-SHA384",
  608. args: []string{"-ciphersuites", "TLS_AES_256_GCM_SHA384"},
  609. }
  610. runClientTestTLS13(t, test)
  611. }
  612. func TestHandshakeClientCHACHA20SHA256(t *testing.T) {
  613. test := &clientTest{
  614. name: "CHACHA20-SHA256",
  615. args: []string{"-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
  616. }
  617. runClientTestTLS13(t, test)
  618. }
  619. func TestHandshakeClientECDSATLS13(t *testing.T) {
  620. test := &clientTest{
  621. name: "ECDSA",
  622. cert: testECDSACertificate,
  623. key: testECDSAPrivateKey,
  624. }
  625. runClientTestTLS13(t, test)
  626. }
  627. func TestHandshakeClientEd25519(t *testing.T) {
  628. test := &clientTest{
  629. name: "Ed25519",
  630. cert: testEd25519Certificate,
  631. key: testEd25519PrivateKey,
  632. }
  633. runClientTestTLS12(t, test)
  634. runClientTestTLS13(t, test)
  635. config := testConfig.Clone()
  636. cert, _ := X509KeyPair([]byte(clientEd25519CertificatePEM), []byte(clientEd25519KeyPEM))
  637. config.Certificates = []Certificate{cert}
  638. test = &clientTest{
  639. name: "ClientCert-Ed25519",
  640. args: []string{"-Verify", "1"},
  641. config: config,
  642. }
  643. runClientTestTLS12(t, test)
  644. runClientTestTLS13(t, test)
  645. }
  646. func TestHandshakeClientCertRSA(t *testing.T) {
  647. config := testConfig.Clone()
  648. cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
  649. config.Certificates = []Certificate{cert}
  650. test := &clientTest{
  651. name: "ClientCert-RSA-RSA",
  652. args: []string{"-cipher", "AES128", "-Verify", "1"},
  653. config: config,
  654. }
  655. runClientTestTLS10(t, test)
  656. runClientTestTLS12(t, test)
  657. test = &clientTest{
  658. name: "ClientCert-RSA-ECDSA",
  659. args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"},
  660. config: config,
  661. cert: testECDSACertificate,
  662. key: testECDSAPrivateKey,
  663. }
  664. runClientTestTLS10(t, test)
  665. runClientTestTLS12(t, test)
  666. runClientTestTLS13(t, test)
  667. test = &clientTest{
  668. name: "ClientCert-RSA-AES256-GCM-SHA384",
  669. args: []string{"-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-Verify", "1"},
  670. config: config,
  671. cert: testRSACertificate,
  672. key: testRSAPrivateKey,
  673. }
  674. runClientTestTLS12(t, test)
  675. }
  676. func TestHandshakeClientCertECDSA(t *testing.T) {
  677. config := testConfig.Clone()
  678. cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
  679. config.Certificates = []Certificate{cert}
  680. test := &clientTest{
  681. name: "ClientCert-ECDSA-RSA",
  682. args: []string{"-cipher", "AES128", "-Verify", "1"},
  683. config: config,
  684. }
  685. runClientTestTLS10(t, test)
  686. runClientTestTLS12(t, test)
  687. runClientTestTLS13(t, test)
  688. test = &clientTest{
  689. name: "ClientCert-ECDSA-ECDSA",
  690. args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"},
  691. config: config,
  692. cert: testECDSACertificate,
  693. key: testECDSAPrivateKey,
  694. }
  695. runClientTestTLS10(t, test)
  696. runClientTestTLS12(t, test)
  697. }
  698. // TestHandshakeClientCertRSAPSS tests rsa_pss_rsae_sha256 signatures from both
  699. // client and server certificates. It also serves from both sides a certificate
  700. // signed itself with RSA-PSS, mostly to check that crypto/x509 chain validation
  701. // works.
  702. func TestHandshakeClientCertRSAPSS(t *testing.T) {
  703. cert, err := x509.ParseCertificate(testRSAPSSCertificate)
  704. if err != nil {
  705. panic(err)
  706. }
  707. rootCAs := x509.NewCertPool()
  708. rootCAs.AddCert(cert)
  709. config := testConfig.Clone()
  710. // Use GetClientCertificate to bypass the client certificate selection logic.
  711. config.GetClientCertificate = func(*CertificateRequestInfo) (*Certificate, error) {
  712. return &Certificate{
  713. Certificate: [][]byte{testRSAPSSCertificate},
  714. PrivateKey: testRSAPrivateKey,
  715. }, nil
  716. }
  717. config.RootCAs = rootCAs
  718. test := &clientTest{
  719. name: "ClientCert-RSA-RSAPSS",
  720. args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs",
  721. "rsa_pss_rsae_sha256", "-sigalgs", "rsa_pss_rsae_sha256"},
  722. config: config,
  723. cert: testRSAPSSCertificate,
  724. key: testRSAPrivateKey,
  725. }
  726. runClientTestTLS12(t, test)
  727. runClientTestTLS13(t, test)
  728. }
  729. func TestHandshakeClientCertRSAPKCS1v15(t *testing.T) {
  730. config := testConfig.Clone()
  731. cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
  732. config.Certificates = []Certificate{cert}
  733. test := &clientTest{
  734. name: "ClientCert-RSA-RSAPKCS1v15",
  735. args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs",
  736. "rsa_pkcs1_sha256", "-sigalgs", "rsa_pkcs1_sha256"},
  737. config: config,
  738. }
  739. runClientTestTLS12(t, test)
  740. }
  741. func TestClientKeyUpdate(t *testing.T) {
  742. test := &clientTest{
  743. name: "KeyUpdate",
  744. args: []string{"-state"},
  745. sendKeyUpdate: true,
  746. }
  747. runClientTestTLS13(t, test)
  748. }
  749. func TestResumption(t *testing.T) {
  750. t.Run("TLSv12", func(t *testing.T) { testResumption(t, VersionTLS12) })
  751. t.Run("TLSv13", func(t *testing.T) { testResumption(t, VersionTLS13) })
  752. }
  753. func testResumption(t *testing.T, version uint16) {
  754. if testing.Short() {
  755. t.Skip("skipping in -short mode")
  756. }
  757. serverConfig := &Config{
  758. MaxVersion: version,
  759. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  760. Certificates: testConfig.Certificates,
  761. }
  762. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  763. if err != nil {
  764. panic(err)
  765. }
  766. rootCAs := x509.NewCertPool()
  767. rootCAs.AddCert(issuer)
  768. clientConfig := &Config{
  769. MaxVersion: version,
  770. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  771. ClientSessionCache: NewLRUClientSessionCache(32),
  772. RootCAs: rootCAs,
  773. ServerName: "example.golang",
  774. }
  775. testResumeState := func(test string, didResume bool) {
  776. _, hs, err := testHandshake(t, clientConfig, serverConfig)
  777. if err != nil {
  778. t.Fatalf("%s: handshake failed: %s", test, err)
  779. }
  780. if hs.DidResume != didResume {
  781. t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
  782. }
  783. if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
  784. t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
  785. }
  786. if got, want := hs.ServerName, clientConfig.ServerName; got != want {
  787. t.Errorf("%s: server name %s, want %s", test, got, want)
  788. }
  789. }
  790. getTicket := func() []byte {
  791. return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket
  792. }
  793. deleteTicket := func() {
  794. ticketKey := clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).sessionKey
  795. clientConfig.ClientSessionCache.Put(ticketKey, nil)
  796. }
  797. corruptTicket := func() {
  798. clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.masterSecret[0] ^= 0xff
  799. }
  800. randomKey := func() [32]byte {
  801. var k [32]byte
  802. if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
  803. t.Fatalf("Failed to read new SessionTicketKey: %s", err)
  804. }
  805. return k
  806. }
  807. testResumeState("Handshake", false)
  808. ticket := getTicket()
  809. testResumeState("Resume", true)
  810. if !bytes.Equal(ticket, getTicket()) && version != VersionTLS13 {
  811. t.Fatal("first ticket doesn't match ticket after resumption")
  812. }
  813. if bytes.Equal(ticket, getTicket()) && version == VersionTLS13 {
  814. t.Fatal("ticket didn't change after resumption")
  815. }
  816. // An old session ticket can resume, but the server will provide a ticket encrypted with a fresh key.
  817. serverConfig.Time = func() time.Time { return time.Now().Add(24*time.Hour + time.Minute) }
  818. testResumeState("ResumeWithOldTicket", true)
  819. if bytes.Equal(ticket[:ticketKeyNameLen], getTicket()[:ticketKeyNameLen]) {
  820. t.Fatal("old first ticket matches the fresh one")
  821. }
  822. // Now the session tickey key is expired, so a full handshake should occur.
  823. serverConfig.Time = func() time.Time { return time.Now().Add(24*8*time.Hour + time.Minute) }
  824. testResumeState("ResumeWithExpiredTicket", false)
  825. if bytes.Equal(ticket, getTicket()) {
  826. t.Fatal("expired first ticket matches the fresh one")
  827. }
  828. serverConfig.Time = func() time.Time { return time.Now() } // reset the time back
  829. key1 := randomKey()
  830. serverConfig.SetSessionTicketKeys([][32]byte{key1})
  831. testResumeState("InvalidSessionTicketKey", false)
  832. testResumeState("ResumeAfterInvalidSessionTicketKey", true)
  833. key2 := randomKey()
  834. serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
  835. ticket = getTicket()
  836. testResumeState("KeyChange", true)
  837. if bytes.Equal(ticket, getTicket()) {
  838. t.Fatal("new ticket wasn't included while resuming")
  839. }
  840. testResumeState("KeyChangeFinish", true)
  841. // Age the session ticket a bit, but not yet expired.
  842. serverConfig.Time = func() time.Time { return time.Now().Add(24*time.Hour + time.Minute) }
  843. testResumeState("OldSessionTicket", true)
  844. ticket = getTicket()
  845. // Expire the session ticket, which would force a full handshake.
  846. serverConfig.Time = func() time.Time { return time.Now().Add(24*8*time.Hour + time.Minute) }
  847. testResumeState("ExpiredSessionTicket", false)
  848. if bytes.Equal(ticket, getTicket()) {
  849. t.Fatal("new ticket wasn't provided after old ticket expired")
  850. }
  851. // Age the session ticket a bit at a time, but don't expire it.
  852. d := 0 * time.Hour
  853. for i := 0; i < 13; i++ {
  854. d += 12 * time.Hour
  855. serverConfig.Time = func() time.Time { return time.Now().Add(d) }
  856. testResumeState("OldSessionTicket", true)
  857. }
  858. // Expire it (now a little more than 7 days) and make sure a full
  859. // handshake occurs for TLS 1.2. Resumption should still occur for
  860. // TLS 1.3 since the client should be using a fresh ticket sent over
  861. // by the server.
  862. d += 12 * time.Hour
  863. serverConfig.Time = func() time.Time { return time.Now().Add(d) }
  864. if version == VersionTLS13 {
  865. testResumeState("ExpiredSessionTicket", true)
  866. } else {
  867. testResumeState("ExpiredSessionTicket", false)
  868. }
  869. if bytes.Equal(ticket, getTicket()) {
  870. t.Fatal("new ticket wasn't provided after old ticket expired")
  871. }
  872. // Reset serverConfig to ensure that calling SetSessionTicketKeys
  873. // before the serverConfig is used works.
  874. serverConfig = &Config{
  875. MaxVersion: version,
  876. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  877. Certificates: testConfig.Certificates,
  878. }
  879. serverConfig.SetSessionTicketKeys([][32]byte{key2})
  880. testResumeState("FreshConfig", true)
  881. // In TLS 1.3, cross-cipher suite resumption is allowed as long as the KDF
  882. // hash matches. Also, Config.CipherSuites does not apply to TLS 1.3.
  883. if version != VersionTLS13 {
  884. clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
  885. testResumeState("DifferentCipherSuite", false)
  886. testResumeState("DifferentCipherSuiteRecovers", true)
  887. }
  888. deleteTicket()
  889. testResumeState("WithoutSessionTicket", false)
  890. // Session resumption should work when using client certificates
  891. deleteTicket()
  892. serverConfig.ClientCAs = rootCAs
  893. serverConfig.ClientAuth = RequireAndVerifyClientCert
  894. clientConfig.Certificates = serverConfig.Certificates
  895. testResumeState("InitialHandshake", false)
  896. testResumeState("WithClientCertificates", true)
  897. serverConfig.ClientAuth = NoClientCert
  898. // Tickets should be removed from the session cache on TLS handshake
  899. // failure, and the client should recover from a corrupted PSK
  900. testResumeState("FetchTicketToCorrupt", false)
  901. corruptTicket()
  902. _, _, err = testHandshake(t, clientConfig, serverConfig)
  903. if err == nil {
  904. t.Fatalf("handshake did not fail with a corrupted client secret")
  905. }
  906. testResumeState("AfterHandshakeFailure", false)
  907. clientConfig.ClientSessionCache = nil
  908. testResumeState("WithoutSessionCache", false)
  909. }
  910. func TestLRUClientSessionCache(t *testing.T) {
  911. // Initialize cache of capacity 4.
  912. cache := NewLRUClientSessionCache(4)
  913. cs := make([]ClientSessionState, 6)
  914. keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  915. // Add 4 entries to the cache and look them up.
  916. for i := 0; i < 4; i++ {
  917. cache.Put(keys[i], &cs[i])
  918. }
  919. for i := 0; i < 4; i++ {
  920. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  921. t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  922. }
  923. }
  924. // Add 2 more entries to the cache. First 2 should be evicted.
  925. for i := 4; i < 6; i++ {
  926. cache.Put(keys[i], &cs[i])
  927. }
  928. for i := 0; i < 2; i++ {
  929. if s, ok := cache.Get(keys[i]); ok || s != nil {
  930. t.Fatalf("session cache should have evicted key: %s", keys[i])
  931. }
  932. }
  933. // Touch entry 2. LRU should evict 3 next.
  934. cache.Get(keys[2])
  935. cache.Put(keys[0], &cs[0])
  936. if s, ok := cache.Get(keys[3]); ok || s != nil {
  937. t.Fatalf("session cache should have evicted key 3")
  938. }
  939. // Update entry 0 in place.
  940. cache.Put(keys[0], &cs[3])
  941. if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  942. t.Fatalf("session cache failed update for key 0")
  943. }
  944. // Calling Put with a nil entry deletes the key.
  945. cache.Put(keys[0], nil)
  946. if _, ok := cache.Get(keys[0]); ok {
  947. t.Fatalf("session cache failed to delete key 0")
  948. }
  949. // Delete entry 2. LRU should keep 4 and 5
  950. cache.Put(keys[2], nil)
  951. if _, ok := cache.Get(keys[2]); ok {
  952. t.Fatalf("session cache failed to delete key 4")
  953. }
  954. for i := 4; i < 6; i++ {
  955. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  956. t.Fatalf("session cache should not have deleted key: %s", keys[i])
  957. }
  958. }
  959. }
  960. func TestKeyLogTLS12(t *testing.T) {
  961. var serverBuf, clientBuf bytes.Buffer
  962. clientConfig := testConfig.Clone()
  963. clientConfig.KeyLogWriter = &clientBuf
  964. clientConfig.MaxVersion = VersionTLS12
  965. serverConfig := testConfig.Clone()
  966. serverConfig.KeyLogWriter = &serverBuf
  967. serverConfig.MaxVersion = VersionTLS12
  968. c, s := localPipe(t)
  969. done := make(chan bool)
  970. go func() {
  971. defer close(done)
  972. if err := Server(s, serverConfig).Handshake(); err != nil {
  973. t.Errorf("server: %s", err)
  974. return
  975. }
  976. s.Close()
  977. }()
  978. if err := Client(c, clientConfig).Handshake(); err != nil {
  979. t.Fatalf("client: %s", err)
  980. }
  981. c.Close()
  982. <-done
  983. checkKeylogLine := func(side, loggedLine string) {
  984. if len(loggedLine) == 0 {
  985. t.Fatalf("%s: no keylog line was produced", side)
  986. }
  987. const expectedLen = 13 /* "CLIENT_RANDOM" */ +
  988. 1 /* space */ +
  989. 32*2 /* hex client nonce */ +
  990. 1 /* space */ +
  991. 48*2 /* hex master secret */ +
  992. 1 /* new line */
  993. if len(loggedLine) != expectedLen {
  994. t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine)
  995. }
  996. if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") {
  997. t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine)
  998. }
  999. }
  1000. checkKeylogLine("client", clientBuf.String())
  1001. checkKeylogLine("server", serverBuf.String())
  1002. }
  1003. func TestKeyLogTLS13(t *testing.T) {
  1004. var serverBuf, clientBuf bytes.Buffer
  1005. clientConfig := testConfig.Clone()
  1006. clientConfig.KeyLogWriter = &clientBuf
  1007. serverConfig := testConfig.Clone()
  1008. serverConfig.KeyLogWriter = &serverBuf
  1009. c, s := localPipe(t)
  1010. done := make(chan bool)
  1011. go func() {
  1012. defer close(done)
  1013. if err := Server(s, serverConfig).Handshake(); err != nil {
  1014. t.Errorf("server: %s", err)
  1015. return
  1016. }
  1017. s.Close()
  1018. }()
  1019. if err := Client(c, clientConfig).Handshake(); err != nil {
  1020. t.Fatalf("client: %s", err)
  1021. }
  1022. c.Close()
  1023. <-done
  1024. checkKeylogLines := func(side, loggedLines string) {
  1025. loggedLines = strings.TrimSpace(loggedLines)
  1026. lines := strings.Split(loggedLines, "\n")
  1027. if len(lines) != 4 {
  1028. t.Errorf("Expected the %s to log 4 lines, got %d", side, len(lines))
  1029. }
  1030. }
  1031. checkKeylogLines("client", clientBuf.String())
  1032. checkKeylogLines("server", serverBuf.String())
  1033. }
  1034. func TestHandshakeClientALPNMatch(t *testing.T) {
  1035. config := testConfig.Clone()
  1036. config.NextProtos = []string{"proto2", "proto1"}
  1037. test := &clientTest{
  1038. name: "ALPN",
  1039. // Note that this needs OpenSSL 1.0.2 because that is the first
  1040. // version that supports the -alpn flag.
  1041. args: []string{"-alpn", "proto1,proto2"},
  1042. config: config,
  1043. validate: func(state ConnectionState) error {
  1044. // The server's preferences should override the client.
  1045. if state.NegotiatedProtocol != "proto1" {
  1046. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  1047. }
  1048. return nil
  1049. },
  1050. }
  1051. runClientTestTLS12(t, test)
  1052. runClientTestTLS13(t, test)
  1053. }
  1054. func TestServerSelectingUnconfiguredApplicationProtocol(t *testing.T) {
  1055. // This checks that the server can't select an application protocol that the
  1056. // client didn't offer.
  1057. c, s := localPipe(t)
  1058. errChan := make(chan error, 1)
  1059. go func() {
  1060. client := Client(c, &Config{
  1061. ServerName: "foo",
  1062. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1063. NextProtos: []string{"http", "something-else"},
  1064. })
  1065. errChan <- client.Handshake()
  1066. }()
  1067. var header [5]byte
  1068. if _, err := io.ReadFull(s, header[:]); err != nil {
  1069. t.Fatal(err)
  1070. }
  1071. recordLen := int(header[3])<<8 | int(header[4])
  1072. record := make([]byte, recordLen)
  1073. if _, err := io.ReadFull(s, record); err != nil {
  1074. t.Fatal(err)
  1075. }
  1076. serverHello := &serverHelloMsg{
  1077. vers: VersionTLS12,
  1078. random: make([]byte, 32),
  1079. cipherSuite: TLS_RSA_WITH_AES_128_GCM_SHA256,
  1080. alpnProtocol: "how-about-this",
  1081. }
  1082. serverHelloBytes := serverHello.marshal()
  1083. s.Write([]byte{
  1084. byte(recordTypeHandshake),
  1085. byte(VersionTLS12 >> 8),
  1086. byte(VersionTLS12 & 0xff),
  1087. byte(len(serverHelloBytes) >> 8),
  1088. byte(len(serverHelloBytes)),
  1089. })
  1090. s.Write(serverHelloBytes)
  1091. s.Close()
  1092. if err := <-errChan; !strings.Contains(err.Error(), "server selected unadvertised ALPN protocol") {
  1093. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  1094. }
  1095. }
  1096. // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  1097. const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  1098. func TestHandshakClientSCTs(t *testing.T) {
  1099. config := testConfig.Clone()
  1100. scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  1101. if err != nil {
  1102. t.Fatal(err)
  1103. }
  1104. // Note that this needs OpenSSL 1.0.2 because that is the first
  1105. // version that supports the -serverinfo flag.
  1106. test := &clientTest{
  1107. name: "SCT",
  1108. config: config,
  1109. extensions: [][]byte{scts},
  1110. validate: func(state ConnectionState) error {
  1111. expectedSCTs := [][]byte{
  1112. scts[8:125],
  1113. scts[127:245],
  1114. scts[247:],
  1115. }
  1116. if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  1117. return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  1118. }
  1119. for i, expected := range expectedSCTs {
  1120. if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  1121. return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  1122. }
  1123. }
  1124. return nil
  1125. },
  1126. }
  1127. runClientTestTLS12(t, test)
  1128. // TLS 1.3 moved SCTs to the Certificate extensions and -serverinfo only
  1129. // supports ServerHello extensions.
  1130. }
  1131. func TestRenegotiationRejected(t *testing.T) {
  1132. config := testConfig.Clone()
  1133. test := &clientTest{
  1134. name: "RenegotiationRejected",
  1135. args: []string{"-state"},
  1136. config: config,
  1137. numRenegotiations: 1,
  1138. renegotiationExpectedToFail: 1,
  1139. checkRenegotiationError: func(renegotiationNum int, err error) error {
  1140. if err == nil {
  1141. return errors.New("expected error from renegotiation but got nil")
  1142. }
  1143. if !strings.Contains(err.Error(), "no renegotiation") {
  1144. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  1145. }
  1146. return nil
  1147. },
  1148. }
  1149. runClientTestTLS12(t, test)
  1150. }
  1151. func TestRenegotiateOnce(t *testing.T) {
  1152. config := testConfig.Clone()
  1153. config.Renegotiation = RenegotiateOnceAsClient
  1154. test := &clientTest{
  1155. name: "RenegotiateOnce",
  1156. args: []string{"-state"},
  1157. config: config,
  1158. numRenegotiations: 1,
  1159. }
  1160. runClientTestTLS12(t, test)
  1161. }
  1162. func TestRenegotiateTwice(t *testing.T) {
  1163. config := testConfig.Clone()
  1164. config.Renegotiation = RenegotiateFreelyAsClient
  1165. test := &clientTest{
  1166. name: "RenegotiateTwice",
  1167. args: []string{"-state"},
  1168. config: config,
  1169. numRenegotiations: 2,
  1170. }
  1171. runClientTestTLS12(t, test)
  1172. }
  1173. func TestRenegotiateTwiceRejected(t *testing.T) {
  1174. config := testConfig.Clone()
  1175. config.Renegotiation = RenegotiateOnceAsClient
  1176. test := &clientTest{
  1177. name: "RenegotiateTwiceRejected",
  1178. args: []string{"-state"},
  1179. config: config,
  1180. numRenegotiations: 2,
  1181. renegotiationExpectedToFail: 2,
  1182. checkRenegotiationError: func(renegotiationNum int, err error) error {
  1183. if renegotiationNum == 1 {
  1184. return err
  1185. }
  1186. if err == nil {
  1187. return errors.New("expected error from renegotiation but got nil")
  1188. }
  1189. if !strings.Contains(err.Error(), "no renegotiation") {
  1190. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  1191. }
  1192. return nil
  1193. },
  1194. }
  1195. runClientTestTLS12(t, test)
  1196. }
  1197. func TestHandshakeClientExportKeyingMaterial(t *testing.T) {
  1198. test := &clientTest{
  1199. name: "ExportKeyingMaterial",
  1200. config: testConfig.Clone(),
  1201. validate: func(state ConnectionState) error {
  1202. if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
  1203. return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
  1204. } else if len(km) != 42 {
  1205. return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
  1206. }
  1207. return nil
  1208. },
  1209. }
  1210. runClientTestTLS10(t, test)
  1211. runClientTestTLS12(t, test)
  1212. runClientTestTLS13(t, test)
  1213. }
  1214. var hostnameInSNITests = []struct {
  1215. in, out string
  1216. }{
  1217. // Opaque string
  1218. {"", ""},
  1219. {"localhost", "localhost"},
  1220. {"foo, bar, baz and qux", "foo, bar, baz and qux"},
  1221. // DNS hostname
  1222. {"golang.org", "golang.org"},
  1223. {"golang.org.", "golang.org"},
  1224. // Literal IPv4 address
  1225. {"1.2.3.4", ""},
  1226. // Literal IPv6 address
  1227. {"::1", ""},
  1228. {"::1%lo0", ""}, // with zone identifier
  1229. {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal
  1230. {"[::1%lo0]", ""},
  1231. }
  1232. func TestHostnameInSNI(t *testing.T) {
  1233. for _, tt := range hostnameInSNITests {
  1234. c, s := localPipe(t)
  1235. go func(host string) {
  1236. Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  1237. }(tt.in)
  1238. var header [5]byte
  1239. if _, err := io.ReadFull(s, header[:]); err != nil {
  1240. t.Fatal(err)
  1241. }
  1242. recordLen := int(header[3])<<8 | int(header[4])
  1243. record := make([]byte, recordLen)
  1244. if _, err := io.ReadFull(s, record[:]); err != nil {
  1245. t.Fatal(err)
  1246. }
  1247. c.Close()
  1248. s.Close()
  1249. var m clientHelloMsg
  1250. if !m.unmarshal(record) {
  1251. t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  1252. continue
  1253. }
  1254. if tt.in != tt.out && m.serverName == tt.in {
  1255. t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  1256. }
  1257. if m.serverName != tt.out {
  1258. t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  1259. }
  1260. }
  1261. }
  1262. func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  1263. // This checks that the server can't select a cipher suite that the
  1264. // client didn't offer. See #13174.
  1265. c, s := localPipe(t)
  1266. errChan := make(chan error, 1)
  1267. go func() {
  1268. client := Client(c, &Config{
  1269. ServerName: "foo",
  1270. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1271. })
  1272. errChan <- client.Handshake()
  1273. }()
  1274. var header [5]byte
  1275. if _, err := io.ReadFull(s, header[:]); err != nil {
  1276. t.Fatal(err)
  1277. }
  1278. recordLen := int(header[3])<<8 | int(header[4])
  1279. record := make([]byte, recordLen)
  1280. if _, err := io.ReadFull(s, record); err != nil {
  1281. t.Fatal(err)
  1282. }
  1283. // Create a ServerHello that selects a different cipher suite than the
  1284. // sole one that the client offered.
  1285. serverHello := &serverHelloMsg{
  1286. vers: VersionTLS12,
  1287. random: make([]byte, 32),
  1288. cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  1289. }
  1290. serverHelloBytes := serverHello.marshal()
  1291. s.Write([]byte{
  1292. byte(recordTypeHandshake),
  1293. byte(VersionTLS12 >> 8),
  1294. byte(VersionTLS12 & 0xff),
  1295. byte(len(serverHelloBytes) >> 8),
  1296. byte(len(serverHelloBytes)),
  1297. })
  1298. s.Write(serverHelloBytes)
  1299. s.Close()
  1300. if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  1301. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  1302. }
  1303. }
  1304. func TestVerifyConnection(t *testing.T) {
  1305. t.Run("TLSv12", func(t *testing.T) { testVerifyConnection(t, VersionTLS12) })
  1306. t.Run("TLSv13", func(t *testing.T) { testVerifyConnection(t, VersionTLS13) })
  1307. }
  1308. func testVerifyConnection(t *testing.T, version uint16) {
  1309. checkFields := func(c ConnectionState, called *int, errorType string) error {
  1310. if c.Version != version {
  1311. return fmt.Errorf("%s: got Version %v, want %v", errorType, c.Version, version)
  1312. }
  1313. if c.HandshakeComplete {
  1314. return fmt.Errorf("%s: got HandshakeComplete, want false", errorType)
  1315. }
  1316. if c.ServerName != "example.golang" {
  1317. return fmt.Errorf("%s: got ServerName %s, want %s", errorType, c.ServerName, "example.golang")
  1318. }
  1319. if c.NegotiatedProtocol != "protocol1" {
  1320. return fmt.Errorf("%s: got NegotiatedProtocol %s, want %s", errorType, c.NegotiatedProtocol, "protocol1")
  1321. }
  1322. if c.CipherSuite == 0 {
  1323. return fmt.Errorf("%s: got CipherSuite 0, want non-zero", errorType)
  1324. }
  1325. wantDidResume := false
  1326. if *called == 2 { // if this is the second time, then it should be a resumption
  1327. wantDidResume = true
  1328. }
  1329. if c.DidResume != wantDidResume {
  1330. return fmt.Errorf("%s: got DidResume %t, want %t", errorType, c.DidResume, wantDidResume)
  1331. }
  1332. return nil
  1333. }
  1334. tests := []struct {
  1335. name string
  1336. configureServer func(*Config, *int)
  1337. configureClient func(*Config, *int)
  1338. }{
  1339. {
  1340. name: "RequireAndVerifyClientCert",
  1341. configureServer: func(config *Config, called *int) {
  1342. config.ClientAuth = RequireAndVerifyClientCert
  1343. config.VerifyConnection = func(c ConnectionState) error {
  1344. *called++
  1345. if l := len(c.PeerCertificates); l != 1 {
  1346. return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l)
  1347. }
  1348. if len(c.VerifiedChains) == 0 {
  1349. return fmt.Errorf("server: got len(VerifiedChains) = 0, wanted non-zero")
  1350. }
  1351. return checkFields(c, called, "server")
  1352. }
  1353. },
  1354. configureClient: func(config *Config, called *int) {
  1355. config.VerifyConnection = func(c ConnectionState) error {
  1356. *called++
  1357. if l := len(c.PeerCertificates); l != 1 {
  1358. return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
  1359. }
  1360. if len(c.VerifiedChains) == 0 {
  1361. return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero")
  1362. }
  1363. if c.DidResume {
  1364. return nil
  1365. // The SCTs and OCSP Response are dropped on resumption.
  1366. // See http://golang.org/issue/39075.
  1367. }
  1368. if len(c.OCSPResponse) == 0 {
  1369. return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
  1370. }
  1371. if len(c.SignedCertificateTimestamps) == 0 {
  1372. return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
  1373. }
  1374. return checkFields(c, called, "client")
  1375. }
  1376. },
  1377. },
  1378. {
  1379. name: "InsecureSkipVerify",
  1380. configureServer: func(config *Config, called *int) {
  1381. config.ClientAuth = RequireAnyClientCert
  1382. config.InsecureSkipVerify = true
  1383. config.VerifyConnection = func(c ConnectionState) error {
  1384. *called++
  1385. if l := len(c.PeerCertificates); l != 1 {
  1386. return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l)
  1387. }
  1388. if c.VerifiedChains != nil {
  1389. return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains)
  1390. }
  1391. return checkFields(c, called, "server")
  1392. }
  1393. },
  1394. configureClient: func(config *Config, called *int) {
  1395. config.InsecureSkipVerify = true
  1396. config.VerifyConnection = func(c ConnectionState) error {
  1397. *called++
  1398. if l := len(c.PeerCertificates); l != 1 {
  1399. return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
  1400. }
  1401. if c.VerifiedChains != nil {
  1402. return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains)
  1403. }
  1404. if c.DidResume {
  1405. return nil
  1406. // The SCTs and OCSP Response are dropped on resumption.
  1407. // See http://golang.org/issue/39075.
  1408. }
  1409. if len(c.OCSPResponse) == 0 {
  1410. return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
  1411. }
  1412. if len(c.SignedCertificateTimestamps) == 0 {
  1413. return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
  1414. }
  1415. return checkFields(c, called, "client")
  1416. }
  1417. },
  1418. },
  1419. {
  1420. name: "NoClientCert",
  1421. configureServer: func(config *Config, called *int) {
  1422. config.ClientAuth = NoClientCert
  1423. config.VerifyConnection = func(c ConnectionState) error {
  1424. *called++
  1425. return checkFields(c, called, "server")
  1426. }
  1427. },
  1428. configureClient: func(config *Config, called *int) {
  1429. config.VerifyConnection = func(c ConnectionState) error {
  1430. *called++
  1431. return checkFields(c, called, "client")
  1432. }
  1433. },
  1434. },
  1435. {
  1436. name: "RequestClientCert",
  1437. configureServer: func(config *Config, called *int) {
  1438. config.ClientAuth = RequestClientCert
  1439. config.VerifyConnection = func(c ConnectionState) error {
  1440. *called++
  1441. return checkFields(c, called, "server")
  1442. }
  1443. },
  1444. configureClient: func(config *Config, called *int) {
  1445. config.Certificates = nil // clear the client cert
  1446. config.VerifyConnection = func(c ConnectionState) error {
  1447. *called++
  1448. if l := len(c.PeerCertificates); l != 1 {
  1449. return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
  1450. }
  1451. if len(c.VerifiedChains) == 0 {
  1452. return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero")
  1453. }
  1454. if c.DidResume {
  1455. return nil
  1456. // The SCTs and OCSP Response are dropped on resumption.
  1457. // See http://golang.org/issue/39075.
  1458. }
  1459. if len(c.OCSPResponse) == 0 {
  1460. return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
  1461. }
  1462. if len(c.SignedCertificateTimestamps) == 0 {
  1463. return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
  1464. }
  1465. return checkFields(c, called, "client")
  1466. }
  1467. },
  1468. },
  1469. }
  1470. for _, test := range tests {
  1471. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1472. if err != nil {
  1473. panic(err)
  1474. }
  1475. rootCAs := x509.NewCertPool()
  1476. rootCAs.AddCert(issuer)
  1477. var serverCalled, clientCalled int
  1478. serverConfig := &Config{
  1479. MaxVersion: version,
  1480. Certificates: []Certificate{testConfig.Certificates[0]},
  1481. ClientCAs: rootCAs,
  1482. NextProtos: []string{"protocol1"},
  1483. }
  1484. serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  1485. serverConfig.Certificates[0].OCSPStaple = []byte("dummy ocsp")
  1486. test.configureServer(serverConfig, &serverCalled)
  1487. clientConfig := &Config{
  1488. MaxVersion: version,
  1489. ClientSessionCache: NewLRUClientSessionCache(32),
  1490. RootCAs: rootCAs,
  1491. ServerName: "example.golang",
  1492. Certificates: []Certificate{testConfig.Certificates[0]},
  1493. NextProtos: []string{"protocol1"},
  1494. }
  1495. test.configureClient(clientConfig, &clientCalled)
  1496. testHandshakeState := func(name string, didResume bool) {
  1497. _, hs, err := testHandshake(t, clientConfig, serverConfig)
  1498. if err != nil {
  1499. t.Fatalf("%s: handshake failed: %s", name, err)
  1500. }
  1501. if hs.DidResume != didResume {
  1502. t.Errorf("%s: resumed: %v, expected: %v", name, hs.DidResume, didResume)
  1503. }
  1504. wantCalled := 1
  1505. if didResume {
  1506. wantCalled = 2 // resumption would mean this is the second time it was called in this test
  1507. }
  1508. if clientCalled != wantCalled {
  1509. t.Errorf("%s: expected client VerifyConnection called %d times, did %d times", name, wantCalled, clientCalled)
  1510. }
  1511. if serverCalled != wantCalled {
  1512. t.Errorf("%s: expected server VerifyConnection called %d times, did %d times", name, wantCalled, serverCalled)
  1513. }
  1514. }
  1515. testHandshakeState(fmt.Sprintf("%s-FullHandshake", test.name), false)
  1516. testHandshakeState(fmt.Sprintf("%s-Resumption", test.name), true)
  1517. }
  1518. }
  1519. func TestVerifyPeerCertificate(t *testing.T) {
  1520. t.Run("TLSv12", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS12) })
  1521. t.Run("TLSv13", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS13) })
  1522. }
  1523. func testVerifyPeerCertificate(t *testing.T, version uint16) {
  1524. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1525. if err != nil {
  1526. panic(err)
  1527. }
  1528. rootCAs := x509.NewCertPool()
  1529. rootCAs.AddCert(issuer)
  1530. now := func() time.Time { return time.Unix(1476984729, 0) }
  1531. sentinelErr := errors.New("TestVerifyPeerCertificate")
  1532. verifyPeerCertificateCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1533. if l := len(rawCerts); l != 1 {
  1534. return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1535. }
  1536. if len(validatedChains) == 0 {
  1537. return errors.New("got len(validatedChains) = 0, wanted non-zero")
  1538. }
  1539. *called = true
  1540. return nil
  1541. }
  1542. verifyConnectionCallback := func(called *bool, isClient bool, c ConnectionState) error {
  1543. if l := len(c.PeerCertificates); l != 1 {
  1544. return fmt.Errorf("got len(PeerCertificates) = %d, wanted 1", l)
  1545. }
  1546. if len(c.VerifiedChains) == 0 {
  1547. return fmt.Errorf("got len(VerifiedChains) = 0, wanted non-zero")
  1548. }
  1549. if isClient && len(c.OCSPResponse) == 0 {
  1550. return fmt.Errorf("got len(OCSPResponse) = 0, wanted non-zero")
  1551. }
  1552. *called = true
  1553. return nil
  1554. }
  1555. tests := []struct {
  1556. configureServer func(*Config, *bool)
  1557. configureClient func(*Config, *bool)
  1558. validate func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error)
  1559. }{
  1560. {
  1561. configureServer: func(config *Config, called *bool) {
  1562. config.InsecureSkipVerify = false
  1563. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1564. return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  1565. }
  1566. },
  1567. configureClient: func(config *Config, called *bool) {
  1568. config.InsecureSkipVerify = false
  1569. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1570. return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  1571. }
  1572. },
  1573. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1574. if clientErr != nil {
  1575. t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1576. }
  1577. if serverErr != nil {
  1578. t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1579. }
  1580. if !clientCalled {
  1581. t.Errorf("test[%d]: client did not call callback", testNo)
  1582. }
  1583. if !serverCalled {
  1584. t.Errorf("test[%d]: server did not call callback", testNo)
  1585. }
  1586. },
  1587. },
  1588. {
  1589. configureServer: func(config *Config, called *bool) {
  1590. config.InsecureSkipVerify = false
  1591. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1592. return sentinelErr
  1593. }
  1594. },
  1595. configureClient: func(config *Config, called *bool) {
  1596. config.VerifyPeerCertificate = nil
  1597. },
  1598. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1599. if serverErr != sentinelErr {
  1600. t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  1601. }
  1602. },
  1603. },
  1604. {
  1605. configureServer: func(config *Config, called *bool) {
  1606. config.InsecureSkipVerify = false
  1607. },
  1608. configureClient: func(config *Config, called *bool) {
  1609. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1610. return sentinelErr
  1611. }
  1612. },
  1613. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1614. if clientErr != sentinelErr {
  1615. t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  1616. }
  1617. },
  1618. },
  1619. {
  1620. configureServer: func(config *Config, called *bool) {
  1621. config.InsecureSkipVerify = false
  1622. },
  1623. configureClient: func(config *Config, called *bool) {
  1624. config.InsecureSkipVerify = true
  1625. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1626. if l := len(rawCerts); l != 1 {
  1627. return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1628. }
  1629. // With InsecureSkipVerify set, this
  1630. // callback should still be called but
  1631. // validatedChains must be empty.
  1632. if l := len(validatedChains); l != 0 {
  1633. return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l)
  1634. }
  1635. *called = true
  1636. return nil
  1637. }
  1638. },
  1639. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1640. if clientErr != nil {
  1641. t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1642. }
  1643. if serverErr != nil {
  1644. t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1645. }
  1646. if !clientCalled {
  1647. t.Errorf("test[%d]: client did not call callback", testNo)
  1648. }
  1649. },
  1650. },
  1651. {
  1652. configureServer: func(config *Config, called *bool) {
  1653. config.InsecureSkipVerify = false
  1654. config.VerifyConnection = func(c ConnectionState) error {
  1655. return verifyConnectionCallback(called, false, c)
  1656. }
  1657. },
  1658. configureClient: func(config *Config, called *bool) {
  1659. config.InsecureSkipVerify = false
  1660. config.VerifyConnection = func(c ConnectionState) error {
  1661. return verifyConnectionCallback(called, true, c)
  1662. }
  1663. },
  1664. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1665. if clientErr != nil {
  1666. t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1667. }
  1668. if serverErr != nil {
  1669. t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1670. }
  1671. if !clientCalled {
  1672. t.Errorf("test[%d]: client did not call callback", testNo)
  1673. }
  1674. if !serverCalled {
  1675. t.Errorf("test[%d]: server did not call callback", testNo)
  1676. }
  1677. },
  1678. },
  1679. {
  1680. configureServer: func(config *Config, called *bool) {
  1681. config.InsecureSkipVerify = false
  1682. config.VerifyConnection = func(c ConnectionState) error {
  1683. return sentinelErr
  1684. }
  1685. },
  1686. configureClient: func(config *Config, called *bool) {
  1687. config.InsecureSkipVerify = false
  1688. config.VerifyConnection = nil
  1689. },
  1690. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1691. if serverErr != sentinelErr {
  1692. t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  1693. }
  1694. },
  1695. },
  1696. {
  1697. configureServer: func(config *Config, called *bool) {
  1698. config.InsecureSkipVerify = false
  1699. config.VerifyConnection = nil
  1700. },
  1701. configureClient: func(config *Config, called *bool) {
  1702. config.InsecureSkipVerify = false
  1703. config.VerifyConnection = func(c ConnectionState) error {
  1704. return sentinelErr
  1705. }
  1706. },
  1707. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1708. if clientErr != sentinelErr {
  1709. t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  1710. }
  1711. },
  1712. },
  1713. {
  1714. configureServer: func(config *Config, called *bool) {
  1715. config.InsecureSkipVerify = false
  1716. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1717. return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  1718. }
  1719. config.VerifyConnection = func(c ConnectionState) error {
  1720. return sentinelErr
  1721. }
  1722. },
  1723. configureClient: func(config *Config, called *bool) {
  1724. config.InsecureSkipVerify = false
  1725. config.VerifyPeerCertificate = nil
  1726. config.VerifyConnection = nil
  1727. },
  1728. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1729. if serverErr != sentinelErr {
  1730. t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  1731. }
  1732. if !serverCalled {
  1733. t.Errorf("test[%d]: server did not call callback", testNo)
  1734. }
  1735. },
  1736. },
  1737. {
  1738. configureServer: func(config *Config, called *bool) {
  1739. config.InsecureSkipVerify = false
  1740. config.VerifyPeerCertificate = nil
  1741. config.VerifyConnection = nil
  1742. },
  1743. configureClient: func(config *Config, called *bool) {
  1744. config.InsecureSkipVerify = false
  1745. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1746. return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  1747. }
  1748. config.VerifyConnection = func(c ConnectionState) error {
  1749. return sentinelErr
  1750. }
  1751. },
  1752. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1753. if clientErr != sentinelErr {
  1754. t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  1755. }
  1756. if !clientCalled {
  1757. t.Errorf("test[%d]: client did not call callback", testNo)
  1758. }
  1759. },
  1760. },
  1761. }
  1762. for i, test := range tests {
  1763. c, s := localPipe(t)
  1764. done := make(chan error)
  1765. var clientCalled, serverCalled bool
  1766. go func() {
  1767. config := testConfig.Clone()
  1768. config.ServerName = "example.golang"
  1769. config.ClientAuth = RequireAndVerifyClientCert
  1770. config.ClientCAs = rootCAs
  1771. config.Time = now
  1772. config.MaxVersion = version
  1773. config.Certificates = make([]Certificate, 1)
  1774. config.Certificates[0].Certificate = [][]byte{testRSACertificate}
  1775. config.Certificates[0].PrivateKey = testRSAPrivateKey
  1776. config.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  1777. config.Certificates[0].OCSPStaple = []byte("dummy ocsp")
  1778. test.configureServer(config, &serverCalled)
  1779. err = Server(s, config).Handshake()
  1780. s.Close()
  1781. done <- err
  1782. }()
  1783. config := testConfig.Clone()
  1784. config.ServerName = "example.golang"
  1785. config.RootCAs = rootCAs
  1786. config.Time = now
  1787. config.MaxVersion = version
  1788. test.configureClient(config, &clientCalled)
  1789. clientErr := Client(c, config).Handshake()
  1790. c.Close()
  1791. serverErr := <-done
  1792. test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr)
  1793. }
  1794. }
  1795. // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  1796. // fail with brokenConnErr.
  1797. type brokenConn struct {
  1798. net.Conn
  1799. // breakAfter is the number of successful writes that will be allowed
  1800. // before all subsequent writes fail.
  1801. breakAfter int
  1802. // numWrites is the number of writes that have been done.
  1803. numWrites int
  1804. }
  1805. // brokenConnErr is the error that brokenConn returns once exhausted.
  1806. var brokenConnErr = errors.New("too many writes to brokenConn")
  1807. func (b *brokenConn) Write(data []byte) (int, error) {
  1808. if b.numWrites >= b.breakAfter {
  1809. return 0, brokenConnErr
  1810. }
  1811. b.numWrites++
  1812. return b.Conn.Write(data)
  1813. }
  1814. func TestFailedWrite(t *testing.T) {
  1815. // Test that a write error during the handshake is returned.
  1816. for _, breakAfter := range []int{0, 1} {
  1817. c, s := localPipe(t)
  1818. done := make(chan bool)
  1819. go func() {
  1820. Server(s, testConfig).Handshake()
  1821. s.Close()
  1822. done <- true
  1823. }()
  1824. brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  1825. err := Client(brokenC, testConfig).Handshake()
  1826. if err != brokenConnErr {
  1827. t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  1828. }
  1829. brokenC.Close()
  1830. <-done
  1831. }
  1832. }
  1833. // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  1834. type writeCountingConn struct {
  1835. net.Conn
  1836. // numWrites is the number of writes that have been done.
  1837. numWrites int
  1838. }
  1839. func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  1840. wcc.numWrites++
  1841. return wcc.Conn.Write(data)
  1842. }
  1843. func TestBuffering(t *testing.T) {
  1844. t.Run("TLSv12", func(t *testing.T) { testBuffering(t, VersionTLS12) })
  1845. t.Run("TLSv13", func(t *testing.T) { testBuffering(t, VersionTLS13) })
  1846. }
  1847. func testBuffering(t *testing.T, version uint16) {
  1848. c, s := localPipe(t)
  1849. done := make(chan bool)
  1850. clientWCC := &writeCountingConn{Conn: c}
  1851. serverWCC := &writeCountingConn{Conn: s}
  1852. go func() {
  1853. config := testConfig.Clone()
  1854. config.MaxVersion = version
  1855. Server(serverWCC, config).Handshake()
  1856. serverWCC.Close()
  1857. done <- true
  1858. }()
  1859. err := Client(clientWCC, testConfig).Handshake()
  1860. if err != nil {
  1861. t.Fatal(err)
  1862. }
  1863. clientWCC.Close()
  1864. <-done
  1865. var expectedClient, expectedServer int
  1866. if version == VersionTLS13 {
  1867. expectedClient = 2
  1868. expectedServer = 1
  1869. } else {
  1870. expectedClient = 2
  1871. expectedServer = 2
  1872. }
  1873. if n := clientWCC.numWrites; n != expectedClient {
  1874. t.Errorf("expected client handshake to complete with %d writes, but saw %d", expectedClient, n)
  1875. }
  1876. if n := serverWCC.numWrites; n != expectedServer {
  1877. t.Errorf("expected server handshake to complete with %d writes, but saw %d", expectedServer, n)
  1878. }
  1879. }
  1880. func TestAlertFlushing(t *testing.T) {
  1881. c, s := localPipe(t)
  1882. done := make(chan bool)
  1883. clientWCC := &writeCountingConn{Conn: c}
  1884. serverWCC := &writeCountingConn{Conn: s}
  1885. serverConfig := testConfig.Clone()
  1886. // Cause a signature-time error
  1887. brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey}
  1888. brokenKey.D = big.NewInt(42)
  1889. serverConfig.Certificates = []Certificate{{
  1890. Certificate: [][]byte{testRSACertificate},
  1891. PrivateKey: &brokenKey,
  1892. }}
  1893. go func() {
  1894. Server(serverWCC, serverConfig).Handshake()
  1895. serverWCC.Close()
  1896. done <- true
  1897. }()
  1898. err := Client(clientWCC, testConfig).Handshake()
  1899. if err == nil {
  1900. t.Fatal("client unexpectedly returned no error")
  1901. }
  1902. const expectedError = "remote error: tls: internal error"
  1903. if e := err.Error(); !strings.Contains(e, expectedError) {
  1904. t.Fatalf("expected to find %q in error but error was %q", expectedError, e)
  1905. }
  1906. clientWCC.Close()
  1907. <-done
  1908. if n := serverWCC.numWrites; n != 1 {
  1909. t.Errorf("expected server handshake to complete with one write, but saw %d", n)
  1910. }
  1911. }
  1912. func TestHandshakeRace(t *testing.T) {
  1913. if testing.Short() {
  1914. t.Skip("skipping in -short mode")
  1915. }
  1916. t.Parallel()
  1917. // This test races a Read and Write to try and complete a handshake in
  1918. // order to provide some evidence that there are no races or deadlocks
  1919. // in the handshake locking.
  1920. for i := 0; i < 32; i++ {
  1921. c, s := localPipe(t)
  1922. go func() {
  1923. server := Server(s, testConfig)
  1924. if err := server.Handshake(); err != nil {
  1925. panic(err)
  1926. }
  1927. var request [1]byte
  1928. if n, err := server.Read(request[:]); err != nil || n != 1 {
  1929. panic(err)
  1930. }
  1931. server.Write(request[:])
  1932. server.Close()
  1933. }()
  1934. startWrite := make(chan struct{})
  1935. startRead := make(chan struct{})
  1936. readDone := make(chan struct{}, 1)
  1937. client := Client(c, testConfig)
  1938. go func() {
  1939. <-startWrite
  1940. var request [1]byte
  1941. client.Write(request[:])
  1942. }()
  1943. go func() {
  1944. <-startRead
  1945. var reply [1]byte
  1946. if _, err := io.ReadFull(client, reply[:]); err != nil {
  1947. panic(err)
  1948. }
  1949. c.Close()
  1950. readDone <- struct{}{}
  1951. }()
  1952. if i&1 == 1 {
  1953. startWrite <- struct{}{}
  1954. startRead <- struct{}{}
  1955. } else {
  1956. startRead <- struct{}{}
  1957. startWrite <- struct{}{}
  1958. }
  1959. <-readDone
  1960. }
  1961. }
  1962. var getClientCertificateTests = []struct {
  1963. setup func(*Config, *Config)
  1964. expectedClientError string
  1965. verify func(*testing.T, int, *ConnectionState)
  1966. }{
  1967. {
  1968. func(clientConfig, serverConfig *Config) {
  1969. // Returning a Certificate with no certificate data
  1970. // should result in an empty message being sent to the
  1971. // server.
  1972. serverConfig.ClientCAs = nil
  1973. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1974. if len(cri.SignatureSchemes) == 0 {
  1975. panic("empty SignatureSchemes")
  1976. }
  1977. if len(cri.AcceptableCAs) != 0 {
  1978. panic("AcceptableCAs should have been empty")
  1979. }
  1980. return new(Certificate), nil
  1981. }
  1982. },
  1983. "",
  1984. func(t *testing.T, testNum int, cs *ConnectionState) {
  1985. if l := len(cs.PeerCertificates); l != 0 {
  1986. t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  1987. }
  1988. },
  1989. },
  1990. {
  1991. func(clientConfig, serverConfig *Config) {
  1992. // With TLS 1.1, the SignatureSchemes should be
  1993. // synthesised from the supported certificate types.
  1994. clientConfig.MaxVersion = VersionTLS11
  1995. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1996. if len(cri.SignatureSchemes) == 0 {
  1997. panic("empty SignatureSchemes")
  1998. }
  1999. return new(Certificate), nil
  2000. }
  2001. },
  2002. "",
  2003. func(t *testing.T, testNum int, cs *ConnectionState) {
  2004. if l := len(cs.PeerCertificates); l != 0 {
  2005. t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  2006. }
  2007. },
  2008. },
  2009. {
  2010. func(clientConfig, serverConfig *Config) {
  2011. // Returning an error should abort the handshake with
  2012. // that error.
  2013. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  2014. return nil, errors.New("GetClientCertificate")
  2015. }
  2016. },
  2017. "GetClientCertificate",
  2018. func(t *testing.T, testNum int, cs *ConnectionState) {
  2019. },
  2020. },
  2021. {
  2022. func(clientConfig, serverConfig *Config) {
  2023. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  2024. if len(cri.AcceptableCAs) == 0 {
  2025. panic("empty AcceptableCAs")
  2026. }
  2027. cert := &Certificate{
  2028. Certificate: [][]byte{testRSACertificate},
  2029. PrivateKey: testRSAPrivateKey,
  2030. }
  2031. return cert, nil
  2032. }
  2033. },
  2034. "",
  2035. func(t *testing.T, testNum int, cs *ConnectionState) {
  2036. if len(cs.VerifiedChains) == 0 {
  2037. t.Errorf("#%d: expected some verified chains, but found none", testNum)
  2038. }
  2039. },
  2040. },
  2041. }
  2042. func TestGetClientCertificate(t *testing.T) {
  2043. t.Run("TLSv12", func(t *testing.T) { testGetClientCertificate(t, VersionTLS12) })
  2044. t.Run("TLSv13", func(t *testing.T) { testGetClientCertificate(t, VersionTLS13) })
  2045. }
  2046. func testGetClientCertificate(t *testing.T, version uint16) {
  2047. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  2048. if err != nil {
  2049. panic(err)
  2050. }
  2051. for i, test := range getClientCertificateTests {
  2052. serverConfig := testConfig.Clone()
  2053. serverConfig.ClientAuth = VerifyClientCertIfGiven
  2054. serverConfig.RootCAs = x509.NewCertPool()
  2055. serverConfig.RootCAs.AddCert(issuer)
  2056. serverConfig.ClientCAs = serverConfig.RootCAs
  2057. serverConfig.Time = func() time.Time { return time.Unix(1476984729, 0) }
  2058. serverConfig.MaxVersion = version
  2059. clientConfig := testConfig.Clone()
  2060. clientConfig.MaxVersion = version
  2061. test.setup(clientConfig, serverConfig)
  2062. type serverResult struct {
  2063. cs ConnectionState
  2064. err error
  2065. }
  2066. c, s := localPipe(t)
  2067. done := make(chan serverResult)
  2068. go func() {
  2069. defer s.Close()
  2070. server := Server(s, serverConfig)
  2071. err := server.Handshake()
  2072. var cs ConnectionState
  2073. if err == nil {
  2074. cs = server.ConnectionState()
  2075. }
  2076. done <- serverResult{cs, err}
  2077. }()
  2078. clientErr := Client(c, clientConfig).Handshake()
  2079. c.Close()
  2080. result := <-done
  2081. if clientErr != nil {
  2082. if len(test.expectedClientError) == 0 {
  2083. t.Errorf("#%d: client error: %v", i, clientErr)
  2084. } else if got := clientErr.Error(); got != test.expectedClientError {
  2085. t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got)
  2086. } else {
  2087. test.verify(t, i, &result.cs)
  2088. }
  2089. } else if len(test.expectedClientError) > 0 {
  2090. t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError)
  2091. } else if err := result.err; err != nil {
  2092. t.Errorf("#%d: server error: %v", i, err)
  2093. } else {
  2094. test.verify(t, i, &result.cs)
  2095. }
  2096. }
  2097. }
  2098. func TestRSAPSSKeyError(t *testing.T) {
  2099. // crypto/tls does not support the rsa_pss_pss_* SignatureSchemes. If support for
  2100. // public keys with OID RSASSA-PSS is added to crypto/x509, they will be misused with
  2101. // the rsa_pss_rsae_* SignatureSchemes. Assert that RSASSA-PSS certificates don't
  2102. // parse, or that they don't carry *rsa.PublicKey keys.
  2103. b, _ := pem.Decode([]byte(`
  2104. -----BEGIN CERTIFICATE-----
  2105. MIIDZTCCAhygAwIBAgIUCF2x0FyTgZG0CC9QTDjGWkB5vgEwPgYJKoZIhvcNAQEK
  2106. MDGgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQC
  2107. AgDeMBIxEDAOBgNVBAMMB1JTQS1QU1MwHhcNMTgwNjI3MjI0NDM2WhcNMTgwNzI3
  2108. MjI0NDM2WjASMRAwDgYDVQQDDAdSU0EtUFNTMIIBIDALBgkqhkiG9w0BAQoDggEP
  2109. ADCCAQoCggEBANxDm0f76JdI06YzsjB3AmmjIYkwUEGxePlafmIASFjDZl/elD0Z
  2110. /a7xLX468b0qGxLS5al7XCcEprSdsDR6DF5L520+pCbpfLyPOjuOvGmk9KzVX4x5
  2111. b05YXYuXdsQ0Kjxcx2i3jjCday6scIhMJVgBZxTEyMj1thPQM14SHzKCd/m6HmCL
  2112. QmswpH2yMAAcBRWzRpp/vdH5DeOJEB3aelq7094no731mrLUCHRiZ1htq8BDB3ou
  2113. czwqgwspbqZ4dnMXl2MvfySQ5wJUxQwILbiuAKO2lVVPUbFXHE9pgtznNoPvKwQT
  2114. JNcX8ee8WIZc2SEGzofjk3NpjR+2ADB2u3sCAwEAAaNTMFEwHQYDVR0OBBYEFNEz
  2115. AdyJ2f+fU+vSCS6QzohnOnprMB8GA1UdIwQYMBaAFNEzAdyJ2f+fU+vSCS6Qzohn
  2116. OnprMA8GA1UdEwEB/wQFMAMBAf8wPgYJKoZIhvcNAQEKMDGgDTALBglghkgBZQME
  2117. AgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQCAgDeA4IBAQCjEdrR5aab
  2118. sZmCwrMeKidXgfkmWvfuLDE+TCbaqDZp7BMWcMQXT9O0UoUT5kqgKj2ARm2pEW0Z
  2119. H3Z1vj3bbds72qcDIJXp+l0fekyLGeCrX/CbgnMZXEP7+/+P416p34ChR1Wz4dU1
  2120. KD3gdsUuTKKeMUog3plxlxQDhRQmiL25ygH1LmjLd6dtIt0GVRGr8lj3euVeprqZ
  2121. bZ3Uq5eLfsn8oPgfC57gpO6yiN+UURRTlK3bgYvLh4VWB3XXk9UaQZ7Mq1tpXjoD
  2122. HYFybkWzibkZp4WRo+Fa28rirH+/wHt0vfeN7UCceURZEx4JaxIIfe4ku7uDRhJi
  2123. RwBA9Xk1KBNF
  2124. -----END CERTIFICATE-----`))
  2125. if b == nil {
  2126. t.Fatal("Failed to decode certificate")
  2127. }
  2128. cert, err := x509.ParseCertificate(b.Bytes)
  2129. if err != nil {
  2130. return
  2131. }
  2132. if _, ok := cert.PublicKey.(*rsa.PublicKey); ok {
  2133. t.Error("A RSASSA-PSS certificate was parsed like a PKCS#1 v1.5 one, and it will be mistakenly used with rsa_pss_rsae_* signature algorithms")
  2134. }
  2135. }
  2136. func TestCloseClientConnectionOnIdleServer(t *testing.T) {
  2137. clientConn, serverConn := localPipe(t)
  2138. client := Client(clientConn, testConfig.Clone())
  2139. go func() {
  2140. var b [1]byte
  2141. serverConn.Read(b[:])
  2142. client.Close()
  2143. }()
  2144. client.SetWriteDeadline(time.Now().Add(time.Minute))
  2145. err := client.Handshake()
  2146. if err != nil {
  2147. if err, ok := err.(net.Error); ok && err.Timeout() {
  2148. t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
  2149. }
  2150. } else {
  2151. t.Errorf("Error expected, but no error returned")
  2152. }
  2153. }
  2154. func testDowngradeCanary(t *testing.T, clientVersion, serverVersion uint16) error {
  2155. defer func() { testingOnlyForceDowngradeCanary = false }()
  2156. testingOnlyForceDowngradeCanary = true
  2157. clientConfig := testConfig.Clone()
  2158. clientConfig.MaxVersion = clientVersion
  2159. serverConfig := testConfig.Clone()
  2160. serverConfig.MaxVersion = serverVersion
  2161. _, _, err := testHandshake(t, clientConfig, serverConfig)
  2162. return err
  2163. }
  2164. func TestDowngradeCanary(t *testing.T) {
  2165. if err := testDowngradeCanary(t, VersionTLS13, VersionTLS12); err == nil {
  2166. t.Errorf("downgrade from TLS 1.3 to TLS 1.2 was not detected")
  2167. }
  2168. if testing.Short() {
  2169. t.Skip("skipping the rest of the checks in short mode")
  2170. }
  2171. if err := testDowngradeCanary(t, VersionTLS13, VersionTLS11); err == nil {
  2172. t.Errorf("downgrade from TLS 1.3 to TLS 1.1 was not detected")
  2173. }
  2174. if err := testDowngradeCanary(t, VersionTLS13, VersionTLS10); err == nil {
  2175. t.Errorf("downgrade from TLS 1.3 to TLS 1.0 was not detected")
  2176. }
  2177. if err := testDowngradeCanary(t, VersionTLS12, VersionTLS11); err == nil {
  2178. t.Errorf("downgrade from TLS 1.2 to TLS 1.1 was not detected")
  2179. }
  2180. if err := testDowngradeCanary(t, VersionTLS12, VersionTLS10); err == nil {
  2181. t.Errorf("downgrade from TLS 1.2 to TLS 1.0 was not detected")
  2182. }
  2183. if err := testDowngradeCanary(t, VersionTLS13, VersionTLS13); err != nil {
  2184. t.Errorf("server unexpectedly sent downgrade canary for TLS 1.3")
  2185. }
  2186. if err := testDowngradeCanary(t, VersionTLS12, VersionTLS12); err != nil {
  2187. t.Errorf("client didn't ignore expected TLS 1.2 canary")
  2188. }
  2189. if err := testDowngradeCanary(t, VersionTLS11, VersionTLS11); err != nil {
  2190. t.Errorf("client unexpectedly reacted to a canary in TLS 1.1")
  2191. }
  2192. if err := testDowngradeCanary(t, VersionTLS10, VersionTLS10); err != nil {
  2193. t.Errorf("client unexpectedly reacted to a canary in TLS 1.0")
  2194. }
  2195. }
  2196. func TestResumptionKeepsOCSPAndSCT(t *testing.T) {
  2197. t.Run("TLSv12", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS12) })
  2198. t.Run("TLSv13", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS13) })
  2199. }
  2200. func testResumptionKeepsOCSPAndSCT(t *testing.T, ver uint16) {
  2201. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  2202. if err != nil {
  2203. t.Fatalf("failed to parse test issuer")
  2204. }
  2205. roots := x509.NewCertPool()
  2206. roots.AddCert(issuer)
  2207. clientConfig := &Config{
  2208. MaxVersion: ver,
  2209. ClientSessionCache: NewLRUClientSessionCache(32),
  2210. ServerName: "example.golang",
  2211. RootCAs: roots,
  2212. }
  2213. serverConfig := testConfig.Clone()
  2214. serverConfig.MaxVersion = ver
  2215. serverConfig.Certificates[0].OCSPStaple = []byte{1, 2, 3}
  2216. serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{4, 5, 6}}
  2217. _, ccs, err := testHandshake(t, clientConfig, serverConfig)
  2218. if err != nil {
  2219. t.Fatalf("handshake failed: %s", err)
  2220. }
  2221. // after a new session we expect to see OCSPResponse and
  2222. // SignedCertificateTimestamps populated as usual
  2223. if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) {
  2224. t.Errorf("client ConnectionState contained unexpected OCSPResponse: wanted %v, got %v",
  2225. serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse)
  2226. }
  2227. if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) {
  2228. t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps: wanted %v, got %v",
  2229. serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps)
  2230. }
  2231. // if the server doesn't send any SCTs, repopulate the old SCTs
  2232. oldSCTs := serverConfig.Certificates[0].SignedCertificateTimestamps
  2233. serverConfig.Certificates[0].SignedCertificateTimestamps = nil
  2234. _, ccs, err = testHandshake(t, clientConfig, serverConfig)
  2235. if err != nil {
  2236. t.Fatalf("handshake failed: %s", err)
  2237. }
  2238. if !ccs.DidResume {
  2239. t.Fatalf("expected session to be resumed")
  2240. }
  2241. // after a resumed session we also expect to see OCSPResponse
  2242. // and SignedCertificateTimestamps populated
  2243. if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) {
  2244. t.Errorf("client ConnectionState contained unexpected OCSPResponse after resumption: wanted %v, got %v",
  2245. serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse)
  2246. }
  2247. if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, oldSCTs) {
  2248. t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v",
  2249. oldSCTs, ccs.SignedCertificateTimestamps)
  2250. }
  2251. // Only test overriding the SCTs for TLS 1.2, since in 1.3
  2252. // the server won't send the message containing them
  2253. if ver == VersionTLS13 {
  2254. return
  2255. }
  2256. // if the server changes the SCTs it sends, they should override the saved SCTs
  2257. serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{7, 8, 9}}
  2258. _, ccs, err = testHandshake(t, clientConfig, serverConfig)
  2259. if err != nil {
  2260. t.Fatalf("handshake failed: %s", err)
  2261. }
  2262. if !ccs.DidResume {
  2263. t.Fatalf("expected session to be resumed")
  2264. }
  2265. if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) {
  2266. t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v",
  2267. serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps)
  2268. }
  2269. }
  2270. // TestClientHandshakeContextCancellation tests that cancelling
  2271. // the context given to the client side conn.HandshakeContext
  2272. // interrupts the in-progress handshake.
  2273. func TestClientHandshakeContextCancellation(t *testing.T) {
  2274. c, s := localPipe(t)
  2275. ctx, cancel := context.WithCancel(context.Background())
  2276. unblockServer := make(chan struct{})
  2277. defer close(unblockServer)
  2278. go func() {
  2279. cancel()
  2280. <-unblockServer
  2281. _ = s.Close()
  2282. }()
  2283. cli := Client(c, testConfig)
  2284. // Initiates client side handshake, which will block until the client hello is read
  2285. // by the server, unless the cancellation works.
  2286. err := cli.HandshakeContext(ctx)
  2287. if err == nil {
  2288. t.Fatal("Client handshake did not error when the context was canceled")
  2289. }
  2290. if err != context.Canceled {
  2291. t.Errorf("Unexpected client handshake error: %v", err)
  2292. }
  2293. if runtime.GOARCH == "wasm" {
  2294. t.Skip("conn.Close does not error as expected when called multiple times on WASM")
  2295. }
  2296. err = cli.Close()
  2297. if err == nil {
  2298. t.Error("Client connection was not closed when the context was canceled")
  2299. }
  2300. }