config.go 14 KB

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