4
0

validate.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //
  5. // The code in this file is an adapted version of the code in
  6. // https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  7. package policy
  8. import (
  9. "bytes"
  10. "errors"
  11. "fmt"
  12. "net"
  13. "net/url"
  14. "reflect"
  15. "strings"
  16. "golang.org/x/net/idna"
  17. "go.step.sm/crypto/x509util"
  18. )
  19. // validateNames verifies that all names are allowed.
  20. func (e *NamePolicyEngine) validateNames(dnsNames []string, ips []net.IP, emailAddresses []string, uris []*url.URL, principals []string) error {
  21. // nothing to compare against; return early
  22. if e.totalNumberOfConstraints == 0 {
  23. return nil
  24. }
  25. // TODO: set limit on total of all names validated? In x509 there's a limit on the number of comparisons
  26. // that protects the CA from a DoS (i.e. many heavy comparisons). The x509 implementation takes
  27. // this number as a total of all checks and keeps a (pointer to a) counter of the number of checks
  28. // executed so far.
  29. // TODO: gather all errors, or return early? Currently we return early on the first wrong name; check might fail for multiple names.
  30. // Perhaps make that an option?
  31. for _, dns := range dnsNames {
  32. // if there are DNS names to check, no DNS constraints set, but there are other permitted constraints,
  33. // then return error, because DNS should be explicitly configured to be allowed in that case. In case there are
  34. // (other) excluded constraints, we'll allow a DNS (implicit allow; currently).
  35. if e.numberOfDNSDomainConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  36. return &NamePolicyError{
  37. Reason: NotAllowed,
  38. NameType: DNSNameType,
  39. Name: dns,
  40. detail: fmt.Sprintf("dns %q is not explicitly permitted by any constraint", dns),
  41. }
  42. }
  43. didCutWildcard := false
  44. parsedDNS := dns
  45. if strings.HasPrefix(parsedDNS, "*.") {
  46. parsedDNS = parsedDNS[1:]
  47. didCutWildcard = true
  48. }
  49. // TODO(hs): fix this above; we need separate rule for Subject Common Name?
  50. parsedDNS, err := idna.Lookup.ToASCII(parsedDNS)
  51. if err != nil {
  52. return &NamePolicyError{
  53. Reason: CannotParseDomain,
  54. NameType: DNSNameType,
  55. Name: dns,
  56. detail: fmt.Sprintf("dns %q cannot be converted to ASCII", dns),
  57. }
  58. }
  59. if didCutWildcard {
  60. parsedDNS = "*" + parsedDNS
  61. }
  62. if _, ok := domainToReverseLabels(parsedDNS); !ok { // TODO(hs): this also fails with spaces
  63. return &NamePolicyError{
  64. Reason: CannotParseDomain,
  65. NameType: DNSNameType,
  66. Name: dns,
  67. detail: fmt.Sprintf("cannot parse dns %q", dns),
  68. }
  69. }
  70. if err := checkNameConstraints(DNSNameType, dns, parsedDNS,
  71. func(parsedName, constraint interface{}) (bool, error) {
  72. return e.matchDomainConstraint(parsedName.(string), constraint.(string))
  73. }, e.permittedDNSDomains, e.excludedDNSDomains); err != nil {
  74. return err
  75. }
  76. }
  77. for _, ip := range ips {
  78. if e.numberOfIPRangeConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  79. return &NamePolicyError{
  80. Reason: NotAllowed,
  81. NameType: IPNameType,
  82. Name: ip.String(),
  83. detail: fmt.Sprintf("ip %q is not explicitly permitted by any constraint", ip.String()),
  84. }
  85. }
  86. if err := checkNameConstraints(IPNameType, ip.String(), ip,
  87. func(parsedName, constraint interface{}) (bool, error) {
  88. return matchIPConstraint(parsedName.(net.IP), constraint.(*net.IPNet))
  89. }, e.permittedIPRanges, e.excludedIPRanges); err != nil {
  90. return err
  91. }
  92. }
  93. for _, email := range emailAddresses {
  94. if e.numberOfEmailAddressConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  95. return &NamePolicyError{
  96. Reason: NotAllowed,
  97. NameType: EmailNameType,
  98. Name: email,
  99. detail: fmt.Sprintf("email %q is not explicitly permitted by any constraint", email),
  100. }
  101. }
  102. mailbox, ok := parseRFC2821Mailbox(email)
  103. if !ok {
  104. return &NamePolicyError{
  105. Reason: CannotParseRFC822Name,
  106. NameType: EmailNameType,
  107. Name: email,
  108. detail: fmt.Sprintf("invalid rfc822Name %q", mailbox),
  109. }
  110. }
  111. // According to RFC 5280, section 7.5, emails are considered to match if the local part is
  112. // an exact match and the host (domain) part matches the ASCII representation (case-insensitive):
  113. // https://datatracker.ietf.org/doc/html/rfc5280#section-7.5
  114. domainASCII, err := idna.ToASCII(mailbox.domain)
  115. if err != nil {
  116. return &NamePolicyError{
  117. Reason: CannotParseDomain,
  118. NameType: EmailNameType,
  119. Name: email,
  120. detail: fmt.Errorf("cannot parse email domain %q: %w", email, err).Error(),
  121. }
  122. }
  123. mailbox.domain = domainASCII
  124. if err := checkNameConstraints(EmailNameType, email, mailbox,
  125. func(parsedName, constraint interface{}) (bool, error) {
  126. return e.matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
  127. }, e.permittedEmailAddresses, e.excludedEmailAddresses); err != nil {
  128. return err
  129. }
  130. }
  131. // TODO(hs): fix internationalization for URIs (IRIs)
  132. for _, uri := range uris {
  133. if e.numberOfURIDomainConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  134. return &NamePolicyError{
  135. Reason: NotAllowed,
  136. NameType: URINameType,
  137. Name: uri.String(),
  138. detail: fmt.Sprintf("uri %q is not explicitly permitted by any constraint", uri.String()),
  139. }
  140. }
  141. // TODO(hs): ideally we'd like the uri.String() to be the original contents; now
  142. // it's transformed into ASCII. Prevent that here?
  143. if err := checkNameConstraints(URINameType, uri.String(), uri,
  144. func(parsedName, constraint interface{}) (bool, error) {
  145. return e.matchURIConstraint(parsedName.(*url.URL), constraint.(string))
  146. }, e.permittedURIDomains, e.excludedURIDomains); err != nil {
  147. return err
  148. }
  149. }
  150. for _, principal := range principals {
  151. if e.numberOfPrincipalConstraints == 0 && e.totalNumberOfPermittedConstraints > 0 {
  152. return &NamePolicyError{
  153. Reason: NotAllowed,
  154. NameType: PrincipalNameType,
  155. Name: principal,
  156. detail: fmt.Sprintf("username principal %q is not explicitly permitted by any constraint", principal),
  157. }
  158. }
  159. // TODO: some validation? I.e. allowed characters?
  160. if err := checkNameConstraints(PrincipalNameType, principal, principal,
  161. func(parsedName, constraint interface{}) (bool, error) {
  162. return matchPrincipalConstraint(parsedName.(string), constraint.(string))
  163. }, e.permittedPrincipals, e.excludedPrincipals); err != nil {
  164. return err
  165. }
  166. }
  167. // if all checks out, all SANs are allowed
  168. return nil
  169. }
  170. // validateCommonName verifies that the Subject Common Name is allowed
  171. func (e *NamePolicyEngine) validateCommonName(commonName string) error {
  172. // nothing to compare against; return early
  173. if e.totalNumberOfConstraints == 0 {
  174. return nil
  175. }
  176. // empty common names are not validated
  177. if commonName == "" {
  178. return nil
  179. }
  180. if e.numberOfCommonNameConstraints > 0 {
  181. // Check the Common Name using its dedicated matcher if constraints have been
  182. // configured. If no error is returned from matching, the Common Name was
  183. // explicitly allowed and nil is returned immediately.
  184. if err := checkNameConstraints(CNNameType, commonName, commonName,
  185. func(parsedName, constraint interface{}) (bool, error) {
  186. return matchCommonNameConstraint(parsedName.(string), constraint.(string))
  187. }, e.permittedCommonNames, e.excludedCommonNames); err == nil {
  188. return nil
  189. }
  190. }
  191. // When an error was returned or when no constraints were configured for Common Names,
  192. // the Common Name should be validated against the other types of constraints too,
  193. // according to what type it is.
  194. dnsNames, ips, emails, uris := x509util.SplitSANs([]string{commonName})
  195. err := e.validateNames(dnsNames, ips, emails, uris, []string{})
  196. var pe *NamePolicyError
  197. if errors.As(err, &pe) {
  198. // override the name type with CN
  199. pe.NameType = CNNameType
  200. }
  201. return err
  202. }
  203. // checkNameConstraints checks that a name, of type nameType is permitted.
  204. // The argument parsedName contains the parsed form of name, suitable for passing
  205. // to the match function.
  206. func checkNameConstraints(
  207. nameType NameType,
  208. name string,
  209. parsedName interface{},
  210. match func(parsedName, constraint interface{}) (match bool, err error),
  211. permitted, excluded interface{}) error {
  212. excludedValue := reflect.ValueOf(excluded)
  213. for i := 0; i < excludedValue.Len(); i++ {
  214. constraint := excludedValue.Index(i).Interface()
  215. match, err := match(parsedName, constraint)
  216. if err != nil {
  217. return &NamePolicyError{
  218. Reason: CannotMatchNameToConstraint,
  219. NameType: nameType,
  220. Name: name,
  221. detail: err.Error(),
  222. }
  223. }
  224. if match {
  225. return &NamePolicyError{
  226. Reason: NotAllowed,
  227. NameType: nameType,
  228. Name: name,
  229. detail: fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint),
  230. }
  231. }
  232. }
  233. permittedValue := reflect.ValueOf(permitted)
  234. ok := true
  235. for i := 0; i < permittedValue.Len(); i++ {
  236. constraint := permittedValue.Index(i).Interface()
  237. var err error
  238. if ok, err = match(parsedName, constraint); err != nil {
  239. return &NamePolicyError{
  240. Reason: CannotMatchNameToConstraint,
  241. NameType: nameType,
  242. Name: name,
  243. detail: err.Error(),
  244. }
  245. }
  246. if ok {
  247. break
  248. }
  249. }
  250. if !ok {
  251. return &NamePolicyError{
  252. Reason: NotAllowed,
  253. NameType: nameType,
  254. Name: name,
  255. detail: fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name),
  256. }
  257. }
  258. return nil
  259. }
  260. // domainToReverseLabels converts a textual domain name like foo.example.com to
  261. // the list of labels in reverse order, e.g. ["com", "example", "foo"].
  262. func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
  263. for domain != "" {
  264. if i := strings.LastIndexByte(domain, '.'); i == -1 {
  265. reverseLabels = append(reverseLabels, domain)
  266. domain = ""
  267. } else {
  268. reverseLabels = append(reverseLabels, domain[i+1:])
  269. domain = domain[:i]
  270. }
  271. }
  272. if len(reverseLabels) > 0 && reverseLabels[0] == "" {
  273. // An empty label at the end indicates an absolute value.
  274. return nil, false
  275. }
  276. for _, label := range reverseLabels {
  277. if label == "" {
  278. // Empty labels are otherwise invalid.
  279. return nil, false
  280. }
  281. for _, c := range label {
  282. if c < 33 || c > 126 {
  283. // Invalid character.
  284. return nil, false
  285. }
  286. }
  287. }
  288. return reverseLabels, true
  289. }
  290. // rfc2821Mailbox represents a “mailbox” (which is an email address to most
  291. // people) by breaking it into the “local” (i.e. before the '@') and “domain”
  292. // parts.
  293. type rfc2821Mailbox struct {
  294. local, domain string
  295. }
  296. // parseRFC2821Mailbox parses an email address into local and domain parts,
  297. // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
  298. // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
  299. // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
  300. func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
  301. if in == "" {
  302. return mailbox, false
  303. }
  304. localPartBytes := make([]byte, 0, len(in)/2)
  305. if in[0] == '"' {
  306. // Quoted-string = DQUOTE *qcontent DQUOTE
  307. // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
  308. // qcontent = qtext / quoted-pair
  309. // qtext = non-whitespace-control /
  310. // %d33 / %d35-91 / %d93-126
  311. // quoted-pair = ("\" text) / obs-qp
  312. // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
  313. //
  314. // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
  315. // Section 4. Since it has been 16 years, we no longer accept that.)
  316. in = in[1:]
  317. QuotedString:
  318. for {
  319. if in == "" {
  320. return mailbox, false
  321. }
  322. c := in[0]
  323. in = in[1:]
  324. switch {
  325. case c == '"':
  326. break QuotedString
  327. case c == '\\':
  328. // quoted-pair
  329. if in == "" {
  330. return mailbox, false
  331. }
  332. if in[0] == 11 ||
  333. in[0] == 12 ||
  334. (1 <= in[0] && in[0] <= 9) ||
  335. (14 <= in[0] && in[0] <= 127) {
  336. localPartBytes = append(localPartBytes, in[0])
  337. in = in[1:]
  338. } else {
  339. return mailbox, false
  340. }
  341. case c == 11 ||
  342. c == 12 ||
  343. // Space (char 32) is not allowed based on the
  344. // BNF, but RFC 3696 gives an example that
  345. // assumes that it is. Several “verified”
  346. // errata continue to argue about this point.
  347. // We choose to accept it.
  348. c == 32 ||
  349. c == 33 ||
  350. c == 127 ||
  351. (1 <= c && c <= 8) ||
  352. (14 <= c && c <= 31) ||
  353. (35 <= c && c <= 91) ||
  354. (93 <= c && c <= 126):
  355. // qtext
  356. localPartBytes = append(localPartBytes, c)
  357. default:
  358. return mailbox, false
  359. }
  360. }
  361. } else {
  362. // Atom ("." Atom)*
  363. NextChar:
  364. for in != "" {
  365. // atext from RFC 2822, Section 3.2.4
  366. c := in[0]
  367. switch {
  368. case c == '\\':
  369. // Examples given in RFC 3696 suggest that
  370. // escaped characters can appear outside of a
  371. // quoted string. Several “verified” errata
  372. // continue to argue the point. We choose to
  373. // accept it.
  374. in = in[1:]
  375. if in == "" {
  376. return mailbox, false
  377. }
  378. fallthrough
  379. case ('0' <= c && c <= '9') ||
  380. ('a' <= c && c <= 'z') ||
  381. ('A' <= c && c <= 'Z') ||
  382. c == '!' || c == '#' || c == '$' || c == '%' ||
  383. c == '&' || c == '\'' || c == '*' || c == '+' ||
  384. c == '-' || c == '/' || c == '=' || c == '?' ||
  385. c == '^' || c == '_' || c == '`' || c == '{' ||
  386. c == '|' || c == '}' || c == '~' || c == '.':
  387. localPartBytes = append(localPartBytes, in[0])
  388. in = in[1:]
  389. default:
  390. break NextChar
  391. }
  392. }
  393. if len(localPartBytes) == 0 {
  394. return mailbox, false
  395. }
  396. // From RFC 3696, Section 3:
  397. // “period (".") may also appear, but may not be used to start
  398. // or end the local part, nor may two or more consecutive
  399. // periods appear.”
  400. twoDots := []byte{'.', '.'}
  401. if localPartBytes[0] == '.' ||
  402. localPartBytes[len(localPartBytes)-1] == '.' ||
  403. bytes.Contains(localPartBytes, twoDots) {
  404. return mailbox, false
  405. }
  406. }
  407. if in == "" || in[0] != '@' {
  408. return mailbox, false
  409. }
  410. in = in[1:]
  411. // The RFC species a format for domains, but that's known to be
  412. // violated in practice so we accept that anything after an '@' is the
  413. // domain part.
  414. if _, ok := domainToReverseLabels(in); !ok {
  415. return mailbox, false
  416. }
  417. mailbox.local = string(localPartBytes)
  418. mailbox.domain = in
  419. return mailbox, true
  420. }
  421. // matchDomainConstraint matches a domain against the given constraint
  422. func (e *NamePolicyEngine) matchDomainConstraint(domain, constraint string) (bool, error) {
  423. // The meaning of zero length constraints is not specified, but this
  424. // code follows NSS and accepts them as matching everything.
  425. if constraint == "" {
  426. return true, nil
  427. }
  428. // A single whitespace seems to be considered a valid domain, but we don't allow it.
  429. if domain == " " {
  430. return false, nil
  431. }
  432. // Block domains that start with just a period
  433. if domain[0] == '.' {
  434. return false, nil
  435. }
  436. // Block wildcard domains that don't start with exactly "*." (i.e. double wildcards and such)
  437. if domain[0] == '*' && domain[1] != '.' {
  438. return false, nil
  439. }
  440. // Check if the domain starts with a wildcard and return early if not allowed
  441. if strings.HasPrefix(domain, "*.") && !e.allowLiteralWildcardNames {
  442. return false, nil
  443. }
  444. // 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)
  445. if strings.LastIndex(domain, "*") > 0 {
  446. return false, nil
  447. }
  448. // Don't allow constraints with empty labels in any position
  449. if strings.Contains(constraint, "..") {
  450. return false, nil
  451. }
  452. domainLabels, ok := domainToReverseLabels(domain)
  453. if !ok {
  454. return false, fmt.Errorf("cannot parse domain %q", domain)
  455. }
  456. // RFC 5280 says that a leading period in a domain name means that at
  457. // least one label must be prepended, but only for URI and email
  458. // constraints, not DNS constraints. The code also supports that
  459. // behavior for DNS constraints. In our adaptation of the original
  460. // Go stdlib x509 Name Constraint implementation we look for exactly
  461. // one subdomain, currently.
  462. mustHaveSubdomains := false
  463. if constraint[0] == '.' {
  464. mustHaveSubdomains = true
  465. constraint = constraint[1:]
  466. }
  467. constraintLabels, ok := domainToReverseLabels(constraint)
  468. if !ok {
  469. return false, fmt.Errorf("cannot parse domain constraint %q", constraint)
  470. }
  471. expectedNumberOfLabels := len(constraintLabels)
  472. if mustHaveSubdomains {
  473. // we expect exactly one more label if it starts with the "canonical" x509 "wildcard": "."
  474. // in the future we could extend this to support multiple additional labels and/or more
  475. // complex matching.
  476. expectedNumberOfLabels++
  477. }
  478. if len(domainLabels) != expectedNumberOfLabels {
  479. return false, nil
  480. }
  481. for i, constraintLabel := range constraintLabels {
  482. if !strings.EqualFold(constraintLabel, domainLabels[i]) {
  483. return false, nil
  484. }
  485. }
  486. return true, nil
  487. }
  488. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  489. func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
  490. // TODO(hs): this is code from Go library, but I got some unexpected result:
  491. // with permitted net 127.0.0.0/24, 127.0.0.1 is NOT allowed. When parsing 127.0.0.1 as net.IP
  492. // which is in the IPAddresses slice, the underlying length is 16. The contraint.IP has a length
  493. // of 4 instead. I currently don't believe that this is a bug in Go now, but why is it like that?
  494. // Is there a difference because we're not operating on a sans []string slice? Or is the Go
  495. // implementation stricter regarding IPv4 vs. IPv6? I've been bitten by some unfortunate differences
  496. // between the two before (i.e. IPv4 in IPv6; IP SANS in ACME)
  497. // if len(ip) != len(constraint.IP) {
  498. // return false, nil
  499. // }
  500. // for i := range ip {
  501. // if mask := constraint.Mask[i]; ip[i]&mask != constraint.IP[i]&mask {
  502. // return false, nil
  503. // }
  504. // }
  505. contained := constraint.Contains(ip) // TODO(hs): validate that this is the correct behavior; also check IPv4-in-IPv6 (again)
  506. return contained, nil
  507. }
  508. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  509. func (e *NamePolicyEngine) matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
  510. if strings.Contains(constraint, "@") {
  511. constraintMailbox, ok := parseRFC2821Mailbox(constraint)
  512. if !ok {
  513. return false, fmt.Errorf("cannot parse constraint %q", constraint)
  514. }
  515. return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
  516. }
  517. // Otherwise the constraint is like a DNS constraint of the domain part
  518. // of the mailbox.
  519. return e.matchDomainConstraint(mailbox.domain, constraint)
  520. }
  521. // matchURIConstraint matches an URL against a constraint
  522. func (e *NamePolicyEngine) matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
  523. // From RFC 5280, Section 4.2.1.10:
  524. // “a uniformResourceIdentifier that does not include an authority
  525. // component with a host name specified as a fully qualified domain
  526. // name (e.g., if the URI either does not include an authority
  527. // component or includes an authority component in which the host name
  528. // is specified as an IP address), then the application MUST reject the
  529. // certificate.”
  530. host := uri.Host
  531. if host == "" {
  532. return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
  533. }
  534. // Block hosts with the wildcard character; no exceptions, also not when wildcards allowed.
  535. if strings.Contains(host, "*") {
  536. return false, fmt.Errorf("URI host %q cannot contain asterisk", uri.String())
  537. }
  538. if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
  539. var err error
  540. host, _, err = net.SplitHostPort(host)
  541. if err != nil {
  542. return false, err
  543. }
  544. }
  545. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
  546. net.ParseIP(host) != nil {
  547. return false, fmt.Errorf("URI with IP %q cannot be matched against constraints", uri.String())
  548. }
  549. // TODO(hs): add checks for scheme, path, etc.; either here, or in a different constraint matcher (to keep this one simple)
  550. return e.matchDomainConstraint(host, constraint)
  551. }
  552. // matchPrincipalConstraint performs a string literal equality check against a constraint.
  553. func matchPrincipalConstraint(principal, constraint string) (bool, error) {
  554. // allow any plain principal when wildcard constraint is used
  555. if constraint == "*" {
  556. return true, nil
  557. }
  558. return strings.EqualFold(principal, constraint), nil
  559. }
  560. // matchCommonNameConstraint performs a string literal equality check against constraint.
  561. func matchCommonNameConstraint(commonName, constraint string) (bool, error) {
  562. // wildcard constraint is (currently) not supported for common names
  563. if constraint == "*" {
  564. return false, nil
  565. }
  566. return strings.EqualFold(commonName, constraint), nil
  567. }