linkedca.go 14 KB

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