config.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package config
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "os"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/linkedca"
  11. kms "go.step.sm/crypto/kms/apiv1"
  12. "github.com/smallstep/certificates/authority/policy"
  13. "github.com/smallstep/certificates/authority/provisioner"
  14. cas "github.com/smallstep/certificates/cas/apiv1"
  15. "github.com/smallstep/certificates/db"
  16. "github.com/smallstep/certificates/templates"
  17. )
  18. const (
  19. legacyAuthority = "step-certificate-authority"
  20. )
  21. var (
  22. // DefaultBackdate length of time to backdate certificates to avoid
  23. // clock skew validation issues.
  24. DefaultBackdate = time.Minute
  25. // DefaultDisableRenewal disables renewals per provisioner.
  26. DefaultDisableRenewal = false
  27. // DefaultAllowRenewalAfterExpiry allows renewals even if the certificate is
  28. // expired.
  29. DefaultAllowRenewalAfterExpiry = false
  30. // DefaultEnableSSHCA enable SSH CA features per provisioner or globally
  31. // for all provisioners.
  32. DefaultEnableSSHCA = false
  33. // DefaultDisableSmallstepExtensions is the default value for the
  34. // DisableSmallstepExtensions provisioner claim.
  35. DefaultDisableSmallstepExtensions = false
  36. // DefaultCRLCacheDuration is the default cache duration for the CRL.
  37. DefaultCRLCacheDuration = &provisioner.Duration{Duration: 24 * time.Hour}
  38. // DefaultCRLExpiredDuration is the default duration in which expired
  39. // certificates will remain in the CRL after expiration.
  40. DefaultCRLExpiredDuration = time.Hour
  41. // GlobalProvisionerClaims is the default duration that expired certificates
  42. // remain in the CRL after expiration.
  43. GlobalProvisionerClaims = provisioner.Claims{
  44. MinTLSDur: &provisioner.Duration{Duration: 5 * time.Minute}, // TLS certs
  45. MaxTLSDur: &provisioner.Duration{Duration: 24 * time.Hour},
  46. DefaultTLSDur: &provisioner.Duration{Duration: 24 * time.Hour},
  47. MinUserSSHDur: &provisioner.Duration{Duration: 5 * time.Minute}, // User SSH certs
  48. MaxUserSSHDur: &provisioner.Duration{Duration: 24 * time.Hour},
  49. DefaultUserSSHDur: &provisioner.Duration{Duration: 16 * time.Hour},
  50. MinHostSSHDur: &provisioner.Duration{Duration: 5 * time.Minute}, // Host SSH certs
  51. MaxHostSSHDur: &provisioner.Duration{Duration: 30 * 24 * time.Hour},
  52. DefaultHostSSHDur: &provisioner.Duration{Duration: 30 * 24 * time.Hour},
  53. EnableSSHCA: &DefaultEnableSSHCA,
  54. DisableRenewal: &DefaultDisableRenewal,
  55. AllowRenewalAfterExpiry: &DefaultAllowRenewalAfterExpiry,
  56. DisableSmallstepExtensions: &DefaultDisableSmallstepExtensions,
  57. }
  58. )
  59. // Config represents the CA configuration and it's mapped to a JSON object.
  60. type Config struct {
  61. Root multiString `json:"root"`
  62. FederatedRoots []string `json:"federatedRoots"`
  63. IntermediateCert string `json:"crt"`
  64. IntermediateKey string `json:"key"`
  65. Address string `json:"address"`
  66. InsecureAddress string `json:"insecureAddress"`
  67. DNSNames []string `json:"dnsNames"`
  68. KMS *kms.Options `json:"kms,omitempty"`
  69. SSH *SSHConfig `json:"ssh,omitempty"`
  70. Logger json.RawMessage `json:"logger,omitempty"`
  71. DB *db.Config `json:"db,omitempty"`
  72. Monitoring json.RawMessage `json:"monitoring,omitempty"`
  73. AuthorityConfig *AuthConfig `json:"authority,omitempty"`
  74. TLS *TLSOptions `json:"tls,omitempty"`
  75. Password string `json:"password,omitempty"`
  76. Templates *templates.Templates `json:"templates,omitempty"`
  77. CommonName string `json:"commonName,omitempty"`
  78. CRL *CRLConfig `json:"crl,omitempty"`
  79. MetricsAddress string `json:"metricsAddress,omitempty"`
  80. SkipValidation bool `json:"-"`
  81. // Keeps record of the filename the Config is read from
  82. loadedFromFilepath string
  83. }
  84. // CRLConfig represents config options for CRL generation
  85. type CRLConfig struct {
  86. Enabled bool `json:"enabled"`
  87. GenerateOnRevoke bool `json:"generateOnRevoke,omitempty"`
  88. CacheDuration *provisioner.Duration `json:"cacheDuration,omitempty"`
  89. RenewPeriod *provisioner.Duration `json:"renewPeriod,omitempty"`
  90. IDPurl string `json:"idpURL,omitempty"`
  91. }
  92. // IsEnabled returns if the CRL is enabled.
  93. func (c *CRLConfig) IsEnabled() bool {
  94. return c != nil && c.Enabled
  95. }
  96. // Validate validates the CRL configuration.
  97. func (c *CRLConfig) Validate() error {
  98. if c == nil {
  99. return nil
  100. }
  101. if c.CacheDuration != nil && c.CacheDuration.Duration < 0 {
  102. return errors.New("crl.cacheDuration must be greater than or equal to 0")
  103. }
  104. if c.RenewPeriod != nil && c.RenewPeriod.Duration < 0 {
  105. return errors.New("crl.renewPeriod must be greater than or equal to 0")
  106. }
  107. if c.RenewPeriod != nil && c.CacheDuration != nil &&
  108. c.RenewPeriod.Duration > c.CacheDuration.Duration {
  109. return errors.New("crl.cacheDuration must be greater than or equal to crl.renewPeriod")
  110. }
  111. return nil
  112. }
  113. // TickerDuration the renewal ticker duration. This is set by renewPeriod, of it
  114. // is not set is ~2/3 of cacheDuration.
  115. func (c *CRLConfig) TickerDuration() time.Duration {
  116. if !c.IsEnabled() {
  117. return 0
  118. }
  119. if c.RenewPeriod != nil && c.RenewPeriod.Duration > 0 {
  120. return c.RenewPeriod.Duration
  121. }
  122. return (c.CacheDuration.Duration / 3) * 2
  123. }
  124. // ASN1DN contains ASN1.DN attributes that are used in Subject and Issuer
  125. // x509 Certificate blocks.
  126. type ASN1DN struct {
  127. Country string `json:"country,omitempty"`
  128. Organization string `json:"organization,omitempty"`
  129. OrganizationalUnit string `json:"organizationalUnit,omitempty"`
  130. Locality string `json:"locality,omitempty"`
  131. Province string `json:"province,omitempty"`
  132. StreetAddress string `json:"streetAddress,omitempty"`
  133. SerialNumber string `json:"serialNumber,omitempty"`
  134. CommonName string `json:"commonName,omitempty"`
  135. }
  136. // AuthConfig represents the configuration options for the authority. An
  137. // underlying registration authority can also be configured using the
  138. // cas.Options.
  139. type AuthConfig struct {
  140. *cas.Options
  141. AuthorityID string `json:"authorityId,omitempty"`
  142. DeploymentType string `json:"deploymentType,omitempty"`
  143. Provisioners provisioner.List `json:"provisioners,omitempty"`
  144. Admins []*linkedca.Admin `json:"-"`
  145. Template *ASN1DN `json:"template,omitempty"`
  146. Claims *provisioner.Claims `json:"claims,omitempty"`
  147. Policy *policy.Options `json:"policy,omitempty"`
  148. DisableIssuedAtCheck bool `json:"disableIssuedAtCheck,omitempty"`
  149. Backdate *provisioner.Duration `json:"backdate,omitempty"`
  150. EnableAdmin bool `json:"enableAdmin,omitempty"`
  151. DisableGetSSHHosts bool `json:"disableGetSSHHosts,omitempty"`
  152. }
  153. // init initializes the required fields in the AuthConfig if they are not
  154. // provided.
  155. func (c *AuthConfig) init() {
  156. if c.Provisioners == nil {
  157. c.Provisioners = provisioner.List{}
  158. }
  159. if c.Template == nil {
  160. c.Template = &ASN1DN{}
  161. }
  162. if c.Backdate == nil {
  163. c.Backdate = &provisioner.Duration{
  164. Duration: DefaultBackdate,
  165. }
  166. }
  167. }
  168. // Validate validates the authority configuration.
  169. func (c *AuthConfig) Validate(provisioner.Audiences) error {
  170. if c == nil {
  171. return errors.New("authority cannot be undefined")
  172. }
  173. // Initialize required fields.
  174. c.init()
  175. // Check that only one K8sSA is enabled
  176. var k8sCount int
  177. for _, p := range c.Provisioners {
  178. if p.GetType() == provisioner.TypeK8sSA {
  179. k8sCount++
  180. }
  181. }
  182. if k8sCount > 1 {
  183. return errors.New("cannot have more than one kubernetes service account provisioner")
  184. }
  185. if c.Backdate.Duration < 0 {
  186. return errors.New("authority.backdate cannot be less than 0")
  187. }
  188. return nil
  189. }
  190. // LoadConfiguration parses the given filename in JSON format and returns the
  191. // configuration struct.
  192. func LoadConfiguration(filename string) (*Config, error) {
  193. f, err := os.Open(filename)
  194. if err != nil {
  195. return nil, errors.Wrapf(err, "error opening %s", filename)
  196. }
  197. defer f.Close()
  198. var c Config
  199. if err := json.NewDecoder(f).Decode(&c); err != nil {
  200. return nil, errors.Wrapf(err, "error parsing %s", filename)
  201. }
  202. // store filename that was read to populate Config
  203. c.loadedFromFilepath = filename
  204. // initialize the Config
  205. c.Init()
  206. return &c, nil
  207. }
  208. // Init initializes the minimal configuration required to create an authority. This
  209. // is mainly used on embedded authorities.
  210. func (c *Config) Init() {
  211. if c.DNSNames == nil {
  212. c.DNSNames = []string{"localhost", "127.0.0.1", "::1"}
  213. }
  214. if c.TLS == nil {
  215. c.TLS = &DefaultTLSOptions
  216. }
  217. if c.AuthorityConfig == nil {
  218. c.AuthorityConfig = &AuthConfig{}
  219. }
  220. if c.CommonName == "" {
  221. c.CommonName = "Step Online CA"
  222. }
  223. if c.CRL != nil && c.CRL.Enabled && c.CRL.CacheDuration == nil {
  224. c.CRL.CacheDuration = DefaultCRLCacheDuration
  225. }
  226. c.AuthorityConfig.init()
  227. }
  228. // Save saves the configuration to the given filename.
  229. func (c *Config) Save(filename string) error {
  230. var b bytes.Buffer
  231. enc := json.NewEncoder(&b)
  232. enc.SetIndent("", "\t")
  233. if err := enc.Encode(c); err != nil { //nolint:gosec // config struct contains password field by design
  234. return fmt.Errorf("error encoding configuration: %w", err)
  235. }
  236. if err := os.WriteFile(filename, b.Bytes(), 0600); err != nil {
  237. return fmt.Errorf("error writing %q: %w", filename, err)
  238. }
  239. return nil
  240. }
  241. // Commit saves the current configuration to the same
  242. // file it was initially loaded from.
  243. //
  244. // TODO(hs): rename Save() to WriteTo() and replace this
  245. // with Save()? Or is Commit clear enough.
  246. func (c *Config) Commit() error {
  247. if !c.WasLoadedFromFile() {
  248. return errors.New("cannot commit configuration if not loaded from file")
  249. }
  250. return c.Save(c.loadedFromFilepath)
  251. }
  252. // WasLoadedFromFile returns whether or not the Config was
  253. // loaded from a file.
  254. func (c *Config) WasLoadedFromFile() bool {
  255. return c.loadedFromFilepath != ""
  256. }
  257. // Filepath returns the path to the file the Config was
  258. // loaded from.
  259. func (c *Config) Filepath() string {
  260. return c.loadedFromFilepath
  261. }
  262. // Validate validates the configuration.
  263. func (c *Config) Validate() error {
  264. switch {
  265. case c.SkipValidation:
  266. return nil
  267. case c.Address == "":
  268. return errors.New("address cannot be empty")
  269. case len(c.DNSNames) == 0:
  270. return errors.New("dnsNames cannot be empty")
  271. case c.AuthorityConfig == nil:
  272. return errors.New("authority cannot be nil")
  273. }
  274. // Options holds the RA/CAS configuration.
  275. ra := c.AuthorityConfig.Options
  276. // The default RA/CAS requires root, crt and key.
  277. if ra.Is(cas.SoftCAS) {
  278. switch {
  279. case c.Root.HasEmpties():
  280. return errors.New("root cannot be empty")
  281. case c.IntermediateCert == "":
  282. return errors.New("crt cannot be empty")
  283. case c.IntermediateKey == "":
  284. return errors.New("key cannot be empty")
  285. }
  286. }
  287. // Validate address (a port is required)
  288. if _, _, err := net.SplitHostPort(c.Address); err != nil {
  289. return errors.Errorf("invalid address %s", c.Address)
  290. }
  291. if addr := c.MetricsAddress; addr != "" {
  292. if _, _, err := net.SplitHostPort(addr); err != nil {
  293. return errors.Errorf("invalid metrics address %q", c.Address)
  294. }
  295. }
  296. if c.TLS == nil {
  297. c.TLS = &DefaultTLSOptions
  298. } else {
  299. if len(c.TLS.CipherSuites) == 0 {
  300. c.TLS.CipherSuites = DefaultTLSOptions.CipherSuites
  301. }
  302. if c.TLS.MaxVersion == 0 {
  303. c.TLS.MaxVersion = DefaultTLSOptions.MaxVersion
  304. }
  305. if c.TLS.MinVersion == 0 {
  306. c.TLS.MinVersion = DefaultTLSOptions.MinVersion
  307. }
  308. if c.TLS.MinVersion > c.TLS.MaxVersion {
  309. return errors.New("tls minVersion cannot exceed tls maxVersion")
  310. }
  311. c.TLS.Renegotiation = c.TLS.Renegotiation || DefaultTLSOptions.Renegotiation
  312. }
  313. // Validate KMS options, nil is ok.
  314. if err := c.KMS.Validate(); err != nil {
  315. return err
  316. }
  317. // Validate RA/CAS options, nil is ok.
  318. if err := ra.Validate(); err != nil {
  319. return err
  320. }
  321. // Validate ssh: nil is ok
  322. if err := c.SSH.Validate(); err != nil {
  323. return err
  324. }
  325. // Validate templates: nil is ok
  326. if err := c.Templates.Validate(); err != nil {
  327. return err
  328. }
  329. // Validate crl config: nil is ok
  330. if err := c.CRL.Validate(); err != nil {
  331. return err
  332. }
  333. return c.AuthorityConfig.Validate(c.GetAudiences())
  334. }
  335. // GetAudiences returns the legacy and possible urls without the ports that will
  336. // be used as the default provisioner audiences. The CA might have proxies in
  337. // front so we cannot rely on the port.
  338. func (c *Config) GetAudiences() provisioner.Audiences {
  339. audiences := provisioner.Audiences{
  340. Sign: []string{legacyAuthority},
  341. Revoke: []string{legacyAuthority},
  342. SSHSign: []string{},
  343. SSHRevoke: []string{},
  344. SSHRenew: []string{},
  345. }
  346. for _, name := range c.DNSNames {
  347. hostname := toHostname(name)
  348. audiences.Sign = append(audiences.Sign,
  349. fmt.Sprintf("https://%s/1.0/sign", hostname),
  350. fmt.Sprintf("https://%s/sign", hostname),
  351. fmt.Sprintf("https://%s/1.0/ssh/sign", hostname),
  352. fmt.Sprintf("https://%s/ssh/sign", hostname))
  353. audiences.Renew = append(audiences.Renew,
  354. fmt.Sprintf("https://%s/1.0/renew", hostname),
  355. fmt.Sprintf("https://%s/renew", hostname))
  356. audiences.Revoke = append(audiences.Revoke,
  357. fmt.Sprintf("https://%s/1.0/revoke", hostname),
  358. fmt.Sprintf("https://%s/revoke", hostname))
  359. audiences.SSHSign = append(audiences.SSHSign,
  360. fmt.Sprintf("https://%s/1.0/ssh/sign", hostname),
  361. fmt.Sprintf("https://%s/ssh/sign", hostname),
  362. fmt.Sprintf("https://%s/1.0/sign", hostname),
  363. fmt.Sprintf("https://%s/sign", hostname))
  364. audiences.SSHRevoke = append(audiences.SSHRevoke,
  365. fmt.Sprintf("https://%s/1.0/ssh/revoke", hostname),
  366. fmt.Sprintf("https://%s/ssh/revoke", hostname))
  367. audiences.SSHRenew = append(audiences.SSHRenew,
  368. fmt.Sprintf("https://%s/1.0/ssh/renew", hostname),
  369. fmt.Sprintf("https://%s/ssh/renew", hostname))
  370. audiences.SSHRekey = append(audiences.SSHRekey,
  371. fmt.Sprintf("https://%s/1.0/ssh/rekey", hostname),
  372. fmt.Sprintf("https://%s/ssh/rekey", hostname))
  373. }
  374. return audiences
  375. }
  376. // Audience returns the list of audiences for a given path.
  377. func (c *Config) Audience(path string) []string {
  378. audiences := make([]string, len(c.DNSNames)+1)
  379. for i, name := range c.DNSNames {
  380. hostname := toHostname(name)
  381. audiences[i] = "https://" + hostname + path
  382. }
  383. // For backward compatibility
  384. audiences[len(c.DNSNames)] = path
  385. return audiences
  386. }
  387. func toHostname(name string) string {
  388. // ensure an IPv6 address is represented with square brackets when used as hostname
  389. if ip := net.ParseIP(name); ip != nil && ip.To4() == nil {
  390. name = "[" + name + "]"
  391. }
  392. return name
  393. }