2020-07-03 16:09:17 +01:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
2021-10-19 10:17:42 +02:00
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
2020-07-03 16:09:17 +01:00
|
|
|
"crypto/x509"
|
2021-10-19 10:17:42 +02:00
|
|
|
"crypto/x509/pkix"
|
2020-07-03 16:09:17 +01:00
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2021-10-19 10:17:42 +02:00
|
|
|
"math/big"
|
|
|
|
"net"
|
|
|
|
"time"
|
2020-07-03 16:09:17 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func GetCertPool(paths []string) (*x509.CertPool, error) {
|
|
|
|
if len(paths) == 0 {
|
|
|
|
return nil, fmt.Errorf("invalid empty list of Root CAs file paths")
|
|
|
|
}
|
|
|
|
pool := x509.NewCertPool()
|
|
|
|
for _, path := range paths {
|
2020-07-20 18:49:45 -07:00
|
|
|
// Cert paths are a configurable option
|
2020-07-19 22:24:18 -07:00
|
|
|
data, err := ioutil.ReadFile(path) // #nosec G304
|
2020-07-03 16:09:17 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("certificate authority file (%s) could not be read - %s", path, err)
|
|
|
|
}
|
|
|
|
if !pool.AppendCertsFromPEM(data) {
|
|
|
|
return nil, fmt.Errorf("loading certificate authority (%s) failed", path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return pool, nil
|
|
|
|
}
|
2021-10-19 10:17:42 +02:00
|
|
|
|
|
|
|
// https://golang.org/src/crypto/tls/generate_cert.go as a function
|
|
|
|
func GenerateCert() ([]byte, []byte, error) {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
keyBytes, err := x509.MarshalPKCS8PrivateKey(priv)
|
|
|
|
if err != nil {
|
|
|
|
return nil, keyBytes, err
|
|
|
|
}
|
|
|
|
|
|
|
|
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
|
|
|
if err != nil {
|
|
|
|
return nil, keyBytes, err
|
|
|
|
}
|
|
|
|
|
|
|
|
notBefore := time.Now()
|
|
|
|
template := x509.Certificate{
|
|
|
|
SerialNumber: serialNumber,
|
|
|
|
Subject: pkix.Name{
|
|
|
|
Organization: []string{"OAuth2 Proxy Test Suite"},
|
|
|
|
},
|
|
|
|
NotBefore: notBefore,
|
|
|
|
NotAfter: notBefore.Add(time.Hour),
|
|
|
|
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
|
|
|
|
|
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
|
|
|
|
|
|
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
|
|
|
}
|
|
|
|
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
|
|
|
|
return certBytes, keyBytes, err
|
|
|
|
}
|