config.go 11 KB

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