vaultcas.go 9.5 KB

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