config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "os"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/authority/provisioner"
  10. cas "github.com/smallstep/certificates/cas/apiv1"
  11. "github.com/smallstep/certificates/db"
  12. kms "github.com/smallstep/certificates/kms/apiv1"
  13. "github.com/smallstep/certificates/templates"
  14. "go.step.sm/linkedca"
  15. )
  16. const (
  17. legacyAuthority = "step-certificate-authority"
  18. )
  19. var (
  20. // DefaultBackdate length of time to backdate certificates to avoid
  21. // clock skew validation issues.
  22. DefaultBackdate = time.Minute
  23. // DefaultDisableRenewal disables renewals per provisioner.
  24. DefaultDisableRenewal = false
  25. // DefaultAllowRenewAfterExpiry allows renewals even if the certificate is
  26. // expired.
  27. DefaultAllowRenewAfterExpiry = false
  28. // DefaultEnableSSHCA enable SSH CA features per provisioner or globally
  29. // for all provisioners.
  30. DefaultEnableSSHCA = false
  31. // GlobalProvisionerClaims default claims for the Authority. Can be overridden
  32. // by provisioner specific claims.
  33. GlobalProvisionerClaims = provisioner.Claims{
  34. MinTLSDur: &provisioner.Duration{Duration: 5 * time.Minute}, // TLS certs
  35. MaxTLSDur: &provisioner.Duration{Duration: 24 * time.Hour},
  36. DefaultTLSDur: &provisioner.Duration{Duration: 24 * time.Hour},
  37. MinUserSSHDur: &provisioner.Duration{Duration: 5 * time.Minute}, // User SSH certs
  38. MaxUserSSHDur: &provisioner.Duration{Duration: 24 * time.Hour},
  39. DefaultUserSSHDur: &provisioner.Duration{Duration: 16 * time.Hour},
  40. MinHostSSHDur: &provisioner.Duration{Duration: 5 * time.Minute}, // Host SSH certs
  41. MaxHostSSHDur: &provisioner.Duration{Duration: 30 * 24 * time.Hour},
  42. DefaultHostSSHDur: &provisioner.Duration{Duration: 30 * 24 * time.Hour},
  43. EnableSSHCA: &DefaultEnableSSHCA,
  44. DisableRenewal: &DefaultDisableRenewal,
  45. AllowRenewAfterExpiry: &DefaultAllowRenewAfterExpiry,
  46. }
  47. )
  48. // Config represents the CA configuration and it's mapped to a JSON object.
  49. type Config struct {
  50. Root multiString `json:"root"`
  51. FederatedRoots []string `json:"federatedRoots"`
  52. IntermediateCert string `json:"crt"`
  53. IntermediateKey string `json:"key"`
  54. Address string `json:"address"`
  55. InsecureAddress string `json:"insecureAddress"`
  56. DNSNames []string `json:"dnsNames"`
  57. KMS *kms.Options `json:"kms,omitempty"`
  58. SSH *SSHConfig `json:"ssh,omitempty"`
  59. Logger json.RawMessage `json:"logger,omitempty"`
  60. DB *db.Config `json:"db,omitempty"`
  61. Monitoring json.RawMessage `json:"monitoring,omitempty"`
  62. AuthorityConfig *AuthConfig `json:"authority,omitempty"`
  63. TLS *TLSOptions `json:"tls,omitempty"`
  64. Password string `json:"password,omitempty"`
  65. Templates *templates.Templates `json:"templates,omitempty"`
  66. }
  67. // ASN1DN contains ASN1.DN attributes that are used in Subject and Issuer
  68. // x509 Certificate blocks.
  69. type ASN1DN struct {
  70. Country string `json:"country,omitempty"`
  71. Organization string `json:"organization,omitempty"`
  72. OrganizationalUnit string `json:"organizationalUnit,omitempty"`
  73. Locality string `json:"locality,omitempty"`
  74. Province string `json:"province,omitempty"`
  75. StreetAddress string `json:"streetAddress,omitempty"`
  76. SerialNumber string `json:"serialNumber,omitempty"`
  77. CommonName string `json:"commonName,omitempty"`
  78. }
  79. // AuthConfig represents the configuration options for the authority. An
  80. // underlaying registration authority can also be configured using the
  81. // cas.Options.
  82. type AuthConfig struct {
  83. *cas.Options
  84. AuthorityID string `json:"authorityId,omitempty"`
  85. DeploymentType string `json:"deploymentType,omitempty"`
  86. Provisioners provisioner.List `json:"provisioners,omitempty"`
  87. Admins []*linkedca.Admin `json:"-"`
  88. Template *ASN1DN `json:"template,omitempty"`
  89. Claims *provisioner.Claims `json:"claims,omitempty"`
  90. DisableIssuedAtCheck bool `json:"disableIssuedAtCheck,omitempty"`
  91. Backdate *provisioner.Duration `json:"backdate,omitempty"`
  92. EnableAdmin bool `json:"enableAdmin,omitempty"`
  93. }
  94. // init initializes the required fields in the AuthConfig if they are not
  95. // provided.
  96. func (c *AuthConfig) init() {
  97. if c.Provisioners == nil {
  98. c.Provisioners = provisioner.List{}
  99. }
  100. if c.Template == nil {
  101. c.Template = &ASN1DN{}
  102. }
  103. if c.Backdate == nil {
  104. c.Backdate = &provisioner.Duration{
  105. Duration: DefaultBackdate,
  106. }
  107. }
  108. }
  109. // Validate validates the authority configuration.
  110. func (c *AuthConfig) Validate(audiences provisioner.Audiences) error {
  111. if c == nil {
  112. return errors.New("authority cannot be undefined")
  113. }
  114. // Initialize required fields.
  115. c.init()
  116. // Check that only one K8sSA is enabled
  117. var k8sCount int
  118. for _, p := range c.Provisioners {
  119. if p.GetType() == provisioner.TypeK8sSA {
  120. k8sCount++
  121. }
  122. }
  123. if k8sCount > 1 {
  124. return errors.New("cannot have more than one kubernetes service account provisioner")
  125. }
  126. if c.Backdate.Duration < 0 {
  127. return errors.New("authority.backdate cannot be less than 0")
  128. }
  129. return nil
  130. }
  131. // LoadConfiguration parses the given filename in JSON format and returns the
  132. // configuration struct.
  133. func LoadConfiguration(filename string) (*Config, error) {
  134. f, err := os.Open(filename)
  135. if err != nil {
  136. return nil, errors.Wrapf(err, "error opening %s", filename)
  137. }
  138. defer f.Close()
  139. var c Config
  140. if err := json.NewDecoder(f).Decode(&c); err != nil {
  141. return nil, errors.Wrapf(err, "error parsing %s", filename)
  142. }
  143. c.Init()
  144. return &c, nil
  145. }
  146. // Init initializes the minimal configuration required to create an authority. This
  147. // is mainly used on embedded authorities.
  148. func (c *Config) Init() {
  149. if c.DNSNames == nil {
  150. c.DNSNames = []string{"localhost", "127.0.0.1", "::1"}
  151. }
  152. if c.TLS == nil {
  153. c.TLS = &DefaultTLSOptions
  154. }
  155. if c.AuthorityConfig == nil {
  156. c.AuthorityConfig = &AuthConfig{}
  157. }
  158. c.AuthorityConfig.init()
  159. }
  160. // Save saves the configuration to the given filename.
  161. func (c *Config) Save(filename string) error {
  162. f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  163. if err != nil {
  164. return errors.Wrapf(err, "error opening %s", filename)
  165. }
  166. defer f.Close()
  167. enc := json.NewEncoder(f)
  168. enc.SetIndent("", "\t")
  169. return errors.Wrapf(enc.Encode(c), "error writing %s", filename)
  170. }
  171. // Validate validates the configuration.
  172. func (c *Config) Validate() error {
  173. switch {
  174. case c.Address == "":
  175. return errors.New("address cannot be empty")
  176. case len(c.DNSNames) == 0:
  177. return errors.New("dnsNames cannot be empty")
  178. case c.AuthorityConfig == nil:
  179. return errors.New("authority cannot be nil")
  180. }
  181. // Options holds the RA/CAS configuration.
  182. ra := c.AuthorityConfig.Options
  183. // The default RA/CAS requires root, crt and key.
  184. if ra.Is(cas.SoftCAS) {
  185. switch {
  186. case c.Root.HasEmpties():
  187. return errors.New("root cannot be empty")
  188. case c.IntermediateCert == "":
  189. return errors.New("crt cannot be empty")
  190. case c.IntermediateKey == "":
  191. return errors.New("key cannot be empty")
  192. }
  193. }
  194. // Validate address (a port is required)
  195. if _, _, err := net.SplitHostPort(c.Address); err != nil {
  196. return errors.Errorf("invalid address %s", c.Address)
  197. }
  198. if c.TLS == nil {
  199. c.TLS = &DefaultTLSOptions
  200. } else {
  201. if len(c.TLS.CipherSuites) == 0 {
  202. c.TLS.CipherSuites = DefaultTLSOptions.CipherSuites
  203. }
  204. if c.TLS.MaxVersion == 0 {
  205. c.TLS.MaxVersion = DefaultTLSOptions.MaxVersion
  206. }
  207. if c.TLS.MinVersion == 0 {
  208. c.TLS.MinVersion = DefaultTLSOptions.MinVersion
  209. }
  210. if c.TLS.MinVersion > c.TLS.MaxVersion {
  211. return errors.New("tls minVersion cannot exceed tls maxVersion")
  212. }
  213. c.TLS.Renegotiation = c.TLS.Renegotiation || DefaultTLSOptions.Renegotiation
  214. }
  215. // Validate KMS options, nil is ok.
  216. if err := c.KMS.Validate(); err != nil {
  217. return err
  218. }
  219. // Validate RA/CAS options, nil is ok.
  220. if err := ra.Validate(); err != nil {
  221. return err
  222. }
  223. // Validate ssh: nil is ok
  224. if err := c.SSH.Validate(); err != nil {
  225. return err
  226. }
  227. // Validate templates: nil is ok
  228. if err := c.Templates.Validate(); err != nil {
  229. return err
  230. }
  231. return c.AuthorityConfig.Validate(c.GetAudiences())
  232. }
  233. // GetAudiences returns the legacy and possible urls without the ports that will
  234. // be used as the default provisioner audiences. The CA might have proxies in
  235. // front so we cannot rely on the port.
  236. func (c *Config) GetAudiences() provisioner.Audiences {
  237. audiences := provisioner.Audiences{
  238. Sign: []string{legacyAuthority},
  239. Revoke: []string{legacyAuthority},
  240. SSHSign: []string{},
  241. SSHRevoke: []string{},
  242. SSHRenew: []string{},
  243. }
  244. for _, name := range c.DNSNames {
  245. hostname := toHostname(name)
  246. audiences.Sign = append(audiences.Sign,
  247. fmt.Sprintf("https://%s/1.0/sign", hostname),
  248. fmt.Sprintf("https://%s/sign", hostname),
  249. fmt.Sprintf("https://%s/1.0/ssh/sign", hostname),
  250. fmt.Sprintf("https://%s/ssh/sign", hostname))
  251. audiences.Renew = append(audiences.Renew,
  252. fmt.Sprintf("https://%s/1.0/renew", hostname),
  253. fmt.Sprintf("https://%s/renew", hostname))
  254. audiences.Revoke = append(audiences.Revoke,
  255. fmt.Sprintf("https://%s/1.0/revoke", hostname),
  256. fmt.Sprintf("https://%s/revoke", hostname))
  257. audiences.SSHSign = append(audiences.SSHSign,
  258. fmt.Sprintf("https://%s/1.0/ssh/sign", hostname),
  259. fmt.Sprintf("https://%s/ssh/sign", hostname),
  260. fmt.Sprintf("https://%s/1.0/sign", hostname),
  261. fmt.Sprintf("https://%s/sign", hostname))
  262. audiences.SSHRevoke = append(audiences.SSHRevoke,
  263. fmt.Sprintf("https://%s/1.0/ssh/revoke", hostname),
  264. fmt.Sprintf("https://%s/ssh/revoke", hostname))
  265. audiences.SSHRenew = append(audiences.SSHRenew,
  266. fmt.Sprintf("https://%s/1.0/ssh/renew", hostname),
  267. fmt.Sprintf("https://%s/ssh/renew", hostname))
  268. audiences.SSHRekey = append(audiences.SSHRekey,
  269. fmt.Sprintf("https://%s/1.0/ssh/rekey", hostname),
  270. fmt.Sprintf("https://%s/ssh/rekey", hostname))
  271. }
  272. return audiences
  273. }
  274. func toHostname(name string) string {
  275. // ensure an IPv6 address is represented with square brackets when used as hostname
  276. if ip := net.ParseIP(name); ip != nil && ip.To4() == nil {
  277. name = "[" + name + "]"
  278. }
  279. return name
  280. }