config.go 14 KB

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