linkedca.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/sha256"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/hex"
  9. "encoding/pem"
  10. "fmt"
  11. "net/url"
  12. "regexp"
  13. "strings"
  14. "time"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/certificates/authority/admin"
  17. "github.com/smallstep/certificates/db"
  18. "go.step.sm/crypto/jose"
  19. "go.step.sm/crypto/keyutil"
  20. "go.step.sm/crypto/tlsutil"
  21. "go.step.sm/crypto/x509util"
  22. "go.step.sm/linkedca"
  23. "golang.org/x/crypto/ssh"
  24. "google.golang.org/grpc"
  25. "google.golang.org/grpc/credentials"
  26. )
  27. const uuidPattern = "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
  28. type linkedCaClient struct {
  29. renewer *tlsutil.Renewer
  30. client linkedca.MajordomoClient
  31. authorityID string
  32. }
  33. // interface guard
  34. var _ admin.DB = (*linkedCaClient)(nil)
  35. type linkedCAClaims struct {
  36. jose.Claims
  37. SANs []string `json:"sans"`
  38. SHA string `json:"sha"`
  39. }
  40. func newLinkedCAClient(token string) (*linkedCaClient, error) {
  41. tok, err := jose.ParseSigned(token)
  42. if err != nil {
  43. return nil, errors.Wrap(err, "error parsing token")
  44. }
  45. var claims linkedCAClaims
  46. if err := tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
  47. return nil, errors.Wrap(err, "error parsing token")
  48. }
  49. // Validate claims
  50. if len(claims.Audience) != 1 {
  51. return nil, errors.New("error parsing token: invalid aud claim")
  52. }
  53. if claims.SHA == "" {
  54. return nil, errors.New("error parsing token: invalid sha claim")
  55. }
  56. // Get linkedCA endpoint from audience.
  57. u, err := url.Parse(claims.Audience[0])
  58. if err != nil {
  59. return nil, errors.New("error parsing token: invalid aud claim")
  60. }
  61. // Get authority from SANs
  62. authority, err := getAuthority(claims.SANs)
  63. if err != nil {
  64. return nil, err
  65. }
  66. // Create csr to login with
  67. signer, err := keyutil.GenerateDefaultSigner()
  68. if err != nil {
  69. return nil, err
  70. }
  71. csr, err := x509util.CreateCertificateRequest(claims.Subject, claims.SANs, signer)
  72. if err != nil {
  73. return nil, err
  74. }
  75. // Get and verify root certificate
  76. root, err := getRootCertificate(u.Host, claims.SHA)
  77. if err != nil {
  78. return nil, err
  79. }
  80. pool := x509.NewCertPool()
  81. pool.AddCert(root)
  82. // Login with majordomo and get certificates
  83. cert, tlsConfig, err := login(authority, token, csr, signer, u.Host, pool)
  84. if err != nil {
  85. return nil, err
  86. }
  87. // Start TLS renewer and set the GetClientCertificate callback to it.
  88. renewer, err := tlsutil.NewRenewer(cert, tlsConfig, func() (*tls.Certificate, *tls.Config, error) {
  89. return login(authority, token, csr, signer, u.Host, pool)
  90. })
  91. if err != nil {
  92. return nil, err
  93. }
  94. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  95. // Start mTLS client
  96. conn, err := grpc.Dial(u.Host, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
  97. if err != nil {
  98. return nil, errors.Wrapf(err, "error connecting %s", u.Host)
  99. }
  100. return &linkedCaClient{
  101. renewer: renewer,
  102. client: linkedca.NewMajordomoClient(conn),
  103. authorityID: authority,
  104. }, nil
  105. }
  106. func (c *linkedCaClient) Run() {
  107. c.renewer.Run()
  108. }
  109. func (c *linkedCaClient) Stop() {
  110. c.renewer.Stop()
  111. }
  112. func (c *linkedCaClient) CreateProvisioner(ctx context.Context, prov *linkedca.Provisioner) error {
  113. resp, err := c.client.CreateProvisioner(ctx, &linkedca.CreateProvisionerRequest{
  114. Type: prov.Type,
  115. Name: prov.Name,
  116. Details: prov.Details,
  117. Claims: prov.Claims,
  118. X509Template: prov.X509Template,
  119. SshTemplate: prov.SshTemplate,
  120. })
  121. if err != nil {
  122. return errors.Wrap(err, "error creating provisioner")
  123. }
  124. prov.Id = resp.Id
  125. prov.AuthorityId = resp.AuthorityId
  126. return nil
  127. }
  128. func (c *linkedCaClient) GetProvisioner(ctx context.Context, id string) (*linkedca.Provisioner, error) {
  129. resp, err := c.client.GetProvisioner(ctx, &linkedca.GetProvisionerRequest{
  130. Id: id,
  131. })
  132. if err != nil {
  133. return nil, errors.Wrap(err, "error getting provisioners")
  134. }
  135. return resp, nil
  136. }
  137. func (c *linkedCaClient) GetProvisioners(ctx context.Context) ([]*linkedca.Provisioner, error) {
  138. resp, err := c.client.GetConfiguration(ctx, &linkedca.ConfigurationRequest{
  139. AuthorityId: c.authorityID,
  140. })
  141. if err != nil {
  142. return nil, errors.Wrap(err, "error getting provisioners")
  143. }
  144. return resp.Provisioners, nil
  145. }
  146. func (c *linkedCaClient) UpdateProvisioner(ctx context.Context, prov *linkedca.Provisioner) error {
  147. _, err := c.client.UpdateProvisioner(ctx, &linkedca.UpdateProvisionerRequest{
  148. Id: prov.Id,
  149. Name: prov.Name,
  150. Details: prov.Details,
  151. Claims: prov.Claims,
  152. X509Template: prov.X509Template,
  153. SshTemplate: prov.SshTemplate,
  154. })
  155. return errors.Wrap(err, "error updating provisioner")
  156. }
  157. func (c *linkedCaClient) DeleteProvisioner(ctx context.Context, id string) error {
  158. _, err := c.client.DeleteProvisioner(ctx, &linkedca.DeleteProvisionerRequest{
  159. Id: id,
  160. })
  161. return errors.Wrap(err, "error deleting provisioner")
  162. }
  163. func (c *linkedCaClient) CreateAdmin(ctx context.Context, adm *linkedca.Admin) error {
  164. resp, err := c.client.CreateAdmin(ctx, &linkedca.CreateAdminRequest{
  165. Subject: adm.Subject,
  166. ProvisionerId: adm.ProvisionerId,
  167. Type: adm.Type,
  168. })
  169. if err != nil {
  170. return errors.Wrap(err, "error creating admin")
  171. }
  172. adm.Id = resp.Id
  173. adm.AuthorityId = resp.AuthorityId
  174. return nil
  175. }
  176. func (c *linkedCaClient) GetAdmin(ctx context.Context, id string) (*linkedca.Admin, error) {
  177. resp, err := c.client.GetAdmin(ctx, &linkedca.GetAdminRequest{
  178. Id: id,
  179. })
  180. if err != nil {
  181. return nil, errors.Wrap(err, "error getting admins")
  182. }
  183. return resp, nil
  184. }
  185. func (c *linkedCaClient) GetAdmins(ctx context.Context) ([]*linkedca.Admin, error) {
  186. resp, err := c.client.GetConfiguration(ctx, &linkedca.ConfigurationRequest{
  187. AuthorityId: c.authorityID,
  188. })
  189. if err != nil {
  190. return nil, errors.Wrap(err, "error getting admins")
  191. }
  192. return resp.Admins, nil
  193. }
  194. func (c *linkedCaClient) UpdateAdmin(ctx context.Context, adm *linkedca.Admin) error {
  195. _, err := c.client.UpdateAdmin(ctx, &linkedca.UpdateAdminRequest{
  196. Id: adm.Id,
  197. Type: adm.Type,
  198. })
  199. return errors.Wrap(err, "error updating admin")
  200. }
  201. func (c *linkedCaClient) DeleteAdmin(ctx context.Context, id string) error {
  202. _, err := c.client.DeleteAdmin(ctx, &linkedca.DeleteAdminRequest{
  203. Id: id,
  204. })
  205. return errors.Wrap(err, "error deleting admin")
  206. }
  207. func (c *linkedCaClient) StoreCertificateChain(fullchain ...*x509.Certificate) error {
  208. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  209. defer cancel()
  210. _, err := c.client.PostCertificate(ctx, &linkedca.CertificateRequest{
  211. PemCertificate: serializeCertificateChain(fullchain[0]),
  212. PemCertificateChain: serializeCertificateChain(fullchain[1:]...),
  213. })
  214. return errors.Wrap(err, "error posting certificate")
  215. }
  216. func (c *linkedCaClient) StoreRenewedCertificate(parent *x509.Certificate, fullchain ...*x509.Certificate) error {
  217. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  218. defer cancel()
  219. _, err := c.client.PostCertificate(ctx, &linkedca.CertificateRequest{
  220. PemCertificate: serializeCertificateChain(fullchain[0]),
  221. PemCertificateChain: serializeCertificateChain(fullchain[1:]...),
  222. PemParentCertificate: serializeCertificateChain(parent),
  223. })
  224. return errors.Wrap(err, "error posting certificate")
  225. }
  226. func (c *linkedCaClient) StoreSSHCertificate(crt *ssh.Certificate) error {
  227. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  228. defer cancel()
  229. _, err := c.client.PostSSHCertificate(ctx, &linkedca.SSHCertificateRequest{
  230. Certificate: string(ssh.MarshalAuthorizedKey(crt)),
  231. })
  232. return errors.Wrap(err, "error posting ssh certificate")
  233. }
  234. func (c *linkedCaClient) Revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  235. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  236. defer cancel()
  237. _, err := c.client.RevokeCertificate(ctx, &linkedca.RevokeCertificateRequest{
  238. Serial: rci.Serial,
  239. PemCertificate: serializeCertificate(crt),
  240. Reason: rci.Reason,
  241. ReasonCode: linkedca.RevocationReasonCode(rci.ReasonCode),
  242. Passive: true,
  243. })
  244. return errors.Wrap(err, "error revoking certificate")
  245. }
  246. func (c *linkedCaClient) RevokeSSH(cert *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  247. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  248. defer cancel()
  249. _, err := c.client.RevokeSSHCertificate(ctx, &linkedca.RevokeSSHCertificateRequest{
  250. Serial: rci.Serial,
  251. Certificate: serializeSSHCertificate(cert),
  252. Reason: rci.Reason,
  253. ReasonCode: linkedca.RevocationReasonCode(rci.ReasonCode),
  254. Passive: true,
  255. })
  256. return errors.Wrap(err, "error revoking ssh certificate")
  257. }
  258. func (c *linkedCaClient) IsRevoked(serial string) (bool, error) {
  259. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  260. defer cancel()
  261. resp, err := c.client.GetCertificateStatus(ctx, &linkedca.GetCertificateStatusRequest{
  262. Serial: serial,
  263. })
  264. if err != nil {
  265. return false, errors.Wrap(err, "error getting certificate status")
  266. }
  267. return resp.Status != linkedca.RevocationStatus_ACTIVE, nil
  268. }
  269. func (c *linkedCaClient) IsSSHRevoked(serial string) (bool, error) {
  270. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  271. defer cancel()
  272. resp, err := c.client.GetSSHCertificateStatus(ctx, &linkedca.GetSSHCertificateStatusRequest{
  273. Serial: serial,
  274. })
  275. if err != nil {
  276. return false, errors.Wrap(err, "error getting certificate status")
  277. }
  278. return resp.Status != linkedca.RevocationStatus_ACTIVE, nil
  279. }
  280. func (c *linkedCaClient) CreateAuthorityPolicy(ctx context.Context, policy *linkedca.Policy) error {
  281. return errors.New("not implemented yet")
  282. }
  283. func (c *linkedCaClient) GetAuthorityPolicy(ctx context.Context) (*linkedca.Policy, error) {
  284. return nil, errors.New("not implemented yet")
  285. }
  286. func (c *linkedCaClient) UpdateAuthorityPolicy(ctx context.Context, policy *linkedca.Policy) error {
  287. return errors.New("not implemented yet")
  288. }
  289. func (c *linkedCaClient) DeleteAuthorityPolicy(ctx context.Context) error {
  290. return errors.New("not implemented yet")
  291. }
  292. func serializeCertificate(crt *x509.Certificate) string {
  293. if crt == nil {
  294. return ""
  295. }
  296. return string(pem.EncodeToMemory(&pem.Block{
  297. Type: "CERTIFICATE",
  298. Bytes: crt.Raw,
  299. }))
  300. }
  301. func serializeCertificateChain(fullchain ...*x509.Certificate) string {
  302. var chain string
  303. for _, crt := range fullchain {
  304. chain += string(pem.EncodeToMemory(&pem.Block{
  305. Type: "CERTIFICATE",
  306. Bytes: crt.Raw,
  307. }))
  308. }
  309. return chain
  310. }
  311. func serializeSSHCertificate(crt *ssh.Certificate) string {
  312. if crt == nil {
  313. return ""
  314. }
  315. return string(ssh.MarshalAuthorizedKey(crt))
  316. }
  317. func getAuthority(sans []string) (string, error) {
  318. for _, s := range sans {
  319. if strings.HasPrefix(s, "urn:smallstep:authority:") {
  320. if regexp.MustCompile(uuidPattern).MatchString(s[24:]) {
  321. return s[24:], nil
  322. }
  323. }
  324. }
  325. return "", fmt.Errorf("error parsing token: invalid sans claim")
  326. }
  327. // getRootCertificate creates an insecure majordomo client and returns the
  328. // verified root certificate.
  329. func getRootCertificate(endpoint, fingerprint string) (*x509.Certificate, error) {
  330. ctx, cancel := context.WithCancel(context.Background())
  331. defer cancel()
  332. conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
  333. InsecureSkipVerify: true,
  334. })))
  335. if err != nil {
  336. return nil, errors.Wrapf(err, "error connecting %s", endpoint)
  337. }
  338. ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
  339. defer cancel()
  340. client := linkedca.NewMajordomoClient(conn)
  341. resp, err := client.GetRootCertificate(ctx, &linkedca.GetRootCertificateRequest{
  342. Fingerprint: fingerprint,
  343. })
  344. if err != nil {
  345. return nil, fmt.Errorf("error getting root certificate: %w", err)
  346. }
  347. var block *pem.Block
  348. b := []byte(resp.PemCertificate)
  349. for len(b) > 0 {
  350. block, b = pem.Decode(b)
  351. if block == nil {
  352. break
  353. }
  354. if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
  355. continue
  356. }
  357. cert, err := x509.ParseCertificate(block.Bytes)
  358. if err != nil {
  359. return nil, fmt.Errorf("error parsing certificate: %w", err)
  360. }
  361. // verify the sha256
  362. sum := sha256.Sum256(cert.Raw)
  363. if !strings.EqualFold(fingerprint, hex.EncodeToString(sum[:])) {
  364. return nil, fmt.Errorf("error verifying certificate: SHA256 fingerprint does not match")
  365. }
  366. return cert, nil
  367. }
  368. return nil, fmt.Errorf("error getting root certificate: certificate not found")
  369. }
  370. // login creates a new majordomo client with just the root ca pool and returns
  371. // the signed certificate and tls configuration.
  372. func login(authority, token string, csr *x509.CertificateRequest, signer crypto.PrivateKey, endpoint string, rootCAs *x509.CertPool) (*tls.Certificate, *tls.Config, error) {
  373. // Connect to majordomo
  374. ctx, cancel := context.WithCancel(context.Background())
  375. defer cancel()
  376. conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
  377. RootCAs: rootCAs,
  378. })))
  379. if err != nil {
  380. return nil, nil, errors.Wrapf(err, "error connecting %s", endpoint)
  381. }
  382. // Login to get the signed certificate
  383. ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
  384. defer cancel()
  385. client := linkedca.NewMajordomoClient(conn)
  386. resp, err := client.Login(ctx, &linkedca.LoginRequest{
  387. AuthorityId: authority,
  388. Token: token,
  389. PemCertificateRequest: string(pem.EncodeToMemory(&pem.Block{
  390. Type: "CERTIFICATE REQUEST",
  391. Bytes: csr.Raw,
  392. })),
  393. })
  394. if err != nil {
  395. return nil, nil, errors.Wrapf(err, "error logging in %s", endpoint)
  396. }
  397. // Parse login response
  398. var block *pem.Block
  399. var bundle []*x509.Certificate
  400. rest := []byte(resp.PemCertificateChain)
  401. for {
  402. block, rest = pem.Decode(rest)
  403. if block == nil {
  404. break
  405. }
  406. if block.Type != "CERTIFICATE" {
  407. return nil, nil, errors.New("error decoding login response: pemCertificateChain is not a certificate bundle")
  408. }
  409. crt, err := x509.ParseCertificate(block.Bytes)
  410. if err != nil {
  411. return nil, nil, errors.Wrap(err, "error parsing login response")
  412. }
  413. bundle = append(bundle, crt)
  414. }
  415. if len(bundle) == 0 {
  416. return nil, nil, errors.New("error decoding login response: pemCertificateChain should not be empty")
  417. }
  418. // Build tls.Certificate with PemCertificate and intermediates in the
  419. // PemCertificateChain
  420. cert := &tls.Certificate{
  421. PrivateKey: signer,
  422. }
  423. rest = []byte(resp.PemCertificate)
  424. for {
  425. block, rest = pem.Decode(rest)
  426. if block == nil {
  427. break
  428. }
  429. if block.Type == "CERTIFICATE" {
  430. leaf, err := x509.ParseCertificate(block.Bytes)
  431. if err != nil {
  432. return nil, nil, errors.Wrap(err, "error parsing pemCertificate")
  433. }
  434. cert.Certificate = append(cert.Certificate, block.Bytes)
  435. cert.Leaf = leaf
  436. }
  437. }
  438. // Add intermediates to the tls.Certificate
  439. last := len(bundle) - 1
  440. for i := 0; i < last; i++ {
  441. cert.Certificate = append(cert.Certificate, bundle[i].Raw)
  442. }
  443. // Add root to the pool if it's not there yet
  444. rootCAs.AddCert(bundle[last])
  445. return cert, &tls.Config{
  446. RootCAs: rootCAs,
  447. }, nil
  448. }