linkedca.go 14 KB

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