public
Created

go crypto/tls test & patch for SNI

  • Download Gist
sni_test.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
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())
}
}
tls.patch
Diff
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
# 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>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.