engine.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. package policy
  2. import (
  3. "bytes"
  4. "crypto/x509"
  5. "crypto/x509/pkix"
  6. "fmt"
  7. "net"
  8. "net/url"
  9. "reflect"
  10. "strings"
  11. "golang.org/x/crypto/ssh"
  12. "golang.org/x/net/idna"
  13. "go.step.sm/crypto/x509util"
  14. )
  15. type NamePolicyReason int
  16. const (
  17. // NotAuthorizedForThisName results when an instance of
  18. // NamePolicyEngine determines that there's a constraint which
  19. // doesn't permit a DNS or another type of SAN to be signed
  20. // (or otherwise used).
  21. NotAuthorizedForThisName NamePolicyReason = iota
  22. // CannotParseDomain is returned when an error occurs
  23. // when parsing the domain part of SAN or subject.
  24. CannotParseDomain
  25. // CannotParseRFC822Name is returned when an error
  26. // occurs when parsing an email address.
  27. CannotParseRFC822Name
  28. // CannotMatch is the type of error returned when
  29. // an error happens when matching SAN types.
  30. CannotMatchNameToConstraint
  31. )
  32. type NamePolicyError struct {
  33. Reason NamePolicyReason
  34. Detail string
  35. }
  36. func (e *NamePolicyError) Error() string {
  37. switch e.Reason {
  38. case NotAuthorizedForThisName:
  39. return "not authorized to sign for this name: " + e.Detail
  40. case CannotParseDomain:
  41. return "cannot parse domain: " + e.Detail
  42. case CannotParseRFC822Name:
  43. return "cannot parse rfc822Name: " + e.Detail
  44. case CannotMatchNameToConstraint:
  45. return "error matching name to constraint: " + e.Detail
  46. default:
  47. return "unknown error: " + e.Detail
  48. }
  49. }
  50. // NamePolicyEngine can be used to check that a CSR or Certificate meets all allowed and
  51. // denied names before a CA creates and/or signs the Certificate.
  52. // TODO(hs): the X509 RFC also defines name checks on directory name; support that?
  53. // TODO(hs): implement Stringer interface: describe the contents of the NamePolicyEngine?
  54. // TODO(hs): implement matching URI schemes, paths, etc; not just the domain part of URI domains
  55. type NamePolicyEngine struct {
  56. // verifySubjectCommonName is set when Subject Common Name must be verified
  57. verifySubjectCommonName bool
  58. // allowLiteralWildcardNames allows literal wildcard DNS domains
  59. allowLiteralWildcardNames bool
  60. // permitted and exluded constraints similar to x509 Name Constraints
  61. permittedDNSDomains []string
  62. excludedDNSDomains []string
  63. permittedIPRanges []*net.IPNet
  64. excludedIPRanges []*net.IPNet
  65. permittedEmailAddresses []string
  66. excludedEmailAddresses []string
  67. permittedURIDomains []string
  68. excludedURIDomains []string
  69. permittedPrincipals []string
  70. excludedPrincipals []string
  71. // some internal counts for housekeeping
  72. numberOfDNSDomainConstraints int
  73. numberOfIPRangeConstraints int
  74. numberOfEmailAddressConstraints int
  75. numberOfURIDomainConstraints int
  76. numberOfPrincipalConstraints int
  77. totalNumberOfPermittedConstraints int
  78. totalNumberOfExcludedConstraints int
  79. totalNumberOfConstraints int
  80. }
  81. // NewNamePolicyEngine creates a new NamePolicyEngine with NamePolicyOptions
  82. func New(opts ...NamePolicyOption) (*NamePolicyEngine, error) {
  83. e := &NamePolicyEngine{}
  84. for _, option := range opts {
  85. if err := option(e); err != nil {
  86. return nil, err
  87. }
  88. }
  89. e.permittedDNSDomains = removeDuplicates(e.permittedDNSDomains)
  90. e.permittedIPRanges = removeDuplicateIPRanges(e.permittedIPRanges)
  91. e.permittedEmailAddresses = removeDuplicates(e.permittedEmailAddresses)
  92. e.permittedURIDomains = removeDuplicates(e.permittedURIDomains)
  93. e.permittedPrincipals = removeDuplicates(e.permittedPrincipals)
  94. e.excludedDNSDomains = removeDuplicates(e.excludedDNSDomains)
  95. e.excludedIPRanges = removeDuplicateIPRanges(e.excludedIPRanges)
  96. e.excludedEmailAddresses = removeDuplicates(e.excludedEmailAddresses)
  97. e.excludedURIDomains = removeDuplicates(e.excludedURIDomains)
  98. e.excludedPrincipals = removeDuplicates(e.excludedPrincipals)
  99. e.numberOfDNSDomainConstraints = len(e.permittedDNSDomains) + len(e.excludedDNSDomains)
  100. e.numberOfIPRangeConstraints = len(e.permittedIPRanges) + len(e.excludedIPRanges)
  101. e.numberOfEmailAddressConstraints = len(e.permittedEmailAddresses) + len(e.excludedEmailAddresses)
  102. e.numberOfURIDomainConstraints = len(e.permittedURIDomains) + len(e.excludedURIDomains)
  103. e.numberOfPrincipalConstraints = len(e.permittedPrincipals) + len(e.excludedPrincipals)
  104. e.totalNumberOfPermittedConstraints = len(e.permittedDNSDomains) + len(e.permittedIPRanges) +
  105. len(e.permittedEmailAddresses) + len(e.permittedURIDomains) + len(e.permittedPrincipals)
  106. e.totalNumberOfExcludedConstraints = len(e.excludedDNSDomains) + len(e.excludedIPRanges) +
  107. len(e.excludedEmailAddresses) + len(e.excludedURIDomains) + len(e.excludedPrincipals)
  108. e.totalNumberOfConstraints = e.totalNumberOfPermittedConstraints + e.totalNumberOfExcludedConstraints
  109. return e, nil
  110. }
  111. func removeDuplicates(strSlice []string) []string {
  112. if len(strSlice) == 0 {
  113. return nil
  114. }
  115. keys := make(map[string]bool)
  116. result := []string{}
  117. for _, item := range strSlice {
  118. if _, value := keys[item]; !value && item != "" { // skip empty constraints
  119. keys[item] = true
  120. result = append(result, item)
  121. }
  122. }
  123. return result
  124. }
  125. func removeDuplicateIPRanges(ipRanges []*net.IPNet) []*net.IPNet {
  126. if len(ipRanges) == 0 {
  127. return nil
  128. }
  129. keys := make(map[string]bool)
  130. result := []*net.IPNet{}
  131. for _, item := range ipRanges {
  132. key := item.String()
  133. if _, value := keys[key]; !value {
  134. keys[key] = true
  135. result = append(result, item)
  136. }
  137. }
  138. return result
  139. }
  140. // AreCertificateNamesAllowed verifies that all SANs in a Certificate are allowed.
  141. func (e *NamePolicyEngine) AreCertificateNamesAllowed(cert *x509.Certificate) (bool, error) {
  142. dnsNames, ips, emails, uris := cert.DNSNames, cert.IPAddresses, cert.EmailAddresses, cert.URIs
  143. // when Subject Common Name must be verified in addition to the SANs, it is
  144. // added to the appropriate slice of names.
  145. if e.verifySubjectCommonName {
  146. appendSubjectCommonName(cert.Subject, &dnsNames, &ips, &emails, &uris)
  147. }
  148. if err := e.validateNames(dnsNames, ips, emails, uris, []string{}); err != nil {
  149. return false, err
  150. }
  151. return true, nil
  152. }
  153. // AreCSRNamesAllowed verifies that all names in the CSR are allowed.
  154. func (e *NamePolicyEngine) AreCSRNamesAllowed(csr *x509.CertificateRequest) (bool, error) {
  155. dnsNames, ips, emails, uris := csr.DNSNames, csr.IPAddresses, csr.EmailAddresses, csr.URIs
  156. // when Subject Common Name must be verified in addition to the SANs, it is
  157. // added to the appropriate slice of names.
  158. if e.verifySubjectCommonName {
  159. appendSubjectCommonName(csr.Subject, &dnsNames, &ips, &emails, &uris)
  160. }
  161. if err := e.validateNames(dnsNames, ips, emails, uris, []string{}); err != nil {
  162. return false, err
  163. }
  164. return true, nil
  165. }
  166. // AreSANSAllowed verifies that all names in the slice of SANs are allowed.
  167. // The SANs are first split into DNS names, IPs, email addresses and URIs.
  168. func (e *NamePolicyEngine) AreSANsAllowed(sans []string) (bool, error) {
  169. dnsNames, ips, emails, uris := x509util.SplitSANs(sans)
  170. if err := e.validateNames(dnsNames, ips, emails, uris, []string{}); err != nil {
  171. return false, err
  172. }
  173. return true, nil
  174. }
  175. // IsDNSAllowed verifies a single DNS domain is allowed.
  176. func (e *NamePolicyEngine) IsDNSAllowed(dns string) (bool, error) {
  177. if err := e.validateNames([]string{dns}, []net.IP{}, []string{}, []*url.URL{}, []string{}); err != nil {
  178. return false, err
  179. }
  180. return true, nil
  181. }
  182. // IsIPAllowed verifies a single IP domain is allowed.
  183. func (e *NamePolicyEngine) IsIPAllowed(ip net.IP) (bool, error) {
  184. if err := e.validateNames([]string{}, []net.IP{ip}, []string{}, []*url.URL{}, []string{}); err != nil {
  185. return false, err
  186. }
  187. return true, nil
  188. }
  189. // ArePrincipalsAllowed verifies that all principals in an SSH certificate are allowed.
  190. func (e *NamePolicyEngine) ArePrincipalsAllowed(cert *ssh.Certificate) (bool, error) {
  191. dnsNames, ips, emails, principals, err := splitSSHPrincipals(cert)
  192. if err != nil {
  193. return false, err
  194. }
  195. if err := e.validateNames(dnsNames, ips, emails, []*url.URL{}, principals); err != nil {
  196. return false, err
  197. }
  198. return true, nil
  199. }
  200. // appendSubjectCommonName appends the Subject Common Name to the appropriate slice of names. The logic is
  201. // similar as x509util.SplitSANs: if the subject can be parsed as an IP, it's added to the ips. If it can
  202. // be parsed as an URL, it is added to the URIs. If it contains an @, it is added to emails. When it's none
  203. // of these, it's added to the DNS names.
  204. func appendSubjectCommonName(subject pkix.Name, dnsNames *[]string, ips *[]net.IP, emails *[]string, uris *[]*url.URL) {
  205. commonName := subject.CommonName
  206. if commonName == "" {
  207. return
  208. }
  209. subjectDNSNames, subjectIPs, subjectEmails, subjectURIs := x509util.SplitSANs([]string{commonName})
  210. *dnsNames = append(*dnsNames, subjectDNSNames...)
  211. *ips = append(*ips, subjectIPs...)
  212. *emails = append(*emails, subjectEmails...)
  213. *uris = append(*uris, subjectURIs...)
  214. }
  215. // splitPrincipals splits SSH certificate principals into DNS names, emails and usernames.
  216. func splitSSHPrincipals(cert *ssh.Certificate) (dnsNames []string, ips []net.IP, emails, principals []string, err error) {
  217. dnsNames = []string{}
  218. ips = []net.IP{}
  219. emails = []string{}
  220. principals = []string{}
  221. var uris []*url.URL
  222. switch cert.CertType {
  223. case ssh.HostCert:
  224. dnsNames, ips, emails, uris = x509util.SplitSANs(cert.ValidPrincipals)
  225. if len(uris) > 0 {
  226. err = fmt.Errorf("URL principals %v not expected in SSH host certificate ", uris)
  227. }
  228. case ssh.UserCert:
  229. // re-using SplitSANs results in anything that can't be parsed as an IP, URI or email
  230. // to be considered a username principal. This allows usernames like h.slatman to be present
  231. // in the SSH certificate. We're exluding IPs and URIs, because they can be confusing
  232. // when used in a SSH user certificate.
  233. principals, ips, emails, uris = x509util.SplitSANs(cert.ValidPrincipals)
  234. if len(uris) > 0 {
  235. err = fmt.Errorf("URL principals %v not expected in SSH user certificate ", uris)
  236. }
  237. default:
  238. err = fmt.Errorf("unexpected SSH certificate type %d", cert.CertType)
  239. }
  240. return
  241. }
  242. // validateNames verifies that all names are allowed.
  243. // Its logic follows that of (a large part of) the (c *Certificate) isValid() function
  244. // in https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  245. func (e *NamePolicyEngine) validateNames(dnsNames []string, ips []net.IP, emailAddresses []string, uris []*url.URL, principals []string) error {
  246. // nothing to compare against; return early
  247. if e.totalNumberOfConstraints == 0 {
  248. return nil
  249. }
  250. // TODO: implement check that requires at least a single name in all of the SANs + subject?
  251. // TODO: set limit on total of all names validated? In x509 there's a limit on the number of comparisons
  252. // that protects the CA from a DoS (i.e. many heavy comparisons). The x509 implementation takes
  253. // this number as a total of all checks and keeps a (pointer to a) counter of the number of checks
  254. // executed so far.
  255. // TODO: gather all errors, or return early? Currently we return early on the first wrong name; check might fail for multiple names.
  256. // Perhaps make that an option?
  257. for _, dns := range dnsNames {
  258. // if there are DNS names to check, no DNS constraints set, but there are other permitted constraints,
  259. // then return error, because DNS should be explicitly configured to be allowed in that case. In case there are
  260. // (other) excluded constraints, we'll allow a DNS (implicit allow; currently).
  261. if e.numberOfDNSDomainConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  262. return &NamePolicyError{
  263. Reason: NotAuthorizedForThisName,
  264. Detail: fmt.Sprintf("dns %q is not explicitly permitted by any constraint", dns),
  265. }
  266. }
  267. didCutWildcard := false
  268. if strings.HasPrefix(dns, "*.") {
  269. dns = dns[1:]
  270. didCutWildcard = true
  271. }
  272. parsedDNS, err := idna.Lookup.ToASCII(dns)
  273. if err != nil {
  274. return &NamePolicyError{
  275. Reason: CannotParseDomain,
  276. Detail: fmt.Sprintf("dns %q cannot be converted to ASCII", dns),
  277. }
  278. }
  279. if didCutWildcard {
  280. parsedDNS = "*" + parsedDNS
  281. }
  282. if _, ok := domainToReverseLabels(parsedDNS); !ok {
  283. return &NamePolicyError{
  284. Reason: CannotParseDomain,
  285. Detail: fmt.Sprintf("cannot parse dns %q", dns),
  286. }
  287. }
  288. if err := checkNameConstraints("dns", dns, parsedDNS,
  289. func(parsedName, constraint interface{}) (bool, error) {
  290. return e.matchDomainConstraint(parsedName.(string), constraint.(string))
  291. }, e.permittedDNSDomains, e.excludedDNSDomains); err != nil {
  292. return err
  293. }
  294. }
  295. for _, ip := range ips {
  296. if e.numberOfIPRangeConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  297. return &NamePolicyError{
  298. Reason: NotAuthorizedForThisName,
  299. Detail: fmt.Sprintf("ip %q is not explicitly permitted by any constraint", ip.String()),
  300. }
  301. }
  302. if err := checkNameConstraints("ip", ip.String(), ip,
  303. func(parsedName, constraint interface{}) (bool, error) {
  304. return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
  305. }, e.permittedIPRanges, e.excludedIPRanges); err != nil {
  306. return err
  307. }
  308. }
  309. for _, email := range emailAddresses {
  310. if e.numberOfEmailAddressConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  311. return &NamePolicyError{
  312. Reason: NotAuthorizedForThisName,
  313. Detail: fmt.Sprintf("email %q is not explicitly permitted by any constraint", email),
  314. }
  315. }
  316. mailbox, ok := parseRFC2821Mailbox(email)
  317. if !ok {
  318. return &NamePolicyError{
  319. Reason: CannotParseRFC822Name,
  320. Detail: fmt.Sprintf("invalid rfc822Name %q", mailbox),
  321. }
  322. }
  323. // According to RFC 5280, section 7.5, emails are considered to match if the local part is
  324. // an exact match and the host (domain) part matches the ASCII representation (case-insensitive):
  325. // https://datatracker.ietf.org/doc/html/rfc5280#section-7.5
  326. domainASCII, err := idna.ToASCII(mailbox.domain)
  327. if err != nil {
  328. return &NamePolicyError{
  329. Reason: CannotParseDomain,
  330. Detail: fmt.Sprintf("cannot parse email domain %q", email),
  331. }
  332. }
  333. mailbox.domain = domainASCII
  334. if err := checkNameConstraints("email", email, mailbox,
  335. func(parsedName, constraint interface{}) (bool, error) {
  336. return e.matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
  337. }, e.permittedEmailAddresses, e.excludedEmailAddresses); err != nil {
  338. return err
  339. }
  340. }
  341. // TODO(hs): fix internationalization for URIs (IRIs)
  342. for _, uri := range uris {
  343. if e.numberOfURIDomainConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  344. return &NamePolicyError{
  345. Reason: NotAuthorizedForThisName,
  346. Detail: fmt.Sprintf("uri %q is not explicitly permitted by any constraint", uri.String()),
  347. }
  348. }
  349. if err := checkNameConstraints("uri", uri.String(), uri,
  350. func(parsedName, constraint interface{}) (bool, error) {
  351. return e.matchURIConstraint(parsedName.(*url.URL), constraint.(string))
  352. }, e.permittedURIDomains, e.excludedURIDomains); err != nil {
  353. return err
  354. }
  355. }
  356. for _, principal := range principals {
  357. if e.numberOfPrincipalConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  358. return &NamePolicyError{
  359. Reason: NotAuthorizedForThisName,
  360. Detail: fmt.Sprintf("username principal %q is not explicitly permitted by any constraint", principal),
  361. }
  362. }
  363. // TODO: some validation? I.e. allowed characters?
  364. if err := checkNameConstraints("principal", principal, principal,
  365. func(parsedName, constraint interface{}) (bool, error) {
  366. return matchUsernameConstraint(parsedName.(string), constraint.(string))
  367. }, e.permittedPrincipals, e.excludedPrincipals); err != nil {
  368. return err
  369. }
  370. }
  371. // if all checks out, all SANs are allowed
  372. return nil
  373. }
  374. // checkNameConstraints checks that a name, of type nameType is permitted.
  375. // The argument parsedName contains the parsed form of name, suitable for passing
  376. // to the match function.
  377. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  378. func checkNameConstraints(
  379. nameType string,
  380. name string,
  381. parsedName interface{},
  382. match func(parsedName, constraint interface{}) (match bool, err error),
  383. permitted, excluded interface{}) error {
  384. excludedValue := reflect.ValueOf(excluded)
  385. for i := 0; i < excludedValue.Len(); i++ {
  386. constraint := excludedValue.Index(i).Interface()
  387. match, err := match(parsedName, constraint)
  388. if err != nil {
  389. return &NamePolicyError{
  390. Reason: CannotMatchNameToConstraint,
  391. Detail: err.Error(),
  392. }
  393. }
  394. if match {
  395. return &NamePolicyError{
  396. Reason: NotAuthorizedForThisName,
  397. Detail: fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint),
  398. }
  399. }
  400. }
  401. permittedValue := reflect.ValueOf(permitted)
  402. ok := true
  403. for i := 0; i < permittedValue.Len(); i++ {
  404. constraint := permittedValue.Index(i).Interface()
  405. var err error
  406. if ok, err = match(parsedName, constraint); err != nil {
  407. return &NamePolicyError{
  408. Reason: CannotMatchNameToConstraint,
  409. Detail: err.Error(),
  410. }
  411. }
  412. if ok {
  413. break
  414. }
  415. }
  416. if !ok {
  417. return &NamePolicyError{
  418. Reason: NotAuthorizedForThisName,
  419. Detail: fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name),
  420. }
  421. }
  422. return nil
  423. }
  424. // domainToReverseLabels converts a textual domain name like foo.example.com to
  425. // the list of labels in reverse order, e.g. ["com", "example", "foo"].
  426. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  427. func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
  428. for len(domain) > 0 {
  429. if i := strings.LastIndexByte(domain, '.'); i == -1 {
  430. reverseLabels = append(reverseLabels, domain)
  431. domain = ""
  432. } else {
  433. reverseLabels = append(reverseLabels, domain[i+1:])
  434. domain = domain[:i]
  435. }
  436. }
  437. if len(reverseLabels) > 0 && reverseLabels[0] == "" {
  438. // An empty label at the end indicates an absolute value.
  439. return nil, false
  440. }
  441. for _, label := range reverseLabels {
  442. if label == "" {
  443. // Empty labels are otherwise invalid.
  444. return nil, false
  445. }
  446. for _, c := range label {
  447. if c < 33 || c > 126 {
  448. // Invalid character.
  449. return nil, false
  450. }
  451. }
  452. }
  453. return reverseLabels, true
  454. }
  455. // rfc2821Mailbox represents a “mailbox” (which is an email address to most
  456. // people) by breaking it into the “local” (i.e. before the '@') and “domain”
  457. // parts.
  458. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  459. type rfc2821Mailbox struct {
  460. local, domain string
  461. }
  462. // parseRFC2821Mailbox parses an email address into local and domain parts,
  463. // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
  464. // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
  465. // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
  466. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  467. func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
  468. if in == "" {
  469. return mailbox, false
  470. }
  471. localPartBytes := make([]byte, 0, len(in)/2)
  472. if in[0] == '"' {
  473. // Quoted-string = DQUOTE *qcontent DQUOTE
  474. // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
  475. // qcontent = qtext / quoted-pair
  476. // qtext = non-whitespace-control /
  477. // %d33 / %d35-91 / %d93-126
  478. // quoted-pair = ("\" text) / obs-qp
  479. // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
  480. //
  481. // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
  482. // Section 4. Since it has been 16 years, we no longer accept that.)
  483. in = in[1:]
  484. QuotedString:
  485. for {
  486. if in == "" {
  487. return mailbox, false
  488. }
  489. c := in[0]
  490. in = in[1:]
  491. switch {
  492. case c == '"':
  493. break QuotedString
  494. case c == '\\':
  495. // quoted-pair
  496. if in == "" {
  497. return mailbox, false
  498. }
  499. if in[0] == 11 ||
  500. in[0] == 12 ||
  501. (1 <= in[0] && in[0] <= 9) ||
  502. (14 <= in[0] && in[0] <= 127) {
  503. localPartBytes = append(localPartBytes, in[0])
  504. in = in[1:]
  505. } else {
  506. return mailbox, false
  507. }
  508. case c == 11 ||
  509. c == 12 ||
  510. // Space (char 32) is not allowed based on the
  511. // BNF, but RFC 3696 gives an example that
  512. // assumes that it is. Several “verified”
  513. // errata continue to argue about this point.
  514. // We choose to accept it.
  515. c == 32 ||
  516. c == 33 ||
  517. c == 127 ||
  518. (1 <= c && c <= 8) ||
  519. (14 <= c && c <= 31) ||
  520. (35 <= c && c <= 91) ||
  521. (93 <= c && c <= 126):
  522. // qtext
  523. localPartBytes = append(localPartBytes, c)
  524. default:
  525. return mailbox, false
  526. }
  527. }
  528. } else {
  529. // Atom ("." Atom)*
  530. NextChar:
  531. for len(in) > 0 {
  532. // atext from RFC 2822, Section 3.2.4
  533. c := in[0]
  534. switch {
  535. case c == '\\':
  536. // Examples given in RFC 3696 suggest that
  537. // escaped characters can appear outside of a
  538. // quoted string. Several “verified” errata
  539. // continue to argue the point. We choose to
  540. // accept it.
  541. in = in[1:]
  542. if in == "" {
  543. return mailbox, false
  544. }
  545. fallthrough
  546. case ('0' <= c && c <= '9') ||
  547. ('a' <= c && c <= 'z') ||
  548. ('A' <= c && c <= 'Z') ||
  549. c == '!' || c == '#' || c == '$' || c == '%' ||
  550. c == '&' || c == '\'' || c == '*' || c == '+' ||
  551. c == '-' || c == '/' || c == '=' || c == '?' ||
  552. c == '^' || c == '_' || c == '`' || c == '{' ||
  553. c == '|' || c == '}' || c == '~' || c == '.':
  554. localPartBytes = append(localPartBytes, in[0])
  555. in = in[1:]
  556. default:
  557. break NextChar
  558. }
  559. }
  560. if len(localPartBytes) == 0 {
  561. return mailbox, false
  562. }
  563. // From RFC 3696, Section 3:
  564. // “period (".") may also appear, but may not be used to start
  565. // or end the local part, nor may two or more consecutive
  566. // periods appear.”
  567. twoDots := []byte{'.', '.'}
  568. if localPartBytes[0] == '.' ||
  569. localPartBytes[len(localPartBytes)-1] == '.' ||
  570. bytes.Contains(localPartBytes, twoDots) {
  571. return mailbox, false
  572. }
  573. }
  574. if in == "" || in[0] != '@' {
  575. return mailbox, false
  576. }
  577. in = in[1:]
  578. // The RFC species a format for domains, but that's known to be
  579. // violated in practice so we accept that anything after an '@' is the
  580. // domain part.
  581. if _, ok := domainToReverseLabels(in); !ok {
  582. return mailbox, false
  583. }
  584. mailbox.local = string(localPartBytes)
  585. mailbox.domain = in
  586. return mailbox, true
  587. }
  588. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  589. func (e *NamePolicyEngine) matchDomainConstraint(domain, constraint string) (bool, error) {
  590. // The meaning of zero length constraints is not specified, but this
  591. // code follows NSS and accepts them as matching everything.
  592. if constraint == "" {
  593. return true, nil
  594. }
  595. // A single whitespace seems to be considered a valid domain, but we don't allow it.
  596. if domain == " " {
  597. return false, nil
  598. }
  599. // Block domains that start with just a period
  600. if domain[0] == '.' {
  601. return false, nil
  602. }
  603. // Block wildcard domains that don't start with exactly "*." (i.e. double wildcards and such)
  604. if domain[0] == '*' && domain[1] != '.' {
  605. return false, nil
  606. }
  607. // Check if the domain starts with a wildcard and return early if not allowed
  608. if strings.HasPrefix(domain, "*.") && !e.allowLiteralWildcardNames {
  609. return false, nil
  610. }
  611. // Only allow asterisk at the start of the domain; we don't allow them as part of a domain label or as a (sub)domain label (currently)
  612. if strings.LastIndex(domain, "*") > 0 {
  613. return false, nil
  614. }
  615. // Don't allow constraints with empty labels in any position
  616. if strings.Contains(constraint, "..") {
  617. return false, nil
  618. }
  619. domainLabels, ok := domainToReverseLabels(domain)
  620. if !ok {
  621. return false, fmt.Errorf("cannot parse domain %q", domain)
  622. }
  623. // RFC 5280 says that a leading period in a domain name means that at
  624. // least one label must be prepended, but only for URI and email
  625. // constraints, not DNS constraints. The code also supports that
  626. // behavior for DNS constraints. In our adaptation of the original
  627. // Go stdlib x509 Name Constraint implementation we look for exactly
  628. // one subdomain, currently.
  629. mustHaveSubdomains := false
  630. if constraint[0] == '.' {
  631. mustHaveSubdomains = true
  632. constraint = constraint[1:]
  633. }
  634. constraintLabels, ok := domainToReverseLabels(constraint)
  635. if !ok {
  636. return false, fmt.Errorf("cannot parse domain constraint %q", constraint)
  637. }
  638. // fmt.Println(mustHaveSubdomains)
  639. // fmt.Println(constraintLabels)
  640. // fmt.Println(domainLabels)
  641. expectedNumberOfLabels := len(constraintLabels)
  642. if mustHaveSubdomains {
  643. // we expect exactly one more label if it starts with the "canonical" x509 "wildcard": "."
  644. // in the future we could extend this to support multiple additional labels and/or more
  645. // complex matching.
  646. expectedNumberOfLabels++
  647. }
  648. if len(domainLabels) != expectedNumberOfLabels {
  649. return false, nil
  650. }
  651. for i, constraintLabel := range constraintLabels {
  652. if !strings.EqualFold(constraintLabel, domainLabels[i]) {
  653. return false, nil
  654. }
  655. }
  656. return true, nil
  657. }
  658. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  659. func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
  660. // TODO(hs): this is code from Go library, but I got some unexpected result:
  661. // with permitted net 127.0.0.0/24, 127.0.0.1 is NOT allowed. When parsing 127.0.0.1 as net.IP
  662. // which is in the IPAddresses slice, the underlying length is 16. The contraint.IP has a length
  663. // of 4 instead. I currently don't believe that this is a bug in Go now, but why is it like that?
  664. // Is there a difference because we're not operating on a sans []string slice? Or is the Go
  665. // implementation stricter regarding IPv4 vs. IPv6? I've been bitten by some unfortunate differences
  666. // between the two before (i.e. IPv4 in IPv6; IP SANS in ACME)
  667. // if len(ip) != len(constraint.IP) {
  668. // return false, nil
  669. // }
  670. // for i := range ip {
  671. // if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
  672. // return false, nil
  673. // }
  674. // }
  675. contained := constraint.Contains(ip) // TODO(hs): validate that this is the correct behavior; also check IPv4-in-IPv6 (again)
  676. return contained, nil
  677. }
  678. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  679. func (e *NamePolicyEngine) matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
  680. // TODO(hs): handle literal wildcard case for emails? Does that even make sense?
  681. // If the constraint contains an @, then it specifies an exact mailbox name (currently)
  682. if strings.Contains(constraint, "*") {
  683. return false, fmt.Errorf("email constraint %q cannot contain asterisk", constraint)
  684. }
  685. if strings.Contains(constraint, "@") {
  686. constraintMailbox, ok := parseRFC2821Mailbox(constraint)
  687. if !ok {
  688. return false, fmt.Errorf("cannot parse constraint %q", constraint)
  689. }
  690. return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
  691. }
  692. // Otherwise the constraint is like a DNS constraint of the domain part
  693. // of the mailbox.
  694. return e.matchDomainConstraint(mailbox.domain, constraint)
  695. }
  696. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  697. func (e *NamePolicyEngine) matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
  698. // From RFC 5280, Section 4.2.1.10:
  699. // “a uniformResourceIdentifier that does not include an authority
  700. // component with a host name specified as a fully qualified domain
  701. // name (e.g., if the URI either does not include an authority
  702. // component or includes an authority component in which the host name
  703. // is specified as an IP address), then the application MUST reject the
  704. // certificate.”
  705. host := uri.Host
  706. if host == "" {
  707. return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
  708. }
  709. // Block hosts with the wildcard character; no exceptions, also not when wildcards allowed.
  710. if strings.Contains(host, "*") {
  711. return false, fmt.Errorf("URI host %q cannot contain asterisk", uri.String())
  712. }
  713. if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
  714. var err error
  715. host, _, err = net.SplitHostPort(uri.Host)
  716. if err != nil {
  717. return false, err
  718. }
  719. }
  720. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
  721. net.ParseIP(host) != nil {
  722. return false, fmt.Errorf("URI with IP %q cannot be matched against constraints", uri.String())
  723. }
  724. // TODO(hs): add checks for scheme, path, etc.; either here, or in a different constraint matcher (to keep this one simple)
  725. return e.matchDomainConstraint(host, constraint)
  726. }
  727. // matchUsernameConstraint performs a string literal match against a constraint.
  728. func matchUsernameConstraint(username, constraint string) (bool, error) {
  729. // allow any plain principal username
  730. if constraint == "*" {
  731. return true, nil
  732. }
  733. return strings.EqualFold(username, constraint), nil
  734. }