validate.go 20 KB

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