1
0
mirror of https://github.com/ribbybibby/ssl_exporter.git synced 2024-11-30 08:36:46 +02:00
ssl_exporter/test/test.go
Rob Best 801179eae7
Move to a modules/probers model, like the blackbox_exporter. (#34)
There are a number of reasons for this change:
- Modules allow a single instance of the exporter to be configured with numerous
different tls configs. Previously you had to run a different exporter for each
combination.
- Adding new and more complicated options to the exporter should be easier with
modules than if I was to go down the route of accepting configuration directly through url params
- I prefer defining a specific prober (https,tcp) over using the URL to guess
what the user wants
2020-06-17 16:29:21 +01:00

67 lines
2.0 KiB
Go

package test
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"net"
"time"
)
// GenerateTestCertificate generates a test certificate with the given expiry date
func GenerateTestCertificate(expiry time.Time) ([]byte, []byte) {
privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(fmt.Sprintf("Error creating rsa key: %s", err))
}
publickey := &privatekey.PublicKey
cert := x509.Certificate{
IsCA: true,
BasicConstraintsValid: true,
SubjectKeyId: []byte{1},
SerialNumber: big.NewInt(100),
Subject: pkix.Name{
CommonName: "example.ribbybibby.me",
Organization: []string{"ribbybibby"},
OrganizationalUnit: []string{"ribbybibbys org"},
},
EmailAddresses: []string{"me@ribbybibby.me", "example@ribbybibby.me"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
DNSNames: []string{"example.ribbybibby.me", "example-2.ribbybibby.me", "example-3.ribbybibby.me"},
NotBefore: time.Now(),
NotAfter: expiry,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
}
derCert, err := x509.CreateCertificate(rand.Reader, &cert, &cert, publickey, privatekey)
if err != nil {
panic(fmt.Sprintf("Error signing test-certificate: %s", err))
}
pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derCert})
pemKey := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privatekey)})
return pemCert, pemKey
}
// WriteFile writes some content to a temporary file
func WriteFile(filename string, contents []byte) (string, error) {
tmpFile, err := ioutil.TempFile("", filename)
if err != nil {
return tmpFile.Name(), err
}
if _, err := tmpFile.Write(contents); err != nil {
return tmpFile.Name(), err
}
if err := tmpFile.Close(); err != nil {
return tmpFile.Name(), err
}
return tmpFile.Name(), nil
}