实现使用自签名证书的tls.Config.GetCertificate方法。

huangapple go评论95阅读模式
英文:

implement tls.Config.GetCertificate with self signed certificates

问题

我正在尝试弄清楚如何实现一个函数来提供给tls.Config.GetCertificate,以使用自签名证书。

我使用了这个二进制源代码作为基础:https://golang.org/src/crypto/tls/generate_cert.go

还阅读了这篇文章:https://ericchiang.github.io/tls/go/https/2015/06/21/go-tls.html

不幸的是,到目前为止,我遇到了这个错误:2016/11/03 23:18:20 http2: server: error reading preface from client 127.0.0.1:34346: remote error: tls: unknown certificate authority

我认为我需要生成一个 CA 证书,然后用它签署密钥,但我不确定如何继续(...)。

这是我的代码,有人可以帮忙吗?

package gssc

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"github.com/pkg/errors"
	"math/big"
	"net"
	"strings"
	"time"
)

func GetCertificate(arg interface{}) func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	var opts Certopts
	var err error
	if host, ok := arg.(string); ok {
		opts = Certopts{
			RsaBits:   2048,
			Host:      host,
			ValidFrom: time.Now(),
		}
	} else if o, ok := arg.(Certopts); ok {
		opts = o
	} else {
		err = errors.New("Invalid arg type, must be string(hostname) or Certopt{...}")
	}
	return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		if err != nil {
			return nil, err
		}
		return generate(opts)
	}
}

type Certopts struct {
	RsaBits   int
	Host      string
	IsCA      bool
	ValidFrom time.Time
	ValidFor  time.Duration
}

func generate(opts Certopts) (*tls.Certificate, error) {

	priv, err := rsa.GenerateKey(rand.Reader, opts.RsaBits)
	if err != nil {
		return nil, errors.Wrap(err, "failed to generate private key")
	}

	notAfter := opts.ValidFrom.Add(opts.ValidFor)

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to generate serial number\n")
	}

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Acme Co"},
		},
		NotBefore: opts.ValidFrom,
		NotAfter:  notAfter,

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	hosts := strings.Split(opts.Host, ",")
	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	if opts.IsCA {
		template.IsCA = true
		template.KeyUsage |= x509.KeyUsageCertSign
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create certificate")
	}

	return &tls.Certificate{
		Certificate: [][]byte{derBytes},
		PrivateKey:  priv,
	}, nil
}

这是我使用的测试代码:

package main

import (
	"crypto/tls"
	"github.com/mh-cbon/gssc"
	"net/http"
)

type ww struct{}

func (s *ww) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte("This is an example server.\n"))
}

func main() {
	s := &http.Server{
		Handler: &ww{},
		Addr:    ":8080",
		TLSConfig: &tls.Config{
			InsecureSkipVerify: true,
			GetCertificate:     gssc.GetCertificate("example.org"),
		},
	}
	s.ListenAndServeTLS("", "")
}

非常感谢!

英文:

I m trying to figure out how i can implement a function to feed to tls.Config.GetCertificate with self signed certificates.

I used this bin source as a base, https://golang.org/src/crypto/tls/generate_cert.go

Also read this,
https://ericchiang.github.io/tls/go/https/2015/06/21/go-tls.html

Unfortunately, so far i m stuck with this error
2016/11/03 23:18:20 http2: server: error reading preface from client 127.0.0.1:34346: remote error: tls: unknown certificate authority

I think i need to generate a CA cert and then sign the key with it, but i m not sure how to proceed (....).

Here is my code, can someone help with that ?

package gssc
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"github.com/pkg/errors"
"math/big"
"net"
"strings"
"time"
)
func GetCertificate(arg interface{}) func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
var opts Certopts
var err error
if host, ok := arg.(string); ok {
opts = Certopts{
RsaBits:   2048,
Host:      host,
ValidFrom: time.Now(),
}
} else if o, ok := arg.(Certopts); ok {
opts = o
} else {
err = errors.New("Invalid arg type, must be string(hostname) or Certopt{...}")
}
return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if err != nil {
return nil, err
}
return generate(opts)
}
}
type Certopts struct {
RsaBits   int
Host      string
IsCA      bool
ValidFrom time.Time
ValidFor  time.Duration
}
func generate(opts Certopts) (*tls.Certificate, error) {
priv, err := rsa.GenerateKey(rand.Reader, opts.RsaBits)
if err != nil {
return nil, errors.Wrap(err, "failed to generate private key")
}
notAfter := opts.ValidFrom.Add(opts.ValidFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate serial number\n")
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: opts.ValidFrom,
NotAfter:  notAfter,
KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(opts.Host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
if opts.IsCA {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, errors.Wrap(err, "Failed to create certificate")
}
return &tls.Certificate{
Certificate: [][]byte{derBytes},
PrivateKey:  priv,
}, nil
}

This is the test code i use

package main
import (
"crypto/tls"
"github.com/mh-cbon/gssc"
"net/http"
)
type ww struct{}
func (s *ww) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("This is an example server.\n"))
}
func main() {
s := &http.Server{
Handler: &ww{},
Addr:    ":8080",
TLSConfig: &tls.Config{
InsecureSkipVerify: true,
GetCertificate:     gssc.GetCertificate("example.org"),
},
}
s.ListenAndServeTLS("", "")
}

Thanks a lot!

答案1

得分: 4

你的tls.Config.GetCertificate的实现导致了问题。

每次调用tls.Config.GetCertificate时,你都在生成一个证书。你需要在匿名函数中生成证书一次,然后返回它。

gssc.GetCertificate中:

cert, err := generate(opts)
return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if err != nil {
return nil, err
}
return cert, err
}
英文:

Your implementation of tls.Config.GetCertificate is causing the problem.

You are generating a certificate each time tls.Config.GetCertificate is called. You need to generate the certificate once and then return it in the anonymous function.

In gssc.GetCertificate :

cert, err := generate(opts)
return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
if err != nil {
return nil, err
}
return cert, err
}

huangapple
  • 本文由 发表于 2016年11月4日 06:25:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/40412270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定