go-gemini/cert.go

174 lines
4.5 KiB
Go
Raw Normal View History

2020-09-27 18:20:59 -06:00
package gmi
2020-09-27 11:50:48 -06:00
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
2020-09-27 21:49:41 -06:00
"crypto/tls"
2020-09-27 11:50:48 -06:00
"crypto/x509"
"encoding/pem"
"math/big"
"net"
"os"
"path/filepath"
2020-09-27 11:50:48 -06:00
"strings"
"time"
)
// CertificateStore maps hostnames to certificates.
2020-10-11 21:48:18 -06:00
type CertificateStore struct {
store map[string]tls.Certificate
}
// Add adds a certificate for the given hostname to the store.
func (c *CertificateStore) Add(hostname string, cert tls.Certificate) {
if c.store == nil {
c.store = map[string]tls.Certificate{}
}
c.store[hostname] = cert
}
// Lookup returns the certificate for the given hostname.
func (c *CertificateStore) Lookup(hostname string) (*tls.Certificate, error) {
cert, ok := c.store[hostname]
if !ok {
return nil, ErrUnknownCertificate
}
// Ensure that the certificate is not expired
if cert.Leaf != nil && cert.Leaf.NotAfter.Before(time.Now()) {
return &cert, ErrInvalidCertificate
}
2020-10-11 21:48:18 -06:00
return &cert, nil
}
// Load loads certificates from the given path.
// The path should lead to a directory containing certificates and private keys
// in the form hostname.crt and hostname.key.
// For example, the hostname "localhost" would have the corresponding files
// localhost.crt (certificate) and localhost.key (private key).
func (c *CertificateStore) Load(path string) error {
if c.store == nil {
c.store = map[string]tls.Certificate{}
}
matches, err := filepath.Glob(filepath.Join(path, "*.crt"))
if err != nil {
return err
}
for _, crtPath := range matches {
keyPath := strings.TrimSuffix(crtPath, ".crt") + ".key"
cert, err := tls.LoadX509KeyPair(crtPath, keyPath)
if err != nil {
continue
}
hostname := filepath.Base(crtPath)
c.store[hostname] = cert
}
2020-10-11 21:48:18 -06:00
return nil
}
2020-09-27 11:50:48 -06:00
2020-09-27 21:49:41 -06:00
// NewCertificate creates and returns a new parsed certificate.
func NewCertificate(host string, duration time.Duration) (tls.Certificate, error) {
crt, key, err := NewRawCertificate(host, duration)
if err != nil {
return tls.Certificate{}, err
}
return tls.X509KeyPair(crt, key)
2020-09-27 11:50:48 -06:00
}
2020-09-27 21:49:41 -06:00
// NewRawCertificate creates and returns a raw certificate for the given host.
2020-09-27 11:50:48 -06:00
// It generates a self-signed TLS certificate and a ED25519 private key.
2020-09-27 21:49:41 -06:00
func NewRawCertificate(host string, duration time.Duration) (crt, key []byte, err error) {
2020-09-27 11:50:48 -06:00
// Generate a ED25519 private key
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
public := priv.Public().(ed25519.PublicKey)
// ED25519 keys should have the DigitalSignature KeyUsage bits set
// in the x509.Certificate template
keyUsage := x509.KeyUsageDigitalSignature
notBefore := time.Now()
2020-09-27 21:49:41 -06:00
notAfter := notBefore.Add(duration)
2020-09-27 11:50:48 -06:00
// Generate the serial number
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, err
}
template := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(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)
}
}
// Create the certificate
cert, err := x509.CreateCertificate(rand.Reader, &template, &template, public, priv)
if err != nil {
return nil, nil, err
}
// Encode the certificate
var b bytes.Buffer
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert}); err != nil {
return nil, nil, err
}
crt = b.Bytes()
// Encode the key
b = bytes.Buffer{}
if err != nil {
return nil, nil, err
}
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
return nil, nil, err
}
if err := pem.Encode(&b, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
return nil, nil, err
}
key = b.Bytes()
return
}
// WriteX509KeyPair writes the provided certificate and private key
2020-09-28 00:13:46 -06:00
// to path.crt and path.key respectively.
func WriteX509KeyPair(path string, crt, key []byte) error {
2020-09-27 11:50:48 -06:00
// Write the certificate
2020-09-28 00:13:46 -06:00
crtPath := path + ".crt"
2020-09-27 11:50:48 -06:00
crtOut, err := os.OpenFile(crtPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if _, err := crtOut.Write(crt); err != nil {
return err
}
// Write the private key
2020-09-28 00:13:46 -06:00
keyPath := path + ".key"
2020-09-27 11:50:48 -06:00
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if _, err := keyOut.Write(key); err != nil {
return err
}
return nil
}