engine.go 9.8 KB

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