engine.go 9.9 KB

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