config.go 11 KB

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