4
0

verify.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // Copyright (c) 2009 The Go Authors. All rights reserved.
  2. //
  3. // Redistribution and use in source and binary forms, with or without
  4. // modification, are permitted provided that the following conditions are
  5. // met:
  6. //
  7. // * Redistributions of source code must retain the above copyright
  8. // notice, this list of conditions and the following disclaimer.
  9. // * Redistributions in binary form must reproduce the above
  10. // copyright notice, this list of conditions and the following disclaimer
  11. // in the documentation and/or other materials provided with the
  12. // distribution.
  13. // * Neither the name of Google Inc. nor the names of its
  14. // contributors may be used to endorse or promote products derived from
  15. // this software without specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. package constraints
  29. import (
  30. "bytes"
  31. "fmt"
  32. "net"
  33. "net/url"
  34. "reflect"
  35. "strings"
  36. )
  37. func checkNameConstraints(nameType, name string, parsedName, permitted, excluded any, match func(name, constraint any) (bool, error)) error {
  38. excludedValue := reflect.ValueOf(excluded)
  39. for i := 0; i < excludedValue.Len(); i++ {
  40. constraint := excludedValue.Index(i).Interface()
  41. match, err := match(parsedName, constraint)
  42. if err != nil {
  43. return ConstraintError{
  44. Type: nameType,
  45. Name: name,
  46. Detail: err.Error(),
  47. }
  48. }
  49. if match {
  50. return ConstraintError{
  51. Type: nameType,
  52. Name: name,
  53. Detail: fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint),
  54. }
  55. }
  56. }
  57. var (
  58. err error
  59. ok = true
  60. )
  61. permittedValue := reflect.ValueOf(permitted)
  62. for i := 0; i < permittedValue.Len(); i++ {
  63. constraint := permittedValue.Index(i).Interface()
  64. if ok, err = match(parsedName, constraint); err != nil {
  65. return ConstraintError{
  66. Type: nameType,
  67. Name: name,
  68. Detail: err.Error(),
  69. }
  70. }
  71. if ok {
  72. break
  73. }
  74. }
  75. if !ok {
  76. return ConstraintError{
  77. Type: nameType,
  78. Name: name,
  79. Detail: fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name),
  80. }
  81. }
  82. return nil
  83. }
  84. func matchDomainConstraint(domain, constraint string) (bool, error) {
  85. // The meaning of zero length constraints is not specified, but this
  86. // code follows NSS and accepts them as matching everything.
  87. if constraint == "" {
  88. return true, nil
  89. }
  90. domainLabels, ok := domainToReverseLabels(domain)
  91. if !ok {
  92. return false, fmt.Errorf("internal error: cannot parse domain %q", domain)
  93. }
  94. // RFC 5280 says that a leading period in a domain name means that at least
  95. // one label must be prepended, but only for URI and email constraints, not
  96. // DNS constraints. The code also supports that behavior for DNS
  97. // constraints.
  98. mustHaveSubdomains := false
  99. if constraint[0] == '.' {
  100. mustHaveSubdomains = true
  101. constraint = constraint[1:]
  102. }
  103. constraintLabels, ok := domainToReverseLabels(constraint)
  104. if !ok {
  105. return false, fmt.Errorf("internal error: cannot parse domain %q", constraint)
  106. }
  107. if len(domainLabels) < len(constraintLabels) ||
  108. (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
  109. return false, nil
  110. }
  111. for i, constraintLabel := range constraintLabels {
  112. if !strings.EqualFold(constraintLabel, domainLabels[i]) {
  113. return false, nil
  114. }
  115. }
  116. return true, nil
  117. }
  118. func normalizeIP(ip net.IP) net.IP {
  119. if ip4 := ip.To4(); ip4 != nil {
  120. return ip4
  121. }
  122. return ip
  123. }
  124. func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) {
  125. ip = normalizeIP(ip)
  126. constraintIP := normalizeIP(constraint.IP)
  127. if len(ip) != len(constraintIP) {
  128. return false, nil
  129. }
  130. for i := range ip {
  131. if mask := constraint.Mask[i]; ip[i]&mask != constraintIP[i]&mask {
  132. return false, nil
  133. }
  134. }
  135. return true, nil
  136. }
  137. func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
  138. // If the constraint contains an @, then it specifies an exact mailbox
  139. // name.
  140. if strings.Contains(constraint, "@") {
  141. constraintMailbox, ok := parseRFC2821Mailbox(constraint)
  142. if !ok {
  143. return false, fmt.Errorf("internal error: cannot parse constraint %q", constraint)
  144. }
  145. return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
  146. }
  147. // Otherwise the constraint is like a DNS constraint of the domain part
  148. // of the mailbox.
  149. return matchDomainConstraint(mailbox.domain, constraint)
  150. }
  151. func matchURIConstraint(uri *url.URL, constraint string) (bool, error) {
  152. // From RFC 5280, Section 4.2.1.10:
  153. // “a uniformResourceIdentifier that does not include an authority
  154. // component with a host name specified as a fully qualified domain
  155. // name (e.g., if the URI either does not include an authority
  156. // component or includes an authority component in which the host name
  157. // is specified as an IP address), then the application MUST reject the
  158. // certificate.”
  159. host := uri.Host
  160. if host == "" {
  161. return false, fmt.Errorf("URI with empty host (%q) cannot be matched against constraints", uri.String())
  162. }
  163. if strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
  164. var err error
  165. host, _, err = net.SplitHostPort(uri.Host)
  166. if err != nil {
  167. return false, err
  168. }
  169. }
  170. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") ||
  171. net.ParseIP(host) != nil {
  172. return false, fmt.Errorf("URI with IP (%q) cannot be matched against constraints", uri.String())
  173. }
  174. return matchDomainConstraint(host, constraint)
  175. }
  176. // domainToReverseLabels converts a textual domain name like foo.example.com to
  177. // the list of labels in reverse order, e.g. ["com", "example", "foo"].
  178. func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
  179. for domain != "" {
  180. if i := strings.LastIndexByte(domain, '.'); i == -1 {
  181. reverseLabels = append(reverseLabels, domain)
  182. domain = ""
  183. } else {
  184. reverseLabels = append(reverseLabels, domain[i+1:])
  185. domain = domain[:i]
  186. }
  187. }
  188. if len(reverseLabels) > 0 && reverseLabels[0] == "" {
  189. // An empty label at the end indicates an absolute value.
  190. return nil, false
  191. }
  192. for _, label := range reverseLabels {
  193. if label == "" {
  194. // Empty labels are otherwise invalid.
  195. return nil, false
  196. }
  197. for _, c := range label {
  198. if c < 33 || c > 126 {
  199. // Invalid character.
  200. return nil, false
  201. }
  202. }
  203. }
  204. return reverseLabels, true
  205. }
  206. // rfc2821Mailbox represents a “mailbox” (which is an email address to most
  207. // people) by breaking it into the “local” (i.e. before the '@') and “domain”
  208. // parts.
  209. type rfc2821Mailbox struct {
  210. local, domain string
  211. }
  212. // parseRFC2821Mailbox parses an email address into local and domain parts,
  213. // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
  214. // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
  215. // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
  216. func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
  217. if in == "" {
  218. return mailbox, false
  219. }
  220. localPartBytes := make([]byte, 0, len(in)/2)
  221. if in[0] == '"' {
  222. // Quoted-string = DQUOTE *qcontent DQUOTE
  223. // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
  224. // qcontent = qtext / quoted-pair
  225. // qtext = non-whitespace-control /
  226. // %d33 / %d35-91 / %d93-126
  227. // quoted-pair = ("\" text) / obs-qp
  228. // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
  229. //
  230. // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
  231. // Section 4. Since it has been 16 years, we no longer accept that.)
  232. in = in[1:]
  233. QuotedString:
  234. for {
  235. if in == "" {
  236. return mailbox, false
  237. }
  238. c := in[0]
  239. in = in[1:]
  240. switch {
  241. case c == '"':
  242. break QuotedString
  243. case c == '\\':
  244. // quoted-pair
  245. if in == "" {
  246. return mailbox, false
  247. }
  248. if in[0] == 11 ||
  249. in[0] == 12 ||
  250. (1 <= in[0] && in[0] <= 9) ||
  251. (14 <= in[0] && in[0] <= 127) {
  252. localPartBytes = append(localPartBytes, in[0])
  253. in = in[1:]
  254. } else {
  255. return mailbox, false
  256. }
  257. case c == 11 ||
  258. c == 12 ||
  259. // Space (char 32) is not allowed based on the
  260. // BNF, but RFC 3696 gives an example that
  261. // assumes that it is. Several “verified”
  262. // errata continue to argue about this point.
  263. // We choose to accept it.
  264. c == 32 ||
  265. c == 33 ||
  266. c == 127 ||
  267. (1 <= c && c <= 8) ||
  268. (14 <= c && c <= 31) ||
  269. (35 <= c && c <= 91) ||
  270. (93 <= c && c <= 126):
  271. // qtext
  272. localPartBytes = append(localPartBytes, c)
  273. default:
  274. return mailbox, false
  275. }
  276. }
  277. } else {
  278. // Atom ("." Atom)*
  279. NextChar:
  280. for in != "" {
  281. // atext from RFC 2822, Section 3.2.4
  282. c := in[0]
  283. switch {
  284. case c == '\\':
  285. // Examples given in RFC 3696 suggest that
  286. // escaped characters can appear outside of a
  287. // quoted string. Several “verified” errata
  288. // continue to argue the point. We choose to
  289. // accept it.
  290. in = in[1:]
  291. if in == "" {
  292. return mailbox, false
  293. }
  294. fallthrough
  295. case ('0' <= c && c <= '9') ||
  296. ('a' <= c && c <= 'z') ||
  297. ('A' <= c && c <= 'Z') ||
  298. c == '!' || c == '#' || c == '$' || c == '%' ||
  299. c == '&' || c == '\'' || c == '*' || c == '+' ||
  300. c == '-' || c == '/' || c == '=' || c == '?' ||
  301. c == '^' || c == '_' || c == '`' || c == '{' ||
  302. c == '|' || c == '}' || c == '~' || c == '.':
  303. localPartBytes = append(localPartBytes, in[0])
  304. in = in[1:]
  305. default:
  306. break NextChar
  307. }
  308. }
  309. if len(localPartBytes) == 0 {
  310. return mailbox, false
  311. }
  312. // From RFC 3696, Section 3:
  313. // “period (".") may also appear, but may not be used to start
  314. // or end the local part, nor may two or more consecutive
  315. // periods appear.”
  316. twoDots := []byte{'.', '.'}
  317. if localPartBytes[0] == '.' ||
  318. localPartBytes[len(localPartBytes)-1] == '.' ||
  319. bytes.Contains(localPartBytes, twoDots) {
  320. return mailbox, false
  321. }
  322. }
  323. if in == "" || in[0] != '@' {
  324. return mailbox, false
  325. }
  326. in = in[1:]
  327. // The RFC species a format for domains, but that's known to be
  328. // violated in practice so we accept that anything after an '@' is the
  329. // domain part.
  330. if _, ok := domainToReverseLabels(in); !ok {
  331. return mailbox, false
  332. }
  333. mailbox.local = string(localPartBytes)
  334. mailbox.domain = in
  335. return mailbox, true
  336. }