engine.go 29 KB

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