2019-03-11 18:56:48 +02:00
|
|
|
package certcrypto
|
2018-12-06 23:50:17 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto"
|
|
|
|
"crypto/ecdsa"
|
2020-01-06 17:52:56 +02:00
|
|
|
"crypto/ed25519"
|
2018-12-06 23:50:17 +02:00
|
|
|
"crypto/elliptic"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
|
|
|
"crypto/x509/pkix"
|
|
|
|
"encoding/asn1"
|
|
|
|
"encoding/pem"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"math/big"
|
2023-05-02 19:02:18 +02:00
|
|
|
"net"
|
2024-02-08 04:16:48 +02:00
|
|
|
"slices"
|
2020-01-06 17:52:56 +02:00
|
|
|
"strings"
|
2018-12-06 23:50:17 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/ocsp"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Constants for all key types we support.
|
|
|
|
const (
|
|
|
|
EC256 = KeyType("P256")
|
|
|
|
EC384 = KeyType("P384")
|
|
|
|
RSA2048 = KeyType("2048")
|
2023-03-01 17:27:20 +02:00
|
|
|
RSA3072 = KeyType("3072")
|
2018-12-06 23:50:17 +02:00
|
|
|
RSA4096 = KeyType("4096")
|
|
|
|
RSA8192 = KeyType("8192")
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// OCSPGood means that the certificate is valid.
|
|
|
|
OCSPGood = ocsp.Good
|
|
|
|
// OCSPRevoked means that the certificate has been deliberately revoked.
|
|
|
|
OCSPRevoked = ocsp.Revoked
|
|
|
|
// OCSPUnknown means that the OCSP responder doesn't know about the certificate.
|
|
|
|
OCSPUnknown = ocsp.Unknown
|
|
|
|
// OCSPServerFailed means that the OCSP responder failed to process the request.
|
|
|
|
OCSPServerFailed = ocsp.ServerFailed
|
|
|
|
)
|
|
|
|
|
2020-05-08 19:35:25 +02:00
|
|
|
// Constants for OCSP must staple.
|
2018-12-06 23:50:17 +02:00
|
|
|
var (
|
|
|
|
tlsFeatureExtensionOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 24}
|
|
|
|
ocspMustStapleFeature = []byte{0x30, 0x03, 0x02, 0x01, 0x05}
|
|
|
|
)
|
|
|
|
|
|
|
|
// KeyType represents the key algo as well as the key size or curve to use.
|
|
|
|
type KeyType string
|
|
|
|
|
|
|
|
type DERCertificateBytes []byte
|
|
|
|
|
|
|
|
// ParsePEMBundle parses a certificate bundle from top to bottom and returns
|
|
|
|
// a slice of x509 certificates. This function will error if no certificates are found.
|
|
|
|
func ParsePEMBundle(bundle []byte) ([]*x509.Certificate, error) {
|
|
|
|
var certificates []*x509.Certificate
|
|
|
|
var certDERBlock *pem.Block
|
|
|
|
|
|
|
|
for {
|
|
|
|
certDERBlock, bundle = pem.Decode(bundle)
|
|
|
|
if certDERBlock == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if certDERBlock.Type == "CERTIFICATE" {
|
|
|
|
cert, err := x509.ParseCertificate(certDERBlock.Bytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
certificates = append(certificates, cert)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(certificates) == 0 {
|
|
|
|
return nil, errors.New("no certificates were found while parsing the bundle")
|
|
|
|
}
|
|
|
|
|
|
|
|
return certificates, nil
|
|
|
|
}
|
|
|
|
|
2020-01-06 17:52:56 +02:00
|
|
|
// ParsePEMPrivateKey parses a private key from key, which is a PEM block.
|
|
|
|
// Borrowed from Go standard library, to handle various private key and PEM block types.
|
|
|
|
// https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L291-L308
|
2023-07-29 12:59:24 +02:00
|
|
|
// https://github.com/golang/go/blob/693748e9fa385f1e2c3b91ca9acbb6c0ad2d133d/src/crypto/tls/tls.go#L238
|
2018-12-06 23:50:17 +02:00
|
|
|
func ParsePEMPrivateKey(key []byte) (crypto.PrivateKey, error) {
|
2020-01-06 17:52:56 +02:00
|
|
|
keyBlockDER, _ := pem.Decode(key)
|
2022-02-20 16:23:52 +02:00
|
|
|
if keyBlockDER == nil {
|
2024-02-08 04:16:48 +02:00
|
|
|
return nil, errors.New("invalid PEM block")
|
2022-02-20 16:23:52 +02:00
|
|
|
}
|
2020-01-06 17:52:56 +02:00
|
|
|
|
|
|
|
if keyBlockDER.Type != "PRIVATE KEY" && !strings.HasSuffix(keyBlockDER.Type, " PRIVATE KEY") {
|
|
|
|
return nil, fmt.Errorf("unknown PEM header %q", keyBlockDER.Type)
|
|
|
|
}
|
|
|
|
|
|
|
|
if key, err := x509.ParsePKCS1PrivateKey(keyBlockDER.Bytes); err == nil {
|
|
|
|
return key, nil
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
2020-01-06 17:52:56 +02:00
|
|
|
|
|
|
|
if key, err := x509.ParsePKCS8PrivateKey(keyBlockDER.Bytes); err == nil {
|
|
|
|
switch key := key.(type) {
|
|
|
|
case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
|
|
|
|
return key, nil
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("found unknown private key type in PKCS#8 wrapping: %T", key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if key, err := x509.ParseECPrivateKey(keyBlockDER.Bytes); err == nil {
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("failed to parse private key")
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func GeneratePrivateKey(keyType KeyType) (crypto.PrivateKey, error) {
|
|
|
|
switch keyType {
|
|
|
|
case EC256:
|
|
|
|
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
|
|
|
case EC384:
|
|
|
|
return ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
|
|
|
|
case RSA2048:
|
|
|
|
return rsa.GenerateKey(rand.Reader, 2048)
|
2023-03-01 17:27:20 +02:00
|
|
|
case RSA3072:
|
|
|
|
return rsa.GenerateKey(rand.Reader, 3072)
|
2018-12-06 23:50:17 +02:00
|
|
|
case RSA4096:
|
|
|
|
return rsa.GenerateKey(rand.Reader, 4096)
|
|
|
|
case RSA8192:
|
|
|
|
return rsa.GenerateKey(rand.Reader, 8192)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, fmt.Errorf("invalid KeyType: %s", keyType)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GenerateCSR(privateKey crypto.PrivateKey, domain string, san []string, mustStaple bool) ([]byte, error) {
|
2023-05-02 19:02:18 +02:00
|
|
|
var dnsNames []string
|
|
|
|
var ipAddresses []net.IP
|
|
|
|
for _, altname := range san {
|
|
|
|
if ip := net.ParseIP(altname); ip != nil {
|
|
|
|
ipAddresses = append(ipAddresses, ip)
|
|
|
|
} else {
|
|
|
|
dnsNames = append(dnsNames, altname)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-06 23:50:17 +02:00
|
|
|
template := x509.CertificateRequest{
|
2023-05-02 19:02:18 +02:00
|
|
|
Subject: pkix.Name{CommonName: domain},
|
|
|
|
DNSNames: dnsNames,
|
|
|
|
IPAddresses: ipAddresses,
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if mustStaple {
|
|
|
|
template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{
|
|
|
|
Id: tlsFeatureExtensionOID,
|
|
|
|
Value: ocspMustStapleFeature,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return x509.CreateCertificateRequest(rand.Reader, &template, privateKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
func PEMEncode(data interface{}) []byte {
|
2019-02-08 20:29:28 +02:00
|
|
|
return pem.EncodeToMemory(PEMBlock(data))
|
|
|
|
}
|
|
|
|
|
|
|
|
func PEMBlock(data interface{}) *pem.Block {
|
2018-12-06 23:50:17 +02:00
|
|
|
var pemBlock *pem.Block
|
|
|
|
switch key := data.(type) {
|
|
|
|
case *ecdsa.PrivateKey:
|
|
|
|
keyBytes, _ := x509.MarshalECPrivateKey(key)
|
|
|
|
pemBlock = &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}
|
|
|
|
case *rsa.PrivateKey:
|
|
|
|
pemBlock = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}
|
|
|
|
case *x509.CertificateRequest:
|
|
|
|
pemBlock = &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: key.Raw}
|
|
|
|
case DERCertificateBytes:
|
|
|
|
pemBlock = &pem.Block{Type: "CERTIFICATE", Bytes: []byte(data.(DERCertificateBytes))}
|
|
|
|
}
|
|
|
|
|
2019-02-08 20:29:28 +02:00
|
|
|
return pemBlock
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func pemDecode(data []byte) (*pem.Block, error) {
|
|
|
|
pemBlock, _ := pem.Decode(data)
|
|
|
|
if pemBlock == nil {
|
2020-02-27 20:14:46 +02:00
|
|
|
return nil, errors.New("PEM decode did not yield a valid block. Is the certificate in the right format?")
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return pemBlock, nil
|
|
|
|
}
|
|
|
|
|
2021-03-04 21:16:59 +02:00
|
|
|
func PemDecodeTox509CSR(data []byte) (*x509.CertificateRequest, error) {
|
|
|
|
pemBlock, err := pemDecode(data)
|
2018-12-06 23:50:17 +02:00
|
|
|
if pemBlock == nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-06-05 13:47:39 +02:00
|
|
|
if pemBlock.Type != "CERTIFICATE REQUEST" && pemBlock.Type != "NEW CERTIFICATE REQUEST" {
|
2020-02-27 20:14:46 +02:00
|
|
|
return nil, errors.New("PEM block is not a certificate request")
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return x509.ParseCertificateRequest(pemBlock.Bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParsePEMCertificate returns Certificate from a PEM encoded certificate.
|
|
|
|
// The certificate has to be PEM encoded. Any other encodings like DER will fail.
|
|
|
|
func ParsePEMCertificate(cert []byte) (*x509.Certificate, error) {
|
|
|
|
pemBlock, err := pemDecode(cert)
|
|
|
|
if pemBlock == nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// from a DER encoded certificate
|
|
|
|
return x509.ParseCertificate(pemBlock.Bytes)
|
|
|
|
}
|
|
|
|
|
2024-01-27 01:16:47 +02:00
|
|
|
func GetCertificateMainDomain(cert *x509.Certificate) (string, error) {
|
|
|
|
return getMainDomain(cert.Subject, cert.DNSNames)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetCSRMainDomain(cert *x509.CertificateRequest) (string, error) {
|
|
|
|
return getMainDomain(cert.Subject, cert.DNSNames)
|
|
|
|
}
|
|
|
|
|
|
|
|
func getMainDomain(subject pkix.Name, dnsNames []string) (string, error) {
|
|
|
|
if subject.CommonName == "" && len(dnsNames) == 0 {
|
|
|
|
return "", errors.New("missing domain")
|
|
|
|
}
|
|
|
|
|
|
|
|
if subject.CommonName != "" {
|
|
|
|
return subject.CommonName, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return dnsNames[0], nil
|
|
|
|
}
|
|
|
|
|
2018-12-06 23:50:17 +02:00
|
|
|
func ExtractDomains(cert *x509.Certificate) []string {
|
2020-02-21 20:28:07 +02:00
|
|
|
var domains []string
|
|
|
|
if cert.Subject.CommonName != "" {
|
|
|
|
domains = append(domains, cert.Subject.CommonName)
|
|
|
|
}
|
2018-12-06 23:50:17 +02:00
|
|
|
|
|
|
|
// Check for SAN certificate
|
|
|
|
for _, sanDomain := range cert.DNSNames {
|
|
|
|
if sanDomain == cert.Subject.CommonName {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
domains = append(domains, sanDomain)
|
|
|
|
}
|
|
|
|
|
2023-05-02 19:02:18 +02:00
|
|
|
commonNameIP := net.ParseIP(cert.Subject.CommonName)
|
|
|
|
for _, sanIP := range cert.IPAddresses {
|
|
|
|
if !commonNameIP.Equal(sanIP) {
|
|
|
|
domains = append(domains, sanIP.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-06 23:50:17 +02:00
|
|
|
return domains
|
|
|
|
}
|
|
|
|
|
|
|
|
func ExtractDomainsCSR(csr *x509.CertificateRequest) []string {
|
2020-02-21 20:28:07 +02:00
|
|
|
var domains []string
|
|
|
|
if csr.Subject.CommonName != "" {
|
|
|
|
domains = append(domains, csr.Subject.CommonName)
|
|
|
|
}
|
2018-12-06 23:50:17 +02:00
|
|
|
|
|
|
|
// loop over the SubjectAltName DNS names
|
|
|
|
for _, sanName := range csr.DNSNames {
|
2024-02-08 04:16:48 +02:00
|
|
|
if slices.Contains(domains, sanName) {
|
2018-12-06 23:50:17 +02:00
|
|
|
// Duplicate; skip this name
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name is unique
|
|
|
|
domains = append(domains, sanName)
|
|
|
|
}
|
|
|
|
|
2023-05-02 19:02:18 +02:00
|
|
|
cnip := net.ParseIP(csr.Subject.CommonName)
|
|
|
|
for _, sanIP := range csr.IPAddresses {
|
|
|
|
if !cnip.Equal(sanIP) {
|
|
|
|
domains = append(domains, sanIP.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-06 23:50:17 +02:00
|
|
|
return domains
|
|
|
|
}
|
|
|
|
|
|
|
|
func GeneratePemCert(privateKey *rsa.PrivateKey, domain string, extensions []pkix.Extension) ([]byte, error) {
|
|
|
|
derBytes, err := generateDerCert(privateKey, time.Time{}, domain, extensions)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateDerCert(privateKey *rsa.PrivateKey, expiration time.Time, domain string, extensions []pkix.Extension) ([]byte, error) {
|
|
|
|
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
|
|
|
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if expiration.IsZero() {
|
2021-11-27 06:22:59 +02:00
|
|
|
expiration = time.Now().AddDate(1, 0, 0)
|
2018-12-06 23:50:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
template := x509.Certificate{
|
|
|
|
SerialNumber: serialNumber,
|
|
|
|
Subject: pkix.Name{
|
|
|
|
CommonName: "ACME Challenge TEMP",
|
|
|
|
},
|
|
|
|
NotBefore: time.Now(),
|
|
|
|
NotAfter: expiration,
|
|
|
|
|
|
|
|
KeyUsage: x509.KeyUsageKeyEncipherment,
|
|
|
|
BasicConstraintsValid: true,
|
|
|
|
ExtraExtensions: extensions,
|
|
|
|
}
|
|
|
|
|
2023-05-02 19:02:18 +02:00
|
|
|
// handling SAN filling as type suspected
|
|
|
|
if ip := net.ParseIP(domain); ip != nil {
|
|
|
|
template.IPAddresses = []net.IP{ip}
|
|
|
|
} else {
|
|
|
|
template.DNSNames = []string{domain}
|
|
|
|
}
|
|
|
|
|
2018-12-06 23:50:17 +02:00
|
|
|
return x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
|
|
|
|
}
|