tls_handshake.mx raw

   1  // A real TLS handshake, both ends running at once, over a loopback socket.
   2  //
   3  // crypto/tls is linked into every server in this tree and had no fixture at
   4  // all: the record layer was converted to the copy rule blind (rounds 240-246),
   5  // and a handshake is the only test that exercises encrypt, decrypt, readRecord
   6  // and writeRecord together. It needs two domains because a domain is
   7  // single-threaded and a handshake is a conversation: the server end lives in a
   8  // spawned domain and reports the port it bound, so the two sides really do
   9  // interleave over the wire instead of alternating in one frame.
  10  //
  11  // The certificates are built at run time rather than embedded, so the same
  12  // fixture covers x509.CreateCertificate, ParseCertificate and ECDSA signing -
  13  // subsystems no fixture covered on their own either. The child builds its own
  14  // CA and leaf and sends the CA back over a channel, which is also why there
  15  // are no package globals here: a main package has no init() to write them in,
  16  // and the child cannot see the parent's frame.
  17  //
  18  // What it asserts:
  19  //
  20  //   1. a client rooted in the issuing CA completes a handshake, and both sides
  21  //      agree on version and cipher suite
  22  //   2. 1 KiB of application data round trips byte-identically through the
  23  //      record layer, in both directions
  24  //   3. a client rooted in a DIFFERENT CA is rejected with a certificate error,
  25  //      and the server sees the alert - not a hang, which is how a record layer
  26  //      usually fails
  27  //
  28  // Case 3 depends on x509.Verify, which round 259 fixed: a callee's writes
  29  // through a pointer parameter are never relocated, so the parsed certificate's
  30  // extension slices pointed into a released frame (W10).
  31  //
  32  // Neither config pins CurvePreferences, so the handshake negotiates the first
  33  // entry of the default list - X25519MLKEM768 - and covers the post-quantum
  34  // hybrid key exchange end to end. Round 268 fixed the bug that made it
  35  // impossible: push's spread element type was resolved to the source SLICE type,
  36  // so the 32-byte X25519 share was written 24x past its slot and arrived as
  37  // zeros.
  38  //
  39  // usage: tls_handshake        exit 0 when every case holds
  40  //
  41  //:wasmtest skip
  42  // The whole point is a real conversation over a loopback socket between two
  43  // domains, and a wasm domain has neither sockets nor a second thread: net on
  44  // wasm is a stub, so the client's connect never completes and the module hangs
  45  // in its own accept loop rather than failing. The record layer is still
  46  // covered on wasm by the fixtures that use it without a socket; what cannot be
  47  // covered there is the socket.
  48  package main
  49  
  50  import (
  51  	"bytes"
  52  	"crypto/ecdsa"
  53  	"crypto/elliptic"
  54  	"crypto/rand"
  55  	"crypto/tls"
  56  	"crypto/x509"
  57  	"crypto/x509/pkix"
  58  	"io"
  59  	"math/big"
  60  	"net"
  61  	"os"
  62  	"strconv"
  63  	"time"
  64  )
  65  
  66  // two connections: one that must succeed, one that must be refused.
  67  const nConns = 2
  68  
  69  // bytes of application data in the echo: several records' worth of state,
  70  // which is the point.
  71  const payloadLen = 1024
  72  
  73  func newKey() (key *ecdsa.PrivateKey, err error) {
  74  	return ecdsa.GenerateKey(elliptic.P256(), rand.Reader())
  75  }
  76  
  77  // caDERFor makes a self-signed CA. IsCA and KeyUsageCertSign are not
  78  // decoration: Verify refuses to use a root that is not one, and a fixture whose
  79  // root is rejected fails for the wrong reason.
  80  func caDERFor(key *ecdsa.PrivateKey, cn []byte, serial int64) (der []byte, err error) {
  81  	var tmpl *x509.Certificate
  82  	tmpl = &x509.Certificate{
  83  		SerialNumber:          big.NewInt(serial),
  84  		Subject:               pkix.Name{CommonName: cn},
  85  		NotBefore:             time.Now().Add(-1 * time.Hour),
  86  		NotAfter:              time.Now().Add(24 * time.Hour),
  87  		IsCA:                  true,
  88  		BasicConstraintsValid: true,
  89  		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
  90  	}
  91  	return x509.CreateCertificate(rand.Reader(), tmpl, tmpl, &key.PublicKey, key)
  92  }
  93  
  94  // leafDERFor issues the leaf the server presents: SANs for both names a client
  95  // may verify, EKU serverAuth, signed by the CA.
  96  func leafDERFor(caKey *ecdsa.PrivateKey, caDER []byte, leafKey *ecdsa.PrivateKey) (der []byte, err error) {
  97  	var caCert *x509.Certificate
  98  	var tmpl *x509.Certificate
  99  
 100  	caCert, err = x509.ParseCertificate(caDER)
 101  	if err != nil {
 102  		return nil, err
 103  	}
 104  	tmpl = &x509.Certificate{
 105  		SerialNumber:          big.NewInt(3),
 106  		Subject:               pkix.Name{CommonName: "localhost"},
 107  		NotBefore:             time.Now().Add(-1 * time.Hour),
 108  		NotAfter:              time.Now().Add(24 * time.Hour),
 109  		KeyUsage:              x509.KeyUsageDigitalSignature,
 110  		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
 111  		BasicConstraintsValid: true,
 112  		DNSNames:              []string{"localhost"},
 113  		IPAddresses:           []net.IP{net.IPv4(127, 0, 0, 1)},
 114  	}
 115  	return x509.CreateCertificate(rand.Reader(), tmpl, caCert, &leafKey.PublicKey, caKey)
 116  }
 117  
 118  // serveOne accepts one connection, handshakes, and (for the first) echoes the
 119  // payload back. Every failure is reported over resCh so the parent can assert
 120  // on both sides of the conversation: a server error the client cannot see is
 121  // exactly the failure mode this fixture exists to catch.
 122  func serveOne(ln net.Listener, cfg *tls.Config, i int32, resCh chan []byte) {
 123  	var nc net.Conn
 124  	var err error
 125  	var c *tls.Conn
 126  	var st tls.ConnectionState
 127  	var buf []byte
 128  	var n int32
 129  	var w int32
 130  
 131  	nc, err = ln.Accept()
 132  	if err != nil {
 133  		resCh <- []byte("conn" | strconv.Itoa(i) | " accept err: " | err.Error())
 134  		return
 135  	}
 136  	// A hang in the record layer must fail the fixture, not the suite.
 137  	nc.SetDeadline(time.Now().Add(30 * time.Second))
 138  	c = tls.Server(nc, cfg)
 139  	err = c.Handshake()
 140  	if err != nil {
 141  		resCh <- []byte("conn" | strconv.Itoa(i) | " handshake err: " | err.Error())
 142  		c.Close()
 143  		return
 144  	}
 145  	st = c.ConnectionState()
 146  	resCh <- []byte("conn" | strconv.Itoa(i) | " ok ver=" | strconv.Itoa(int32(st.Version)) | " suite=" | strconv.Itoa(int32(st.CipherSuite)))
 147  	if i != 0 {
 148  		c.Close()
 149  		return
 150  	}
 151  	buf = []byte{:payloadLen}
 152  	n, err = io.ReadFull(c, buf)
 153  	if err != nil {
 154  		resCh <- []byte("conn0 read err: " | err.Error())
 155  		c.Close()
 156  		return
 157  	}
 158  	w, err = c.Write(buf[0:n])
 159  	if err != nil {
 160  		resCh <- []byte("conn0 write err: " | err.Error())
 161  		c.Close()
 162  		return
 163  	}
 164  	resCh <- []byte("conn0 echo " | strconv.Itoa(w))
 165  	c.Close()
 166  }
 167  
 168  // serverDomain is the child: it owns the certificate, the listener and both
 169  // connections. It reports the CA first, then the bound address, so the parent
 170  // can never dial a port whose root it does not have yet.
 171  func serverDomain(caCh chan []byte, addrCh chan []byte, resCh chan []byte) (closed chan struct{}) {
 172  	var caKey *ecdsa.PrivateKey
 173  	var caDER []byte
 174  	var leafKey *ecdsa.PrivateKey
 175  	var leafDER []byte
 176  	var cert tls.Certificate
 177  	var cfg tls.Config
 178  	var ln net.Listener
 179  	var err error
 180  	var i int32
 181  
 182  	caKey, err = newKey()
 183  	if err != nil {
 184  		addrCh <- []byte("ERR ca key: " | err.Error())
 185  		return
 186  	}
 187  	caDER, err = caDERFor(caKey, []byte("moxie fixture CA"), 1)
 188  	if err != nil {
 189  		addrCh <- []byte("ERR ca: " | err.Error())
 190  		return
 191  	}
 192  	leafKey, err = newKey()
 193  	if err != nil {
 194  		addrCh <- []byte("ERR leaf key: " | err.Error())
 195  		return
 196  	}
 197  	leafDER, err = leafDERFor(caKey, caDER, leafKey)
 198  	if err != nil {
 199  		addrCh <- []byte("ERR leaf: " | err.Error())
 200  		return
 201  	}
 202  	cert = tls.Certificate{}
 203  	cert.Certificate = [][]byte{leafDER, caDER}
 204  	cert.PrivateKey = leafKey
 205  	caCh <- caDER
 206  	ln, err = net.Listen("tcp", "127.0.0.1:0")
 207  	if err != nil {
 208  		addrCh <- []byte("ERR listen: " | err.Error())
 209  		return
 210  	}
 211  	// The port is ephemeral, so the child is the only side that can name it.
 212  	addrCh <- []byte(ln.Addr().String())
 213  	cfg = tls.Config{Certificates: []tls.Certificate{cert}}
 214  	for i = 0; i < nConns; i++ {
 215  		select {
 216  		case <-closed:
 217  			ln.Close()
 218  			return closed
 219  		default:
 220  		}
 221  		serveOne(ln, &cfg, i, resCh)
 222  	}
 223  	ln.Close()
 224  	return closed
 225  }
 226  
 227  func goodCase(addr []byte, roots *x509.CertPool, resCh chan []byte) (fails int32) {
 228  	var nc net.Conn
 229  	var err error
 230  	var cfg tls.Config
 231  	var c *tls.Conn
 232  	var st tls.ConnectionState
 233  	var srvMsg []byte
 234  	var send []byte
 235  	var got []byte
 236  	var n int32
 237  
 238  	nc, err = net.Dial("tcp", addr)
 239  	if err != nil {
 240  		println("FAIL dial:", err.Error())
 241  		return 1
 242  	}
 243  	nc.SetDeadline(time.Now().Add(30 * time.Second))
 244  	cfg = tls.Config{RootCAs: roots, ServerName: []byte("localhost")}
 245  	c = tls.Client(nc, &cfg)
 246  	err = c.Handshake()
 247  	if err != nil {
 248  		println("FAIL client handshake:", err.Error())
 249  		return 1
 250  	}
 251  	st = c.ConnectionState()
 252  	println("ok   client handshake ver=" | int32(st.Version).String() | " suite=" | int32(st.CipherSuite).String())
 253  	srvMsg = <-resCh
 254  	println("srv  " | string(srvMsg))
 255  	if !bytes.HasPrefix(srvMsg, []byte("conn0 ok")) {
 256  		return 1
 257  	}
 258  	// Every byte follows a stride, so a one-byte shift in the record layer
 259  	// changes the comparison.
 260  	send = []byte{:payloadLen}
 261  	for i := int32(0); i < payloadLen; i++ {
 262  		send[i] = byte((i*31 + 7) & 0xff)
 263  	}
 264  	_, err = c.Write(send)
 265  	if err != nil {
 266  		println("FAIL write:", err.Error())
 267  		return 1
 268  	}
 269  	got = []byte{:payloadLen}
 270  	n, err = io.ReadFull(c, got)
 271  	if err != nil {
 272  		println("FAIL read:", err.Error())
 273  		return 1
 274  	}
 275  	srvMsg = <-resCh
 276  	println("srv  " | string(srvMsg))
 277  	if n != payloadLen {
 278  		println("FAIL echo short read:", n.String())
 279  		return 1
 280  	}
 281  	for i := int32(0); i < payloadLen; i++ {
 282  		if got[i] != send[i] {
 283  			println("FAIL echo differs at byte", i.String())
 284  			return 1
 285  		}
 286  	}
 287  	c.Close()
 288  	println("ok   echo " | payloadLen.String() | " bytes identical")
 289  	return 0
 290  }
 291  
 292  func badCase(addr []byte, roots *x509.CertPool, resCh chan []byte) (fails int32) {
 293  	var nc net.Conn
 294  	var err error
 295  	var cfg tls.Config
 296  	var c *tls.Conn
 297  	var srvMsg []byte
 298  
 299  	nc, err = net.Dial("tcp", addr)
 300  	if err != nil {
 301  		println("FAIL dial(2):", err.Error())
 302  		return 1
 303  	}
 304  	nc.SetDeadline(time.Now().Add(30 * time.Second))
 305  	cfg = tls.Config{RootCAs: roots, ServerName: []byte("localhost")}
 306  	c = tls.Client(nc, &cfg)
 307  	err = c.Handshake()
 308  	if err == nil {
 309  		println("FAIL handshake against the wrong CA succeeded")
 310  		c.Close()
 311  		<-resCh
 312  		return 1
 313  	}
 314  	println("ok   wrong CA rejected: " | err.Error())
 315  	c.Close()
 316  	srvMsg = <-resCh
 317  	println("srv  " | string(srvMsg))
 318  	if !bytes.HasPrefix(srvMsg, []byte("conn1 handshake err")) {
 319  		println("FAIL server did not report the rejected handshake")
 320  		return 1
 321  	}
 322  	return 0
 323  }
 324  
 325  func main() {
 326  	// Termination: a batch program must still be stoppable, so the entry
 327  	// handles the channel the runtime closes on SIGINT/SIGTERM.
 328  	select {
 329  	case <-shutdown:
 330  		return
 331  	default:
 332  	}
 333  
 334  	var caCh chan []byte
 335  	var addrCh chan []byte
 336  	var resCh chan []byte
 337  	var caDER []byte
 338  	var addr []byte
 339  	var caCert *x509.Certificate
 340  	var goodRoots *x509.CertPool
 341  	var badKey *ecdsa.PrivateKey
 342  	var badDER []byte
 343  	var badCert *x509.Certificate
 344  	var badRoots *x509.CertPool
 345  	var err error
 346  	var fails int32
 347  
 348  	caCh = chan []byte{}
 349  	addrCh = chan []byte{}
 350  	resCh = chan []byte{}
 351  	spawn(serverDomain, caCh, addrCh, resCh)
 352  
 353  	// The CA the child issued: this client must be able to verify the leaf.
 354  	caDER = <-caCh
 355  	caCert, err = x509.ParseCertificate(caDER)
 356  	if err != nil {
 357  		println("FAIL parse child ca:", err.Error())
 358  		os.Exit(1)
 359  	}
 360  	goodRoots = x509.NewCertPool()
 361  	goodRoots.AddCert(caCert)
 362  
 363  	// An unrelated CA: this client must NOT be able to verify the leaf.
 364  	badKey, err = newKey()
 365  	if err != nil {
 366  		println("FAIL other ca key:", err.Error())
 367  		os.Exit(1)
 368  	}
 369  	badDER, err = caDERFor(badKey, []byte("moxie fixture other CA"), 2)
 370  	if err != nil {
 371  		println("FAIL other ca:", err.Error())
 372  		os.Exit(1)
 373  	}
 374  	badCert, err = x509.ParseCertificate(badDER)
 375  	if err != nil {
 376  		println("FAIL parse other ca:", err.Error())
 377  		os.Exit(1)
 378  	}
 379  	badRoots = x509.NewCertPool()
 380  	badRoots.AddCert(badCert)
 381  
 382  	addr = <-addrCh
 383  	if bytes.HasPrefix(addr, []byte("ERR")) {
 384  		println("FAIL " | string(addr))
 385  		os.Exit(1)
 386  	}
 387  	println("srv  listening on " | string(addr))
 388  
 389  	fails = fails + goodCase(addr, goodRoots, resCh)
 390  	fails = fails + badCase(addr, badRoots, resCh)
 391  
 392  	if fails != 0 {
 393  		println("tls_handshake:", fails.String(), "case(s) failed")
 394  		os.Exit(1)
 395  	}
 396  	println("tls_handshake ok")
 397  }
 398