config.go 11 KB

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