pki.go 15 KB

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