config.go 14 KB

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