engine.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package policy
  2. import (
  3. "crypto/x509"
  4. "crypto/x509/pkix"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "golang.org/x/crypto/ssh"
  9. "go.step.sm/crypto/x509util"
  10. )
  11. type NamePolicyReason int
  12. const (
  13. // NotAllowed results when an instance of NamePolicyEngine
  14. // determines that there's a constraint which doesn't permit
  15. // a DNS or another type of SAN to be signed (or otherwise used).
  16. NotAllowed NamePolicyReason = iota + 1
  17. // CannotParseDomain is returned when an error occurs
  18. // when parsing the domain part of SAN or subject.
  19. CannotParseDomain
  20. // CannotParseRFC822Name is returned when an error
  21. // occurs when parsing an email address.
  22. CannotParseRFC822Name
  23. // CannotMatch is the type of error returned when
  24. // an error happens when matching SAN types.
  25. CannotMatchNameToConstraint
  26. )
  27. type NameType string
  28. const (
  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. permittedDNSDomains []string
  70. excludedDNSDomains []string
  71. permittedIPRanges []*net.IPNet
  72. excludedIPRanges []*net.IPNet
  73. permittedEmailAddresses []string
  74. excludedEmailAddresses []string
  75. permittedURIDomains []string
  76. excludedURIDomains []string
  77. permittedPrincipals []string
  78. excludedPrincipals []string
  79. // some internal counts for housekeeping
  80. numberOfDNSDomainConstraints int
  81. numberOfIPRangeConstraints int
  82. numberOfEmailAddressConstraints int
  83. numberOfURIDomainConstraints int
  84. numberOfPrincipalConstraints int
  85. totalNumberOfPermittedConstraints int
  86. totalNumberOfExcludedConstraints int
  87. totalNumberOfConstraints int
  88. }
  89. // NewNamePolicyEngine creates a new NamePolicyEngine with NamePolicyOptions
  90. func New(opts ...NamePolicyOption) (*NamePolicyEngine, error) {
  91. e := &NamePolicyEngine{}
  92. for _, option := range opts {
  93. if err := option(e); err != nil {
  94. return nil, err
  95. }
  96. }
  97. e.permittedDNSDomains = removeDuplicates(e.permittedDNSDomains)
  98. e.permittedIPRanges = removeDuplicateIPNets(e.permittedIPRanges)
  99. e.permittedEmailAddresses = removeDuplicates(e.permittedEmailAddresses)
  100. e.permittedURIDomains = removeDuplicates(e.permittedURIDomains)
  101. e.permittedPrincipals = removeDuplicates(e.permittedPrincipals)
  102. e.excludedDNSDomains = removeDuplicates(e.excludedDNSDomains)
  103. e.excludedIPRanges = removeDuplicateIPNets(e.excludedIPRanges)
  104. e.excludedEmailAddresses = removeDuplicates(e.excludedEmailAddresses)
  105. e.excludedURIDomains = removeDuplicates(e.excludedURIDomains)
  106. e.excludedPrincipals = removeDuplicates(e.excludedPrincipals)
  107. e.numberOfDNSDomainConstraints = len(e.permittedDNSDomains) + len(e.excludedDNSDomains)
  108. e.numberOfIPRangeConstraints = len(e.permittedIPRanges) + len(e.excludedIPRanges)
  109. e.numberOfEmailAddressConstraints = len(e.permittedEmailAddresses) + len(e.excludedEmailAddresses)
  110. e.numberOfURIDomainConstraints = len(e.permittedURIDomains) + len(e.excludedURIDomains)
  111. e.numberOfPrincipalConstraints = len(e.permittedPrincipals) + len(e.excludedPrincipals)
  112. e.totalNumberOfPermittedConstraints = len(e.permittedDNSDomains) + len(e.permittedIPRanges) +
  113. len(e.permittedEmailAddresses) + len(e.permittedURIDomains) + len(e.permittedPrincipals)
  114. e.totalNumberOfExcludedConstraints = len(e.excludedDNSDomains) + len(e.excludedIPRanges) +
  115. len(e.excludedEmailAddresses) + len(e.excludedURIDomains) + len(e.excludedPrincipals)
  116. e.totalNumberOfConstraints = e.totalNumberOfPermittedConstraints + e.totalNumberOfExcludedConstraints
  117. return e, nil
  118. }
  119. // removeDuplicates returns a new slice of strings with
  120. // duplicate values removed. It retains the order of elements
  121. // in the source slice.
  122. func removeDuplicates(items []string) (ret []string) {
  123. // no need to remove dupes; return original
  124. if len(items) <= 1 {
  125. return items
  126. }
  127. keys := make(map[string]struct{}, len(items))
  128. ret = make([]string, 0, len(items))
  129. for _, item := range items {
  130. if _, ok := keys[item]; ok {
  131. continue
  132. }
  133. keys[item] = struct{}{}
  134. ret = append(ret, item)
  135. }
  136. return
  137. }
  138. // removeDuplicateIPNets returns a new slice of net.IPNets with
  139. // duplicate values removed. It retains the order of elements in
  140. // the source slice. An IPNet is considered duplicate if its CIDR
  141. // notation exists multiple times in the slice.
  142. func removeDuplicateIPNets(items []*net.IPNet) (ret []*net.IPNet) {
  143. // no need to remove dupes; return original
  144. if len(items) <= 1 {
  145. return items
  146. }
  147. keys := make(map[string]struct{}, len(items))
  148. ret = make([]*net.IPNet, 0, len(items))
  149. for _, item := range items {
  150. key := item.String() // use CIDR notation as key
  151. if _, ok := keys[key]; ok {
  152. continue
  153. }
  154. keys[key] = struct{}{}
  155. ret = append(ret, item)
  156. }
  157. // TODO(hs): implement filter of fully overlapping ranges,
  158. // so that the smaller ones are automatically removed?
  159. return
  160. }
  161. // IsX509CertificateAllowed verifies that all SANs in a Certificate are allowed.
  162. func (e *NamePolicyEngine) IsX509CertificateAllowed(cert *x509.Certificate) error {
  163. dnsNames, ips, emails, uris := cert.DNSNames, cert.IPAddresses, cert.EmailAddresses, cert.URIs
  164. // when Subject Common Name must be verified in addition to the SANs, it is
  165. // added to the appropriate slice of names.
  166. if e.verifySubjectCommonName {
  167. appendSubjectCommonName(cert.Subject, &dnsNames, &ips, &emails, &uris)
  168. }
  169. if err := e.validateNames(dnsNames, ips, emails, uris, []string{}); err != nil {
  170. return err
  171. }
  172. return nil
  173. }
  174. // IsX509CertificateRequestAllowed verifies that all names in the CSR are allowed.
  175. func (e *NamePolicyEngine) IsX509CertificateRequestAllowed(csr *x509.CertificateRequest) error {
  176. dnsNames, ips, emails, uris := csr.DNSNames, csr.IPAddresses, csr.EmailAddresses, csr.URIs
  177. // when Subject Common Name must be verified in addition to the SANs, it is
  178. // added to the appropriate slice of names.
  179. if e.verifySubjectCommonName {
  180. appendSubjectCommonName(csr.Subject, &dnsNames, &ips, &emails, &uris)
  181. }
  182. if err := e.validateNames(dnsNames, ips, emails, uris, []string{}); err != nil {
  183. return err
  184. }
  185. return nil
  186. }
  187. // AreSANSAllowed verifies that all names in the slice of SANs are allowed.
  188. // The SANs are first split into DNS names, IPs, email addresses and URIs.
  189. func (e *NamePolicyEngine) AreSANsAllowed(sans []string) error {
  190. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  191. if err := e.validateNames(dnsNames, ips, emails, uris, []string{}); err != nil {
  192. return err
  193. }
  194. return nil
  195. }
  196. // IsDNSAllowed verifies a single DNS domain is allowed.
  197. func (e *NamePolicyEngine) IsDNSAllowed(dns string) error {
  198. if err := e.validateNames([]string{dns}, []net.IP{}, []string{}, []*url.URL{}, []string{}); err != nil {
  199. return err
  200. }
  201. return nil
  202. }
  203. // IsIPAllowed verifies a single IP domain is allowed.
  204. func (e *NamePolicyEngine) IsIPAllowed(ip net.IP) error {
  205. if err := e.validateNames([]string{}, []net.IP{ip}, []string{}, []*url.URL{}, []string{}); err != nil {
  206. return err
  207. }
  208. return nil
  209. }
  210. // IsSSHCertificateAllowed verifies that all principals in an SSH certificate are allowed.
  211. func (e *NamePolicyEngine) IsSSHCertificateAllowed(cert *ssh.Certificate) error {
  212. dnsNames, ips, emails, principals, err := splitSSHPrincipals(cert)
  213. if err != nil {
  214. return err
  215. }
  216. if err := e.validateNames(dnsNames, ips, emails, []*url.URL{}, principals); err != nil {
  217. return err
  218. }
  219. return nil
  220. }
  221. // appendSubjectCommonName appends the Subject Common Name to the appropriate slice of names. The logic is
  222. // similar as x509util.SplitSANs: if the subject can be parsed as an IP, it's added to the ips. If it can
  223. // be parsed as an URL, it is added to the URIs. If it contains an @, it is added to emails. When it's none
  224. // of these, it's added to the DNS names.
  225. func appendSubjectCommonName(subject pkix.Name, dnsNames *[]string, ips *[]net.IP, emails *[]string, uris *[]*url.URL) {
  226. commonName := subject.CommonName
  227. if commonName == "" {
  228. return
  229. }
  230. subjectDNSNames, subjectIPs, subjectEmails, subjectURIs := x509util.SplitSANs([]string{commonName})
  231. *dnsNames = append(*dnsNames, subjectDNSNames...)
  232. *ips = append(*ips, subjectIPs...)
  233. *emails = append(*emails, subjectEmails...)
  234. *uris = append(*uris, subjectURIs...)
  235. }
  236. // splitPrincipals splits SSH certificate principals into DNS names, emails and usernames.
  237. func splitSSHPrincipals(cert *ssh.Certificate) (dnsNames []string, ips []net.IP, emails, principals []string, err error) {
  238. dnsNames = []string{}
  239. ips = []net.IP{}
  240. emails = []string{}
  241. principals = []string{}
  242. var uris []*url.URL
  243. switch cert.CertType {
  244. case ssh.HostCert:
  245. dnsNames, ips, emails, uris = x509util.SplitSANs(cert.ValidPrincipals)
  246. if len(uris) > 0 {
  247. err = fmt.Errorf("URL principals %v not expected in SSH host certificate ", uris)
  248. }
  249. case ssh.UserCert:
  250. // re-using SplitSANs results in anything that can't be parsed as an IP, URI or email
  251. // to be considered a username principal. This allows usernames like h.slatman to be present
  252. // in the SSH certificate. We're exluding URIs, because they can be confusing
  253. // when used in a SSH user certificate.
  254. principals, ips, emails, uris = x509util.SplitSANs(cert.ValidPrincipals)
  255. if len(ips) > 0 {
  256. err = fmt.Errorf("IP principals %v not expected in SSH user certificate ", ips)
  257. }
  258. if len(uris) > 0 {
  259. err = fmt.Errorf("URL principals %v not expected in SSH user certificate ", uris)
  260. }
  261. default:
  262. err = fmt.Errorf("unexpected SSH certificate type %d", cert.CertType)
  263. }
  264. return
  265. }