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