config.go 14 KB

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