linkedca.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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) StoreCertificateChain(prov provisioner.Interface, fullchain ...*x509.Certificate) error {
  211. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  212. defer cancel()
  213. _, err := c.client.PostCertificate(ctx, &linkedca.CertificateRequest{
  214. PemCertificate: serializeCertificateChain(fullchain[0]),
  215. PemCertificateChain: serializeCertificateChain(fullchain[1:]...),
  216. Provisioner: createProvisionerIdentity(prov),
  217. })
  218. return errors.Wrap(err, "error posting certificate")
  219. }
  220. func (c *linkedCaClient) StoreRenewedCertificate(parent *x509.Certificate, fullchain ...*x509.Certificate) error {
  221. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  222. defer cancel()
  223. _, err := c.client.PostCertificate(ctx, &linkedca.CertificateRequest{
  224. PemCertificate: serializeCertificateChain(fullchain[0]),
  225. PemCertificateChain: serializeCertificateChain(fullchain[1:]...),
  226. PemParentCertificate: serializeCertificateChain(parent),
  227. })
  228. return errors.Wrap(err, "error posting certificate")
  229. }
  230. func (c *linkedCaClient) StoreSSHCertificate(crt *ssh.Certificate) error {
  231. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  232. defer cancel()
  233. _, err := c.client.PostSSHCertificate(ctx, &linkedca.SSHCertificateRequest{
  234. Certificate: string(ssh.MarshalAuthorizedKey(crt)),
  235. })
  236. return errors.Wrap(err, "error posting ssh certificate")
  237. }
  238. func (c *linkedCaClient) Revoke(crt *x509.Certificate, rci *db.RevokedCertificateInfo) error {
  239. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  240. defer cancel()
  241. _, err := c.client.RevokeCertificate(ctx, &linkedca.RevokeCertificateRequest{
  242. Serial: rci.Serial,
  243. PemCertificate: serializeCertificate(crt),
  244. Reason: rci.Reason,
  245. ReasonCode: linkedca.RevocationReasonCode(rci.ReasonCode),
  246. Passive: true,
  247. })
  248. return errors.Wrap(err, "error revoking certificate")
  249. }
  250. func (c *linkedCaClient) RevokeSSH(cert *ssh.Certificate, rci *db.RevokedCertificateInfo) error {
  251. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  252. defer cancel()
  253. _, err := c.client.RevokeSSHCertificate(ctx, &linkedca.RevokeSSHCertificateRequest{
  254. Serial: rci.Serial,
  255. Certificate: serializeSSHCertificate(cert),
  256. Reason: rci.Reason,
  257. ReasonCode: linkedca.RevocationReasonCode(rci.ReasonCode),
  258. Passive: true,
  259. })
  260. return errors.Wrap(err, "error revoking ssh certificate")
  261. }
  262. func (c *linkedCaClient) IsRevoked(serial string) (bool, error) {
  263. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  264. defer cancel()
  265. resp, err := c.client.GetCertificateStatus(ctx, &linkedca.GetCertificateStatusRequest{
  266. Serial: serial,
  267. })
  268. if err != nil {
  269. return false, errors.Wrap(err, "error getting certificate status")
  270. }
  271. return resp.Status != linkedca.RevocationStatus_ACTIVE, nil
  272. }
  273. func (c *linkedCaClient) IsSSHRevoked(serial string) (bool, error) {
  274. ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
  275. defer cancel()
  276. resp, err := c.client.GetSSHCertificateStatus(ctx, &linkedca.GetSSHCertificateStatusRequest{
  277. Serial: serial,
  278. })
  279. if err != nil {
  280. return false, errors.Wrap(err, "error getting certificate status")
  281. }
  282. return resp.Status != linkedca.RevocationStatus_ACTIVE, nil
  283. }
  284. func createProvisionerIdentity(prov provisioner.Interface) *linkedca.ProvisionerIdentity {
  285. if prov == nil {
  286. return nil
  287. }
  288. return &linkedca.ProvisionerIdentity{
  289. Id: prov.GetID(),
  290. Type: linkedca.Provisioner_Type(prov.GetType()),
  291. Name: prov.GetName(),
  292. }
  293. }
  294. func serializeCertificate(crt *x509.Certificate) string {
  295. if crt == nil {
  296. return ""
  297. }
  298. return string(pem.EncodeToMemory(&pem.Block{
  299. Type: "CERTIFICATE",
  300. Bytes: crt.Raw,
  301. }))
  302. }
  303. func serializeCertificateChain(fullchain ...*x509.Certificate) string {
  304. var chain string
  305. for _, crt := range fullchain {
  306. chain += string(pem.EncodeToMemory(&pem.Block{
  307. Type: "CERTIFICATE",
  308. Bytes: crt.Raw,
  309. }))
  310. }
  311. return chain
  312. }
  313. func serializeSSHCertificate(crt *ssh.Certificate) string {
  314. if crt == nil {
  315. return ""
  316. }
  317. return string(ssh.MarshalAuthorizedKey(crt))
  318. }
  319. func getAuthority(sans []string) (string, error) {
  320. for _, s := range sans {
  321. if strings.HasPrefix(s, "urn:smallstep:authority:") {
  322. if regexp.MustCompile(uuidPattern).MatchString(s[24:]) {
  323. return s[24:], nil
  324. }
  325. }
  326. }
  327. return "", fmt.Errorf("error parsing token: invalid sans claim")
  328. }
  329. // getRootCertificate creates an insecure majordomo client and returns the
  330. // verified root certificate.
  331. func getRootCertificate(endpoint, fingerprint string) (*x509.Certificate, error) {
  332. ctx, cancel := context.WithCancel(context.Background())
  333. defer cancel()
  334. conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
  335. InsecureSkipVerify: true,
  336. })))
  337. if err != nil {
  338. return nil, errors.Wrapf(err, "error connecting %s", endpoint)
  339. }
  340. ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
  341. defer cancel()
  342. client := linkedca.NewMajordomoClient(conn)
  343. resp, err := client.GetRootCertificate(ctx, &linkedca.GetRootCertificateRequest{
  344. Fingerprint: fingerprint,
  345. })
  346. if err != nil {
  347. return nil, fmt.Errorf("error getting root certificate: %w", err)
  348. }
  349. var block *pem.Block
  350. b := []byte(resp.PemCertificate)
  351. for len(b) > 0 {
  352. block, b = pem.Decode(b)
  353. if block == nil {
  354. break
  355. }
  356. if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
  357. continue
  358. }
  359. cert, err := x509.ParseCertificate(block.Bytes)
  360. if err != nil {
  361. return nil, fmt.Errorf("error parsing certificate: %w", err)
  362. }
  363. // verify the sha256
  364. sum := sha256.Sum256(cert.Raw)
  365. if !strings.EqualFold(fingerprint, hex.EncodeToString(sum[:])) {
  366. return nil, fmt.Errorf("error verifying certificate: SHA256 fingerprint does not match")
  367. }
  368. return cert, nil
  369. }
  370. return nil, fmt.Errorf("error getting root certificate: certificate not found")
  371. }
  372. // login creates a new majordomo client with just the root ca pool and returns
  373. // the signed certificate and tls configuration.
  374. func login(authority, token string, csr *x509.CertificateRequest, signer crypto.PrivateKey, endpoint string, rootCAs *x509.CertPool) (*tls.Certificate, *tls.Config, error) {
  375. // Connect to majordomo
  376. ctx, cancel := context.WithCancel(context.Background())
  377. defer cancel()
  378. conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
  379. RootCAs: rootCAs,
  380. })))
  381. if err != nil {
  382. return nil, nil, errors.Wrapf(err, "error connecting %s", endpoint)
  383. }
  384. // Login to get the signed certificate
  385. ctx, cancel = context.WithTimeout(context.Background(), 15*time.Second)
  386. defer cancel()
  387. client := linkedca.NewMajordomoClient(conn)
  388. resp, err := client.Login(ctx, &linkedca.LoginRequest{
  389. AuthorityId: authority,
  390. Token: token,
  391. PemCertificateRequest: string(pem.EncodeToMemory(&pem.Block{
  392. Type: "CERTIFICATE REQUEST",
  393. Bytes: csr.Raw,
  394. })),
  395. })
  396. if err != nil {
  397. return nil, nil, errors.Wrapf(err, "error logging in %s", endpoint)
  398. }
  399. // Parse login response
  400. var block *pem.Block
  401. var bundle []*x509.Certificate
  402. rest := []byte(resp.PemCertificateChain)
  403. for {
  404. block, rest = pem.Decode(rest)
  405. if block == nil {
  406. break
  407. }
  408. if block.Type != "CERTIFICATE" {
  409. return nil, nil, errors.New("error decoding login response: pemCertificateChain is not a certificate bundle")
  410. }
  411. crt, err := x509.ParseCertificate(block.Bytes)
  412. if err != nil {
  413. return nil, nil, errors.Wrap(err, "error parsing login response")
  414. }
  415. bundle = append(bundle, crt)
  416. }
  417. if len(bundle) == 0 {
  418. return nil, nil, errors.New("error decoding login response: pemCertificateChain should not be empty")
  419. }
  420. // Build tls.Certificate with PemCertificate and intermediates in the
  421. // PemCertificateChain
  422. cert := &tls.Certificate{
  423. PrivateKey: signer,
  424. }
  425. rest = []byte(resp.PemCertificate)
  426. for {
  427. block, rest = pem.Decode(rest)
  428. if block == nil {
  429. break
  430. }
  431. if block.Type == "CERTIFICATE" {
  432. leaf, err := x509.ParseCertificate(block.Bytes)
  433. if err != nil {
  434. return nil, nil, errors.Wrap(err, "error parsing pemCertificate")
  435. }
  436. cert.Certificate = append(cert.Certificate, block.Bytes)
  437. cert.Leaf = leaf
  438. }
  439. }
  440. // Add intermediates to the tls.Certificate
  441. last := len(bundle) - 1
  442. for i := 0; i < last; i++ {
  443. cert.Certificate = append(cert.Certificate, bundle[i].Raw)
  444. }
  445. // Add root to the pool if it's not there yet
  446. rootCAs.AddCert(bundle[last])
  447. return cert, &tls.Config{
  448. RootCAs: rootCAs,
  449. }, nil
  450. }