Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
go crypto/tls test & patch for SNI
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"io/ioutil"
"math/big"
"net"
"path/filepath"
"syscall"
"time"
)
var (
maxInt64 int64 = 0x7FFFFFFFFFFFFFFF
maxBig64 = big.NewInt(maxInt64)
)
func main() {
// Generate a self signed CA cert & key.
caCert, caKey, err := generateCA("CA")
handle(err)
// Generate an alpha cert signed by our CA cert
alphaPair, err := generatePair("alpha", caCert, caKey)
handle(err)
// Generate an beta cert signed by our CA cert
betaPair, err := generatePair("beta", caCert, caKey)
handle(err)
// Add the certs to our server config and build the NameToCertificates map
serverConfig := &tls.Config{
Certificates: []tls.Certificate{alphaPair, betaPair},
}
serverConfig.BuildNameToCertificate()
socketPath := startUnixServer(serverConfig)
pool := x509.NewCertPool()
pool.AddCert(caCert)
// test client connections
testClients("alpha", socketPath, pool) // works fine
testClients("beta", socketPath, pool) // remote error: bad record MAC
}
func testClients(serverName, socketPath string, pool *x509.CertPool) {
config := &tls.Config{
ServerName: serverName,
RootCAs: pool,
}
// tls.Dial
tlsDial, err := tls.Dial("unix", socketPath, config)
handle(err)
err = tlsDial.Handshake()
handle(err)
// net.Dial + tls.Client
netDial, err := net.Dial("unix", socketPath)
handle(err)
tlsClient := tls.Client(netDial, config)
handle(err)
err = tlsClient.Handshake()
handle(err)
}
func generateCA(serverName string) (*x509.Certificate, *rsa.PrivateKey, error) {
priv, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, nil, err
}
serial := randBigInt()
keyId := randBytes()
template := x509.Certificate{
Subject: pkix.Name{
CommonName: serverName,
},
SerialNumber: serial,
SubjectKeyId: keyId,
AuthorityKeyId: keyId,
NotBefore: time.Now().Add(-5 * time.Minute).UTC(),
NotAfter: time.Now().Add(5 * time.Minute).UTC(),
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, nil, err
}
certs, err := x509.ParseCertificates(derBytes)
if err != nil {
return nil, nil, err
}
if len(certs) != 1 {
return nil, nil, errors.New("Failed to generate a parsable certificate")
}
return certs[0], priv, nil
}
func generateCert(serverName string, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey, error) {
priv, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, nil, err
}
serial := randBigInt()
keyId := randBytes()
template := x509.Certificate{
Subject: pkix.Name{
CommonName: serverName,
},
SerialNumber: serial,
SubjectKeyId: keyId,
AuthorityKeyId: caCert.AuthorityKeyId,
NotBefore: time.Now().Add(-5 * time.Minute).UTC(),
NotAfter: time.Now().Add(5 * time.Minute).UTC(),
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, caCert, &priv.PublicKey, caKey)
if err != nil {
return nil, nil, err
}
certs, err := x509.ParseCertificates(derBytes)
if err != nil {
return nil, nil, err
}
if len(certs) != 1 {
return nil, nil, errors.New("Failed to generate a parsable certificate")
}
return certs[0], priv, nil
}
func x509Pair(cert *x509.Certificate, key *rsa.PrivateKey) (tls.Certificate, error) {
cBytes := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
kBytes := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
return tls.X509KeyPair(cBytes, kBytes)
}
func generatePair(serverName string, caCert *x509.Certificate, caKey *rsa.PrivateKey) (tls.Certificate, error) {
cert, key, err := generateCert(serverName, caCert, caKey)
if err != nil {
return tls.Certificate{}, err
}
return x509Pair(cert, key)
}
func startUnixServer(config *tls.Config) string {
dir, err := ioutil.TempDir("", "")
if err != nil {
panic(err.Error())
}
socketPath := filepath.Join(dir, "test.sock")
listener, err := tls.Listen("unix", socketPath, config)
if err != nil {
panic(err.Error())
}
go func() {
defer listener.Close()
for {
conn, err := listener.Accept()
if err == nil {
tlsConn, ok := conn.(*tls.Conn)
if ok {
tlsConn.Handshake()
//tlsConn.Close()
} else {
panic("got a non tls client connection")
}
} else if err == syscall.EINVAL {
return
} else {
panic(err.Error())
}
}
}()
return socketPath
}
func randBigInt() (value *big.Int) {
value, _ = rand.Int(rand.Reader, maxBig64)
return
}
func randBytes() (bytes []byte) {
bytes = make([]byte, 20)
rand.Read(bytes)
return
}
func handle(err error) {
if err != nil {
panic(err.Error())
}
}
# HG changeset patch
# User Ben Burkert <ben@benburkert.com>
# Date 1332324234 25200
# Node ID 42ca8f0f6a6d09e6ce1aae285bbcc860a4d2afb4
# Parent 15a98eba66e021d5ea66d357b54742c74160bb39
crypto/tls: use the private key for the certificate presented to the client.
A server's default certificate's private key was always used to establish the tls connection,
even when the client uses the Server Name extension to request a non-default certificate.
The key agreement keeps track of the private key to use during the key exchange so that the
private key corresponding to the presented certificate can be used.
diff --git a/src/pkg/crypto/tls/cipher_suites.go b/src/pkg/crypto/tls/cipher_suites.go
--- a/src/pkg/crypto/tls/cipher_suites.go
+++ b/src/pkg/crypto/tls/cipher_suites.go
@@ -153,7 +153,7 @@
}
func rsaKA() keyAgreement {
- return rsaKeyAgreement{}
+ return new(rsaKeyAgreement)
}
func ecdheRSAKA() keyAgreement {
diff --git a/src/pkg/crypto/tls/key_agreement.go b/src/pkg/crypto/tls/key_agreement.go
--- a/src/pkg/crypto/tls/key_agreement.go
+++ b/src/pkg/crypto/tls/key_agreement.go
@@ -18,13 +18,21 @@
// rsaKeyAgreement implements the standard TLS key agreement where the client
// encrypts the pre-master secret to the server's public key.
-type rsaKeyAgreement struct{}
+type rsaKeyAgreement struct{
+ privateKey *rsa.PrivateKey
+}
-func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
+func (ka *rsaKeyAgreement) generateServerKeyExchange(config *Config, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
+ if len(clientHello.serverName) > 0 {
+ ka.privateKey = config.getCertificateForName(clientHello.serverName).PrivateKey.(*rsa.PrivateKey)
+ } else {
+ ka.privateKey = config.Certificates[0].PrivateKey.(*rsa.PrivateKey)
+ }
+
return nil, nil
}
-func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
+func (ka *rsaKeyAgreement) processClientKeyExchange(config *Config, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
preMasterSecret := make([]byte, 48)
_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
if err != nil {
@@ -44,7 +52,7 @@
ciphertext = ckx.ciphertext[2:]
}
- err = rsa.DecryptPKCS1v15SessionKey(config.rand(), config.Certificates[0].PrivateKey.(*rsa.PrivateKey), ciphertext, preMasterSecret)
+ err = rsa.DecryptPKCS1v15SessionKey(config.rand(), ka.privateKey, ciphertext, preMasterSecret)
if err != nil {
return nil, err
}
@@ -57,11 +65,11 @@
return preMasterSecret, nil
}
-func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
+func (ka *rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
return errors.New("unexpected ServerKeyExchange")
}
-func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
+func (ka *rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
preMasterSecret := make([]byte, 48)
preMasterSecret[0] = byte(clientHello.vers >> 8)
preMasterSecret[1] = byte(clientHello.vers)
@@ -147,7 +155,13 @@
copy(serverECDHParams[4:], ecdhePublic)
md5sha1 := md5SHA1Hash(clientHello.random, hello.random, serverECDHParams)
- sig, err := rsa.SignPKCS1v15(config.rand(), config.Certificates[0].PrivateKey.(*rsa.PrivateKey), crypto.MD5SHA1, md5sha1)
+ priv := config.Certificates[0].PrivateKey.(*rsa.PrivateKey)
+
+ if len(clientHello.serverName) > 0 {
+ priv = config.getCertificateForName(clientHello.serverName).PrivateKey.(*rsa.PrivateKey)
+ }
+
+ sig, err := rsa.SignPKCS1v15(config.rand(), priv, crypto.MD5SHA1, md5sha1)
if err != nil {
return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
}
exporting patch:
<fdopen>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.