vaultcas.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package vaultcas
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "encoding/json"
  9. "encoding/pem"
  10. "errors"
  11. "fmt"
  12. "math/big"
  13. "strings"
  14. "time"
  15. "github.com/smallstep/certificates/cas/apiv1"
  16. "github.com/smallstep/certificates/cas/vaultcas/auth/approle"
  17. "github.com/smallstep/certificates/cas/vaultcas/auth/kubernetes"
  18. vault "github.com/hashicorp/vault/api"
  19. )
  20. func init() {
  21. apiv1.Register(apiv1.VaultCAS, func(ctx context.Context, opts apiv1.Options) (apiv1.CertificateAuthorityService, error) {
  22. return New(ctx, opts)
  23. })
  24. }
  25. // VaultOptions defines the configuration options added using the
  26. // apiv1.Options.Config field.
  27. type VaultOptions struct {
  28. PKIMountPath string `json:"pkiMountPath,omitempty"`
  29. PKIRoleDefault string `json:"pkiRoleDefault,omitempty"`
  30. PKIRoleRSA string `json:"pkiRoleRSA,omitempty"`
  31. PKIRoleEC string `json:"pkiRoleEC,omitempty"`
  32. PKIRoleEd25519 string `json:"pkiRoleEd25519,omitempty"`
  33. AuthType string `json:"authType,omitempty"`
  34. AuthMountPath string `json:"authMountPath,omitempty"`
  35. AuthOptions json.RawMessage `json:"authOptions,omitempty"`
  36. }
  37. // VaultCAS implements a Certificate Authority Service using Hashicorp Vault.
  38. type VaultCAS struct {
  39. client *vault.Client
  40. config VaultOptions
  41. fingerprint string
  42. }
  43. type certBundle struct {
  44. leaf *x509.Certificate
  45. intermediates []*x509.Certificate
  46. root *x509.Certificate
  47. }
  48. // New creates a new CertificateAuthorityService implementation
  49. // using Hashicorp Vault
  50. func New(ctx context.Context, opts apiv1.Options) (*VaultCAS, error) {
  51. if opts.CertificateAuthority == "" {
  52. return nil, errors.New("vaultCAS 'certificateAuthority' cannot be empty")
  53. }
  54. if opts.CertificateAuthorityFingerprint == "" {
  55. return nil, errors.New("vaultCAS 'certificateAuthorityFingerprint' cannot be empty")
  56. }
  57. vc, err := loadOptions(opts.Config)
  58. if err != nil {
  59. return nil, err
  60. }
  61. config := vault.DefaultConfig()
  62. config.Address = opts.CertificateAuthority
  63. client, err := vault.NewClient(config)
  64. if err != nil {
  65. return nil, fmt.Errorf("unable to initialize vault client: %w", err)
  66. }
  67. var method vault.AuthMethod
  68. switch vc.AuthType {
  69. case "kubernetes":
  70. method, err = kubernetes.NewKubernetesAuthMethod(vc.AuthMountPath, vc.AuthOptions)
  71. case "approle":
  72. method, err = approle.NewApproleAuthMethod(vc.AuthMountPath, vc.AuthOptions)
  73. default:
  74. return nil, fmt.Errorf("unknown auth type: %s, only 'kubernetes' and 'approle' currently supported", vc.AuthType)
  75. }
  76. if err != nil {
  77. return nil, fmt.Errorf("unable to configure %s auth method: %w", vc.AuthType, err)
  78. }
  79. authInfo, err := client.Auth().Login(ctx, method)
  80. if err != nil {
  81. return nil, fmt.Errorf("unable to login to %s auth method: %w", vc.AuthType, err)
  82. }
  83. if authInfo == nil {
  84. return nil, errors.New("no auth info was returned after login")
  85. }
  86. return &VaultCAS{
  87. client: client,
  88. config: *vc,
  89. fingerprint: opts.CertificateAuthorityFingerprint,
  90. }, nil
  91. }
  92. // CreateCertificate signs a new certificate using Hashicorp Vault.
  93. func (v *VaultCAS) CreateCertificate(req *apiv1.CreateCertificateRequest) (*apiv1.CreateCertificateResponse, error) {
  94. switch {
  95. case req.CSR == nil:
  96. return nil, errors.New("createCertificate `csr` cannot be nil")
  97. case req.Lifetime == 0:
  98. return nil, errors.New("createCertificate `lifetime` cannot be 0")
  99. }
  100. cert, chain, err := v.createCertificate(req.CSR, req.Lifetime)
  101. if err != nil {
  102. return nil, err
  103. }
  104. return &apiv1.CreateCertificateResponse{
  105. Certificate: cert,
  106. CertificateChain: chain,
  107. }, nil
  108. }
  109. // GetCertificateAuthority returns the root certificate of the certificate
  110. // authority using the configured fingerprint.
  111. func (v *VaultCAS) GetCertificateAuthority(req *apiv1.GetCertificateAuthorityRequest) (*apiv1.GetCertificateAuthorityResponse, error) {
  112. secret, err := v.client.Logical().Read(v.config.PKIMountPath + "/cert/ca_chain")
  113. if err != nil {
  114. return nil, fmt.Errorf("error reading ca chain: %w", err)
  115. }
  116. if secret == nil {
  117. return nil, errors.New("error reading ca chain: response is empty")
  118. }
  119. chain, ok := secret.Data["certificate"].(string)
  120. if !ok {
  121. return nil, errors.New("error unmarshaling vault response: certificate not found")
  122. }
  123. cert, err := getCertificateBundle(chain)
  124. if err != nil {
  125. return nil, err
  126. }
  127. if cert.root == nil {
  128. return nil, errors.New("error unmarshaling vault response: root certificate not found")
  129. }
  130. sum := sha256.Sum256(cert.root.Raw)
  131. if !strings.EqualFold(v.fingerprint, strings.ToLower(hex.EncodeToString(sum[:]))) {
  132. return nil, errors.New("error verifying vault root: fingerprint does not match")
  133. }
  134. return &apiv1.GetCertificateAuthorityResponse{
  135. RootCertificate: cert.root,
  136. }, nil
  137. }
  138. // RenewCertificate will always return a non-implemented error as renewals
  139. // are not supported yet.
  140. func (v *VaultCAS) RenewCertificate(req *apiv1.RenewCertificateRequest) (*apiv1.RenewCertificateResponse, error) {
  141. return nil, apiv1.NotImplementedError{Message: "vaultCAS does not support renewals"}
  142. }
  143. // RevokeCertificate revokes a certificate by serial number.
  144. func (v *VaultCAS) RevokeCertificate(req *apiv1.RevokeCertificateRequest) (*apiv1.RevokeCertificateResponse, error) {
  145. if req.SerialNumber == "" && req.Certificate == nil {
  146. return nil, errors.New("revokeCertificate `serialNumber` or `certificate` are required")
  147. }
  148. var sn *big.Int
  149. if req.SerialNumber != "" {
  150. var ok bool
  151. if sn, ok = new(big.Int).SetString(req.SerialNumber, 10); !ok {
  152. return nil, fmt.Errorf("error parsing serialNumber: %v cannot be converted to big.Int", req.SerialNumber)
  153. }
  154. } else {
  155. sn = req.Certificate.SerialNumber
  156. }
  157. vaultReq := map[string]interface{}{
  158. "serial_number": formatSerialNumber(sn),
  159. }
  160. _, err := v.client.Logical().Write(v.config.PKIMountPath+"/revoke/", vaultReq)
  161. if err != nil {
  162. return nil, fmt.Errorf("error revoking certificate: %w", err)
  163. }
  164. return &apiv1.RevokeCertificateResponse{
  165. Certificate: req.Certificate,
  166. CertificateChain: nil,
  167. }, nil
  168. }
  169. func (v *VaultCAS) createCertificate(cr *x509.CertificateRequest, lifetime time.Duration) (*x509.Certificate, []*x509.Certificate, error) {
  170. var vaultPKIRole string
  171. switch {
  172. case cr.PublicKeyAlgorithm == x509.RSA:
  173. vaultPKIRole = v.config.PKIRoleRSA
  174. case cr.PublicKeyAlgorithm == x509.ECDSA:
  175. vaultPKIRole = v.config.PKIRoleEC
  176. case cr.PublicKeyAlgorithm == x509.Ed25519:
  177. vaultPKIRole = v.config.PKIRoleEd25519
  178. default:
  179. return nil, nil, fmt.Errorf("unsupported public key algorithm %v", cr.PublicKeyAlgorithm)
  180. }
  181. vaultReq := map[string]interface{}{
  182. "csr": string(pem.EncodeToMemory(&pem.Block{
  183. Type: "CERTIFICATE REQUEST",
  184. Bytes: cr.Raw,
  185. })),
  186. "format": "pem_bundle",
  187. "ttl": lifetime.Seconds(),
  188. }
  189. secret, err := v.client.Logical().Write(v.config.PKIMountPath+"/sign/"+vaultPKIRole, vaultReq)
  190. if err != nil {
  191. return nil, nil, fmt.Errorf("error signing certificate: %w", err)
  192. }
  193. if secret == nil {
  194. return nil, nil, errors.New("error signing certificate: response is empty")
  195. }
  196. chain, ok := secret.Data["certificate"].(string)
  197. if !ok {
  198. return nil, nil, errors.New("error unmarshaling vault response: certificate not found")
  199. }
  200. cert, err := getCertificateBundle(chain)
  201. if err != nil {
  202. return nil, nil, err
  203. }
  204. // Return certificate and certificate chain
  205. return cert.leaf, cert.intermediates, nil
  206. }
  207. func loadOptions(config json.RawMessage) (*VaultOptions, error) {
  208. // setup default values
  209. vc := VaultOptions{
  210. PKIMountPath: "pki",
  211. PKIRoleDefault: "default",
  212. }
  213. err := json.Unmarshal(config, &vc)
  214. if err != nil {
  215. return nil, fmt.Errorf("error decoding vaultCAS config: %w", err)
  216. }
  217. if vc.PKIRoleRSA == "" {
  218. vc.PKIRoleRSA = vc.PKIRoleDefault
  219. }
  220. if vc.PKIRoleEC == "" {
  221. vc.PKIRoleEC = vc.PKIRoleDefault
  222. }
  223. if vc.PKIRoleEd25519 == "" {
  224. vc.PKIRoleEd25519 = vc.PKIRoleDefault
  225. }
  226. return &vc, nil
  227. }
  228. func parseCertificates(pemCert string) []*x509.Certificate {
  229. var certs []*x509.Certificate
  230. rest := []byte(pemCert)
  231. var block *pem.Block
  232. for {
  233. block, rest = pem.Decode(rest)
  234. if block == nil {
  235. break
  236. }
  237. cert, err := x509.ParseCertificate(block.Bytes)
  238. if err != nil {
  239. break
  240. }
  241. certs = append(certs, cert)
  242. }
  243. return certs
  244. }
  245. func getCertificateBundle(chain string) (*certBundle, error) {
  246. var root *x509.Certificate
  247. var leaf *x509.Certificate
  248. var intermediates []*x509.Certificate
  249. for _, cert := range parseCertificates(chain) {
  250. switch {
  251. case isRoot(cert):
  252. root = cert
  253. case cert.BasicConstraintsValid && cert.IsCA:
  254. intermediates = append(intermediates, cert)
  255. default:
  256. leaf = cert
  257. }
  258. }
  259. certificate := &certBundle{
  260. root: root,
  261. leaf: leaf,
  262. intermediates: intermediates,
  263. }
  264. return certificate, nil
  265. }
  266. // isRoot returns true if the given certificate is a root certificate.
  267. func isRoot(cert *x509.Certificate) bool {
  268. if cert.BasicConstraintsValid && cert.IsCA {
  269. return cert.CheckSignatureFrom(cert) == nil
  270. }
  271. return false
  272. }
  273. // formatSerialNumber formats a serial number to a dash-separated hexadecimal
  274. // string.
  275. func formatSerialNumber(sn *big.Int) string {
  276. var ret bytes.Buffer
  277. for _, b := range sn.Bytes() {
  278. if ret.Len() > 0 {
  279. ret.WriteString("-")
  280. }
  281. ret.WriteString(hex.EncodeToString([]byte{b}))
  282. }
  283. return ret.String()
  284. }