pki.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. package pki
  2. import (
  3. "crypto"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "encoding/json"
  8. "encoding/pem"
  9. "fmt"
  10. "html"
  11. "net"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "github.com/pkg/errors"
  17. "github.com/smallstep/certificates/authority"
  18. "github.com/smallstep/certificates/authority/provisioner"
  19. "github.com/smallstep/certificates/ca"
  20. "github.com/smallstep/certificates/db"
  21. "github.com/smallstep/cli/config"
  22. "github.com/smallstep/cli/crypto/keys"
  23. "github.com/smallstep/cli/crypto/pemutil"
  24. "github.com/smallstep/cli/crypto/tlsutil"
  25. "github.com/smallstep/cli/crypto/x509util"
  26. "github.com/smallstep/cli/errs"
  27. "github.com/smallstep/cli/jose"
  28. "github.com/smallstep/cli/ui"
  29. "github.com/smallstep/cli/utils"
  30. "golang.org/x/crypto/ssh"
  31. )
  32. const (
  33. // ConfigPath is the directory name under the step path where the configuration
  34. // files will be stored.
  35. configPath = "config"
  36. // PublicPath is the directory name under the step path where the public keys
  37. // will be stored.
  38. publicPath = "certs"
  39. // PublicPath is the directory name under the step path where the private keys
  40. // will be stored.
  41. privatePath = "secrets"
  42. // DBPath is the directory name under the step path where the private keys
  43. // will be stored.
  44. dbPath = "db"
  45. // templatesPath is the directory to store templates
  46. templatesPath = "templates"
  47. )
  48. // GetDBPath returns the path where the file-system persistence is stored
  49. // based on the STEPPATH environment variable.
  50. func GetDBPath() string {
  51. return filepath.Join(config.StepPath(), dbPath)
  52. }
  53. // GetConfigPath returns the directory where the configuration files are stored
  54. // based on the STEPPATH environment variable.
  55. func GetConfigPath() string {
  56. return filepath.Join(config.StepPath(), configPath)
  57. }
  58. // GetPublicPath returns the directory where the public keys are stored based on
  59. // the STEPPATH environment variable.
  60. func GetPublicPath() string {
  61. return filepath.Join(config.StepPath(), publicPath)
  62. }
  63. // GetSecretsPath returns the directory where the private keys are stored based
  64. // on the STEPPATH environment variable.
  65. func GetSecretsPath() string {
  66. return filepath.Join(config.StepPath(), privatePath)
  67. }
  68. // GetRootCAPath returns the path where the root CA is stored based on the
  69. // STEPPATH environment variable.
  70. func GetRootCAPath() string {
  71. return filepath.Join(config.StepPath(), publicPath, "root_ca.crt")
  72. }
  73. // GetOTTKeyPath returns the path where the one-time token key is stored based
  74. // on the STEPPATH environment variable.
  75. func GetOTTKeyPath() string {
  76. return filepath.Join(config.StepPath(), privatePath, "ott_key")
  77. }
  78. // GetTemplatesPath returns the path where the templates are stored.
  79. func GetTemplatesPath() string {
  80. return filepath.Join(config.StepPath(), templatesPath)
  81. }
  82. // GetProvisioners returns the map of provisioners on the given CA.
  83. func GetProvisioners(caURL, rootFile string) (provisioner.List, error) {
  84. if len(rootFile) == 0 {
  85. rootFile = GetRootCAPath()
  86. }
  87. client, err := ca.NewClient(caURL, ca.WithRootFile(rootFile))
  88. if err != nil {
  89. return nil, err
  90. }
  91. cursor := ""
  92. provisioners := provisioner.List{}
  93. for {
  94. resp, err := client.Provisioners(ca.WithProvisionerCursor(cursor), ca.WithProvisionerLimit(100))
  95. if err != nil {
  96. return nil, err
  97. }
  98. provisioners = append(provisioners, resp.Provisioners...)
  99. if resp.NextCursor == "" {
  100. return provisioners, nil
  101. }
  102. cursor = resp.NextCursor
  103. }
  104. }
  105. // GetProvisionerKey returns the encrypted provisioner key with the for the
  106. // given kid.
  107. func GetProvisionerKey(caURL, rootFile, kid string) (string, error) {
  108. if len(rootFile) == 0 {
  109. rootFile = GetRootCAPath()
  110. }
  111. client, err := ca.NewClient(caURL, ca.WithRootFile(rootFile))
  112. if err != nil {
  113. return "", err
  114. }
  115. resp, err := client.ProvisionerKey(kid)
  116. if err != nil {
  117. return "", err
  118. }
  119. return resp.Key, nil
  120. }
  121. // PKI represents the Public Key Infrastructure used by a certificate authority.
  122. type PKI struct {
  123. root, rootKey, rootFingerprint string
  124. intermediate, intermediateKey string
  125. sshHostPubKey, sshHostKey string
  126. sshUserPubKey, sshUserKey string
  127. config, defaults string
  128. ottPublicKey *jose.JSONWebKey
  129. ottPrivateKey *jose.JSONWebEncryption
  130. provisioner string
  131. address string
  132. dnsNames []string
  133. caURL string
  134. enableSSH bool
  135. }
  136. // New creates a new PKI configuration.
  137. func New() (*PKI, error) {
  138. public := GetPublicPath()
  139. private := GetSecretsPath()
  140. config := GetConfigPath()
  141. // Create directories
  142. dirs := []string{public, private, config, GetTemplatesPath()}
  143. for _, name := range dirs {
  144. if _, err := os.Stat(name); os.IsNotExist(err) {
  145. if err = os.MkdirAll(name, 0700); err != nil {
  146. return nil, errs.FileError(err, name)
  147. }
  148. }
  149. }
  150. // get absolute path for dir/name
  151. getPath := func(dir string, name string) (string, error) {
  152. s, err := filepath.Abs(filepath.Join(dir, name))
  153. return s, errors.Wrapf(err, "error getting absolute path for %s", name)
  154. }
  155. var err error
  156. p := &PKI{
  157. provisioner: "step-cli",
  158. address: "127.0.0.1:9000",
  159. dnsNames: []string{"127.0.0.1"},
  160. }
  161. if p.root, err = getPath(public, "root_ca.crt"); err != nil {
  162. return nil, err
  163. }
  164. if p.rootKey, err = getPath(private, "root_ca_key"); err != nil {
  165. return nil, err
  166. }
  167. if p.intermediate, err = getPath(public, "intermediate_ca.crt"); err != nil {
  168. return nil, err
  169. }
  170. if p.intermediateKey, err = getPath(private, "intermediate_ca_key"); err != nil {
  171. return nil, err
  172. }
  173. if p.sshHostPubKey, err = getPath(public, "ssh_host_key.pub"); err != nil {
  174. return nil, err
  175. }
  176. if p.sshUserPubKey, err = getPath(public, "ssh_user_key.pub"); err != nil {
  177. return nil, err
  178. }
  179. if p.sshHostKey, err = getPath(private, "ssh_host_key"); err != nil {
  180. return nil, err
  181. }
  182. if p.sshUserKey, err = getPath(private, "ssh_user_key"); err != nil {
  183. return nil, err
  184. }
  185. if len(config) > 0 {
  186. if p.config, err = getPath(config, "ca.json"); err != nil {
  187. return nil, err
  188. }
  189. if p.defaults, err = getPath(config, "defaults.json"); err != nil {
  190. return nil, err
  191. }
  192. }
  193. return p, nil
  194. }
  195. // GetCAConfigPath returns the path of the CA configuration file.
  196. func (p *PKI) GetCAConfigPath() string {
  197. return p.config
  198. }
  199. // GetRootFingerprint returns the root fingerprint.
  200. func (p *PKI) GetRootFingerprint() string {
  201. return p.rootFingerprint
  202. }
  203. // SetProvisioner sets the provisioner name of the OTT keys.
  204. func (p *PKI) SetProvisioner(s string) {
  205. p.provisioner = s
  206. }
  207. // SetAddress sets the listening address of the CA.
  208. func (p *PKI) SetAddress(s string) {
  209. p.address = s
  210. }
  211. // SetDNSNames sets the dns names of the CA.
  212. func (p *PKI) SetDNSNames(s []string) {
  213. p.dnsNames = s
  214. }
  215. // SetCAURL sets the ca-url to use in the defaults.json.
  216. func (p *PKI) SetCAURL(s string) {
  217. p.caURL = s
  218. }
  219. // GenerateKeyPairs generates the key pairs used by the certificate authority.
  220. func (p *PKI) GenerateKeyPairs(pass []byte) error {
  221. var err error
  222. // Create OTT key pair, the user doesn't need to know about this.
  223. p.ottPublicKey, p.ottPrivateKey, err = jose.GenerateDefaultKeyPair(pass)
  224. if err != nil {
  225. return err
  226. }
  227. return nil
  228. }
  229. // GenerateRootCertificate generates a root certificate with the given name.
  230. func (p *PKI) GenerateRootCertificate(name string, pass []byte) (*x509.Certificate, interface{}, error) {
  231. rootProfile, err := x509util.NewRootProfile(name)
  232. if err != nil {
  233. return nil, nil, err
  234. }
  235. rootBytes, err := rootProfile.CreateWriteCertificate(p.root, p.rootKey, string(pass))
  236. if err != nil {
  237. return nil, nil, err
  238. }
  239. rootCrt, err := x509.ParseCertificate(rootBytes)
  240. if err != nil {
  241. return nil, nil, errors.Wrap(err, "error parsing root certificate")
  242. }
  243. sum := sha256.Sum256(rootCrt.Raw)
  244. p.rootFingerprint = strings.ToLower(hex.EncodeToString(sum[:]))
  245. return rootCrt, rootProfile.SubjectPrivateKey(), nil
  246. }
  247. // WriteRootCertificate writes to disk the given certificate and key.
  248. func (p *PKI) WriteRootCertificate(rootCrt *x509.Certificate, rootKey interface{}, pass []byte) error {
  249. if err := utils.WriteFile(p.root, pem.EncodeToMemory(&pem.Block{
  250. Type: "CERTIFICATE",
  251. Bytes: rootCrt.Raw,
  252. }), 0600); err != nil {
  253. return err
  254. }
  255. _, err := pemutil.Serialize(rootKey, pemutil.WithPassword([]byte(pass)), pemutil.ToFile(p.rootKey, 0600))
  256. if err != nil {
  257. return err
  258. }
  259. return nil
  260. }
  261. // GenerateIntermediateCertificate generates an intermediate certificate with
  262. // the given name.
  263. func (p *PKI) GenerateIntermediateCertificate(name string, rootCrt *x509.Certificate, rootKey interface{}, pass []byte) error {
  264. interProfile, err := x509util.NewIntermediateProfile(name, rootCrt, rootKey)
  265. if err != nil {
  266. return err
  267. }
  268. _, err = interProfile.CreateWriteCertificate(p.intermediate, p.intermediateKey, string(pass))
  269. return err
  270. }
  271. // GenerateSSHSigningKeys generates and encrypts a private key used for signing
  272. // SSH user certificates and a private key used for signing host certificates.
  273. func (p *PKI) GenerateSSHSigningKeys(password []byte) error {
  274. var pubNames = []string{p.sshHostPubKey, p.sshUserPubKey}
  275. var privNames = []string{p.sshHostKey, p.sshUserKey}
  276. for i := 0; i < 2; i++ {
  277. pub, priv, err := keys.GenerateDefaultKeyPair()
  278. if err != nil {
  279. return err
  280. }
  281. if _, ok := priv.(crypto.Signer); !ok {
  282. return errors.Errorf("key of type %T is not a crypto.Signer", priv)
  283. }
  284. sshKey, err := ssh.NewPublicKey(pub)
  285. if err != nil {
  286. return errors.Wrapf(err, "error converting public key")
  287. }
  288. _, err = pemutil.Serialize(priv, pemutil.WithFilename(privNames[i]), pemutil.WithPassword(password))
  289. if err != nil {
  290. return err
  291. }
  292. if err = utils.WriteFile(pubNames[i], ssh.MarshalAuthorizedKey(sshKey), 0600); err != nil {
  293. return err
  294. }
  295. }
  296. p.enableSSH = true
  297. return nil
  298. }
  299. func (p *PKI) askFeedback() {
  300. ui.Println()
  301. ui.Printf("\033[1mFEEDBACK\033[0m %s %s\n",
  302. html.UnescapeString("&#"+strconv.Itoa(128525)+";"),
  303. html.UnescapeString("&#"+strconv.Itoa(127867)+";"))
  304. ui.Println(" The \033[1mstep\033[0m utility is not instrumented for usage statistics. It does not")
  305. ui.Println(" phone home. But your feedback is extremely valuable. Any information you")
  306. ui.Println(" can provide regarding how you’re using `step` helps. Please send us a")
  307. ui.Println(" sentence or two, good or bad: \033[1mfeedback@smallstep.com\033[0m or join")
  308. ui.Println(" \033[1mhttps://gitter.im/smallstep/community\033[0m.")
  309. }
  310. // TellPKI outputs the locations of public and private keys generated
  311. // generated for a new PKI. Generally this will consist of a root certificate
  312. // and key and an intermediate certificate and key.
  313. func (p *PKI) TellPKI() {
  314. p.tellPKI()
  315. p.askFeedback()
  316. }
  317. func (p *PKI) tellPKI() {
  318. ui.Println()
  319. ui.PrintSelected("Root certificate", p.root)
  320. ui.PrintSelected("Root private key", p.rootKey)
  321. ui.PrintSelected("Root fingerprint", p.rootFingerprint)
  322. ui.PrintSelected("Intermediate certificate", p.intermediate)
  323. ui.PrintSelected("Intermediate private key", p.intermediateKey)
  324. if p.enableSSH {
  325. ui.PrintSelected("SSH user root certificate", p.sshUserPubKey)
  326. ui.PrintSelected("SSH user root private key", p.sshUserKey)
  327. ui.PrintSelected("SSH host root certificate", p.sshHostPubKey)
  328. ui.PrintSelected("SSH host root private key", p.sshHostKey)
  329. }
  330. }
  331. type caDefaults struct {
  332. CAUrl string `json:"ca-url"`
  333. CAConfig string `json:"ca-config"`
  334. Fingerprint string `json:"fingerprint"`
  335. Root string `json:"root"`
  336. }
  337. // Option is the type for modifiers over the auth config object.
  338. type Option func(c *authority.Config) error
  339. // WithDefaultDB is a configuration modifier that adds a default DB stanza to
  340. // the authority config.
  341. func WithDefaultDB() Option {
  342. return func(c *authority.Config) error {
  343. c.DB = &db.Config{
  344. Type: "badger",
  345. DataSource: GetDBPath(),
  346. }
  347. return nil
  348. }
  349. }
  350. // WithoutDB is a configuration modifier that adds a default DB stanza to
  351. // the authority config.
  352. func WithoutDB() Option {
  353. return func(c *authority.Config) error {
  354. c.DB = nil
  355. return nil
  356. }
  357. }
  358. // GenerateConfig returns the step certificates configuration.
  359. func (p *PKI) GenerateConfig(opt ...Option) (*authority.Config, error) {
  360. key, err := p.ottPrivateKey.CompactSerialize()
  361. if err != nil {
  362. return nil, errors.Wrap(err, "error serializing private key")
  363. }
  364. prov := &provisioner.JWK{
  365. Name: p.provisioner,
  366. Type: "JWK",
  367. Key: p.ottPublicKey,
  368. EncryptedKey: key,
  369. }
  370. config := &authority.Config{
  371. Root: []string{p.root},
  372. FederatedRoots: []string{},
  373. IntermediateCert: p.intermediate,
  374. IntermediateKey: p.intermediateKey,
  375. Address: p.address,
  376. DNSNames: p.dnsNames,
  377. Logger: []byte(`{"format": "text"}`),
  378. DB: &db.Config{
  379. Type: "badger",
  380. DataSource: GetDBPath(),
  381. },
  382. AuthorityConfig: &authority.AuthConfig{
  383. DisableIssuedAtCheck: false,
  384. Provisioners: provisioner.List{prov},
  385. },
  386. TLS: &tlsutil.TLSOptions{
  387. MinVersion: x509util.DefaultTLSMinVersion,
  388. MaxVersion: x509util.DefaultTLSMaxVersion,
  389. Renegotiation: x509util.DefaultTLSRenegotiation,
  390. CipherSuites: x509util.DefaultTLSCipherSuites,
  391. },
  392. Templates: p.getTemplates(),
  393. }
  394. if p.enableSSH {
  395. enableSSHCA := true
  396. config.SSH = &authority.SSHConfig{
  397. HostKey: p.sshHostKey,
  398. UserKey: p.sshUserKey,
  399. }
  400. prov.Claims = &provisioner.Claims{
  401. EnableSSHCA: &enableSSHCA,
  402. }
  403. }
  404. // Apply configuration modifiers
  405. for _, o := range opt {
  406. if err = o(config); err != nil {
  407. return nil, err
  408. }
  409. }
  410. return config, nil
  411. }
  412. // Save stores the pki on a json file that will be used as the certificate
  413. // authority configuration.
  414. func (p *PKI) Save(opt ...Option) error {
  415. p.tellPKI()
  416. // Generate and write ca.json
  417. config, err := p.GenerateConfig(opt...)
  418. if err != nil {
  419. return err
  420. }
  421. b, err := json.MarshalIndent(config, "", " ")
  422. if err != nil {
  423. return errors.Wrapf(err, "error marshaling %s", p.config)
  424. }
  425. if err = utils.WriteFile(p.config, b, 0644); err != nil {
  426. return errs.FileError(err, p.config)
  427. }
  428. // Generate the CA URL.
  429. if p.caURL == "" {
  430. p.caURL = p.dnsNames[0]
  431. var port string
  432. _, port, err = net.SplitHostPort(p.address)
  433. if err != nil {
  434. return errors.Wrapf(err, "error parsing %s", p.address)
  435. }
  436. if port == "443" {
  437. p.caURL = fmt.Sprintf("https://%s", p.caURL)
  438. } else {
  439. p.caURL = fmt.Sprintf("https://%s:%s", p.caURL, port)
  440. }
  441. }
  442. // Generate and write defaults.json
  443. defaults := &caDefaults{
  444. Root: p.root,
  445. CAConfig: p.config,
  446. CAUrl: p.caURL,
  447. Fingerprint: p.rootFingerprint,
  448. }
  449. b, err = json.MarshalIndent(defaults, "", " ")
  450. if err != nil {
  451. return errors.Wrapf(err, "error marshaling %s", p.defaults)
  452. }
  453. if err = utils.WriteFile(p.defaults, b, 0644); err != nil {
  454. return errs.FileError(err, p.defaults)
  455. }
  456. // Generate and write templates
  457. if err := generateTemplates(config.Templates); err != nil {
  458. return err
  459. }
  460. if config.DB != nil {
  461. ui.PrintSelected("Database folder", config.DB.DataSource)
  462. }
  463. if config.Templates != nil {
  464. ui.PrintSelected("Templates folder", GetTemplatesPath())
  465. }
  466. ui.PrintSelected("Default configuration", p.defaults)
  467. ui.PrintSelected("Certificate Authority configuration", p.config)
  468. ui.Println()
  469. ui.Println("Your PKI is ready to go. To generate certificates for individual services see 'step help ca'.")
  470. p.askFeedback()
  471. return nil
  472. }