generator.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package cert
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "time"
  7. )
  8. // Artifacts hosts a private key, its corresponding serving certificate and
  9. // the CA certificate that signs the serving certificate.
  10. type Artifacts struct {
  11. // PEM encoded private key
  12. Key []byte
  13. // PEM encoded serving certificate
  14. Cert []byte
  15. // PEM encoded CA private key
  16. CAKey []byte
  17. // PEM encoded CA certificate
  18. CACert []byte
  19. // Resource version of the certs
  20. ResourceVersion string
  21. }
  22. // Generator is an interface to provision the serving certificate.
  23. type Generator interface {
  24. // Generate returns a Artifacts struct.
  25. Generate(CommonName string) (*Artifacts, error)
  26. // SetCA sets the PEM-encoded CA private key and CA cert for signing the generated serving cert.
  27. SetCA(caKey, caCert []byte)
  28. }
  29. // ValidCACert think cert and key are valid if they meet the following requirements:
  30. // - key and cert are valid pair
  31. // - caCert is the root ca of cert
  32. // - cert is for dnsName
  33. // - cert won't expire before time
  34. func ValidCACert(key, cert, caCert []byte, dnsName string, time time.Time) bool {
  35. if len(key) == 0 || len(cert) == 0 || len(caCert) == 0 {
  36. return false
  37. }
  38. // Verify key and cert are valid pair
  39. _, err := tls.X509KeyPair(cert, key)
  40. if err != nil {
  41. return false
  42. }
  43. // Verify cert is valid for at least 1 year.
  44. pool := x509.NewCertPool()
  45. if !pool.AppendCertsFromPEM(caCert) {
  46. return false
  47. }
  48. block, _ := pem.Decode(cert)
  49. if block == nil {
  50. return false
  51. }
  52. c, err := x509.ParseCertificate(block.Bytes)
  53. if err != nil {
  54. return false
  55. }
  56. ops := x509.VerifyOptions{
  57. DNSName: dnsName,
  58. Roots: pool,
  59. CurrentTime: time,
  60. }
  61. _, err = c.Verify(ops)
  62. return err == nil
  63. }