linkedca.go 15 KB

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