engine.go 11 KB

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