validate.go 18 KB

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