4
0

engine.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package policy
  2. import (
  3. "crypto/x509"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "go.step.sm/crypto/x509util"
  9. "golang.org/x/crypto/ssh"
  10. "github.com/smallstep/certificates/errs"
  11. )
  12. type NamePolicyReason int
  13. const (
  14. // NotAllowed results when an instance of NamePolicyEngine
  15. // determines that there's a constraint which doesn't permit
  16. // a DNS or another type of SAN to be signed (or otherwise used).
  17. NotAllowed NamePolicyReason = iota + 1
  18. // CannotParseDomain is returned when an error occurs
  19. // when parsing the domain part of SAN or subject.
  20. CannotParseDomain
  21. // CannotParseRFC822Name is returned when an error
  22. // occurs when parsing an email address.
  23. CannotParseRFC822Name
  24. // CannotMatch is the type of error returned when
  25. // an error happens when matching SAN types.
  26. CannotMatchNameToConstraint
  27. )
  28. type NameType string
  29. const (
  30. CNNameType NameType = "cn"
  31. DNSNameType NameType = "dns"
  32. IPNameType NameType = "ip"
  33. EmailNameType NameType = "email"
  34. URINameType NameType = "uri"
  35. PrincipalNameType NameType = "principal"
  36. )
  37. type NamePolicyError struct {
  38. Reason NamePolicyReason
  39. NameType NameType
  40. Name string
  41. detail string
  42. }
  43. func (e *NamePolicyError) Error() string {
  44. switch e.Reason {
  45. case NotAllowed:
  46. return fmt.Sprintf("%s name %q not allowed", e.NameType, e.Name)
  47. case CannotParseDomain:
  48. return fmt.Sprintf("cannot parse %s domain %q", e.NameType, e.Name)
  49. case CannotParseRFC822Name:
  50. return fmt.Sprintf("cannot parse %s rfc822Name %q", e.NameType, e.Name)
  51. case CannotMatchNameToConstraint:
  52. return fmt.Sprintf("error matching %s name %q to constraint", e.NameType, e.Name)
  53. default:
  54. return fmt.Sprintf("unknown error reason (%d): %s", e.Reason, e.detail)
  55. }
  56. }
  57. // As implements the As(any) bool interface and allows to use "errors.As()" to
  58. // convert a NotAllowed NamePolicyError to an errs.Error.
  59. func (e *NamePolicyError) As(v any) bool {
  60. if e.Reason == NotAllowed {
  61. if err, ok := v.(**errs.Error); ok {
  62. *err = &errs.Error{
  63. Status: http.StatusForbidden,
  64. Msg: fmt.Sprintf("The request was forbidden by the certificate authority: %s", e.Error()),
  65. Err: e,
  66. }
  67. return true
  68. }
  69. }
  70. return false
  71. }
  72. func (e *NamePolicyError) Detail() string {
  73. return e.detail
  74. }
  75. // NamePolicyEngine can be used to check that a CSR or Certificate meets all allowed and
  76. // denied names before a CA creates and/or signs the Certificate.
  77. // TODO(hs): the X509 RFC also defines name checks on directory name; support that?
  78. // TODO(hs): implement Stringer interface: describe the contents of the NamePolicyEngine?
  79. // TODO(hs): implement matching URI schemes, paths, etc; not just the domain part of URI domains
  80. type NamePolicyEngine struct {
  81. // verifySubjectCommonName is set when Subject Common Name must be verified
  82. verifySubjectCommonName bool
  83. // allowLiteralWildcardNames allows literal wildcard DNS domains
  84. allowLiteralWildcardNames bool
  85. // permitted and exluded constraints similar to x509 Name Constraints
  86. permittedCommonNames []string
  87. excludedCommonNames []string
  88. permittedDNSDomains []string
  89. excludedDNSDomains []string
  90. permittedIPRanges []*net.IPNet
  91. excludedIPRanges []*net.IPNet
  92. permittedEmailAddresses []string
  93. excludedEmailAddresses []string
  94. permittedURIDomains []string
  95. excludedURIDomains []string
  96. permittedPrincipals []string
  97. excludedPrincipals []string
  98. // some internal counts for housekeeping
  99. numberOfCommonNameConstraints int
  100. numberOfDNSDomainConstraints int
  101. numberOfIPRangeConstraints int
  102. numberOfEmailAddressConstraints int
  103. numberOfURIDomainConstraints int
  104. numberOfPrincipalConstraints int
  105. totalNumberOfPermittedConstraints int
  106. totalNumberOfExcludedConstraints int
  107. totalNumberOfConstraints int
  108. }
  109. // NewNamePolicyEngine creates a new NamePolicyEngine with NamePolicyOptions
  110. func New(opts ...NamePolicyOption) (*NamePolicyEngine, error) {
  111. e := &NamePolicyEngine{}
  112. for _, option := range opts {
  113. if err := option(e); err != nil {
  114. return nil, err
  115. }
  116. }
  117. e.permittedCommonNames = removeDuplicates(e.permittedCommonNames)
  118. e.permittedDNSDomains = removeDuplicates(e.permittedDNSDomains)
  119. e.permittedIPRanges = removeDuplicateIPNets(e.permittedIPRanges)
  120. e.permittedEmailAddresses = removeDuplicates(e.permittedEmailAddresses)
  121. e.permittedURIDomains = removeDuplicates(e.permittedURIDomains)
  122. e.permittedPrincipals = removeDuplicates(e.permittedPrincipals)
  123. e.excludedCommonNames = removeDuplicates(e.excludedCommonNames)
  124. e.excludedDNSDomains = removeDuplicates(e.excludedDNSDomains)
  125. e.excludedIPRanges = removeDuplicateIPNets(e.excludedIPRanges)
  126. e.excludedEmailAddresses = removeDuplicates(e.excludedEmailAddresses)
  127. e.excludedURIDomains = removeDuplicates(e.excludedURIDomains)
  128. e.excludedPrincipals = removeDuplicates(e.excludedPrincipals)
  129. e.numberOfCommonNameConstraints = len(e.permittedCommonNames) + len(e.excludedCommonNames)
  130. e.numberOfDNSDomainConstraints = len(e.permittedDNSDomains) + len(e.excludedDNSDomains)
  131. e.numberOfIPRangeConstraints = len(e.permittedIPRanges) + len(e.excludedIPRanges)
  132. e.numberOfEmailAddressConstraints = len(e.permittedEmailAddresses) + len(e.excludedEmailAddresses)
  133. e.numberOfURIDomainConstraints = len(e.permittedURIDomains) + len(e.excludedURIDomains)
  134. e.numberOfPrincipalConstraints = len(e.permittedPrincipals) + len(e.excludedPrincipals)
  135. e.totalNumberOfPermittedConstraints = len(e.permittedCommonNames) + len(e.permittedDNSDomains) +
  136. len(e.permittedIPRanges) + len(e.permittedEmailAddresses) + len(e.permittedURIDomains) +
  137. len(e.permittedPrincipals)
  138. e.totalNumberOfExcludedConstraints = len(e.excludedCommonNames) + len(e.excludedDNSDomains) +
  139. len(e.excludedIPRanges) + len(e.excludedEmailAddresses) + len(e.excludedURIDomains) +
  140. len(e.excludedPrincipals)
  141. e.totalNumberOfConstraints = e.totalNumberOfPermittedConstraints + e.totalNumberOfExcludedConstraints
  142. return e, nil
  143. }
  144. // removeDuplicates returns a new slice of strings with
  145. // duplicate values removed. It retains the order of elements
  146. // in the source slice.
  147. func removeDuplicates(items []string) (ret []string) {
  148. // no need to remove dupes; return original
  149. if len(items) <= 1 {
  150. return items
  151. }
  152. keys := make(map[string]struct{}, len(items))
  153. ret = make([]string, 0, len(items))
  154. for _, item := range items {
  155. if _, ok := keys[item]; ok {
  156. continue
  157. }
  158. keys[item] = struct{}{}
  159. ret = append(ret, item)
  160. }
  161. return
  162. }
  163. // removeDuplicateIPNets returns a new slice of net.IPNets with
  164. // duplicate values removed. It retains the order of elements in
  165. // the source slice. An IPNet is considered duplicate if its CIDR
  166. // notation exists multiple times in the slice.
  167. func removeDuplicateIPNets(items []*net.IPNet) (ret []*net.IPNet) {
  168. // no need to remove dupes; return original
  169. if len(items) <= 1 {
  170. return items
  171. }
  172. keys := make(map[string]struct{}, len(items))
  173. ret = make([]*net.IPNet, 0, len(items))
  174. for _, item := range items {
  175. key := item.String() // use CIDR notation as key
  176. if _, ok := keys[key]; ok {
  177. continue
  178. }
  179. keys[key] = struct{}{}
  180. ret = append(ret, item)
  181. }
  182. // TODO(hs): implement filter of fully overlapping ranges,
  183. // so that the smaller ones are automatically removed?
  184. return
  185. }
  186. // IsX509CertificateAllowed verifies that all SANs in a Certificate are allowed.
  187. func (e *NamePolicyEngine) IsX509CertificateAllowed(cert *x509.Certificate) error {
  188. if err := e.validateNames(cert.DNSNames, cert.IPAddresses, cert.EmailAddresses, cert.URIs, []string{}); err != nil {
  189. return err
  190. }
  191. if e.verifySubjectCommonName {
  192. return e.validateCommonName(cert.Subject.CommonName)
  193. }
  194. return nil
  195. }
  196. // IsX509CertificateRequestAllowed verifies that all names in the CSR are allowed.
  197. func (e *NamePolicyEngine) IsX509CertificateRequestAllowed(csr *x509.CertificateRequest) error {
  198. if err := e.validateNames(csr.DNSNames, csr.IPAddresses, csr.EmailAddresses, csr.URIs, []string{}); err != nil {
  199. return err
  200. }
  201. if e.verifySubjectCommonName {
  202. return e.validateCommonName(csr.Subject.CommonName)
  203. }
  204. return nil
  205. }
  206. // AreSANsAllowed verifies that all names in the slice of SANs are allowed.
  207. // The SANs are first split into DNS names, IPs, email addresses and URIs.
  208. func (e *NamePolicyEngine) AreSANsAllowed(sans []string) error {
  209. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  210. return e.validateNames(dnsNames, ips, emails, uris, []string{})
  211. }
  212. // IsDNSAllowed verifies a single DNS domain is allowed.
  213. func (e *NamePolicyEngine) IsDNSAllowed(dns string) error {
  214. return e.validateNames([]string{dns}, []net.IP{}, []string{}, []*url.URL{}, []string{})
  215. }
  216. // IsIPAllowed verifies a single IP domain is allowed.
  217. func (e *NamePolicyEngine) IsIPAllowed(ip net.IP) error {
  218. return e.validateNames([]string{}, []net.IP{ip}, []string{}, []*url.URL{}, []string{})
  219. }
  220. // IsSSHCertificateAllowed verifies that all principals in an SSH certificate are allowed.
  221. func (e *NamePolicyEngine) IsSSHCertificateAllowed(cert *ssh.Certificate) error {
  222. dnsNames, ips, emails, principals, err := splitSSHPrincipals(cert)
  223. if err != nil {
  224. return err
  225. }
  226. return e.validateNames(dnsNames, ips, emails, []*url.URL{}, principals)
  227. }
  228. // splitSSHPrincipals splits SSH certificate principals into DNS names, emails and usernames.
  229. func splitSSHPrincipals(cert *ssh.Certificate) (dnsNames []string, ips []net.IP, emails, principals []string, err error) {
  230. dnsNames = []string{}
  231. ips = []net.IP{}
  232. emails = []string{}
  233. principals = []string{}
  234. var uris []*url.URL
  235. switch cert.CertType {
  236. case ssh.HostCert:
  237. dnsNames, ips, emails, uris = x509util.SplitSANs(cert.ValidPrincipals)
  238. if len(uris) > 0 {
  239. err = fmt.Errorf("URL principals %v not expected in SSH host certificate ", uris)
  240. }
  241. case ssh.UserCert:
  242. // re-using SplitSANs results in anything that can't be parsed as an IP, URI or email
  243. // to be considered a username principal. This allows usernames like h.slatman to be present
  244. // in the SSH certificate. We're exluding URIs, because they can be confusing
  245. // when used in a SSH user certificate.
  246. principals, ips, emails, uris = x509util.SplitSANs(cert.ValidPrincipals)
  247. if len(ips) > 0 {
  248. err = fmt.Errorf("IP principals %v not expected in SSH user certificate ", ips)
  249. }
  250. if len(uris) > 0 {
  251. err = fmt.Errorf("URL principals %v not expected in SSH user certificate ", uris)
  252. }
  253. default:
  254. err = fmt.Errorf("unexpected SSH certificate type %d", cert.CertType)
  255. }
  256. return
  257. }