ssh.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package sshpolicy
  2. import (
  3. "bytes"
  4. "crypto/x509"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. "github.com/pkg/errors"
  9. "golang.org/x/crypto/ssh"
  10. )
  11. type CertificateInvalidError struct {
  12. Reason x509.InvalidReason
  13. Detail string
  14. }
  15. func (e CertificateInvalidError) Error() string {
  16. switch e.Reason {
  17. // TODO: include logical errors for this package; exlude ones that don't make sense for its current use case?
  18. // TODO: currently only CANotAuthorizedForThisName is used by this package; we're not checking the other things in CSRs in this package.
  19. case x509.NotAuthorizedToSign:
  20. return "not authorized to sign other certificates" // TODO: this one doesn't make sense for this pkg
  21. case x509.Expired:
  22. return "csr has expired or is not yet valid: " + e.Detail
  23. case x509.CANotAuthorizedForThisName:
  24. return "not authorized to sign for this name: " + e.Detail
  25. case x509.CANotAuthorizedForExtKeyUsage:
  26. return "not authorized for an extended key usage: " + e.Detail
  27. case x509.TooManyIntermediates:
  28. return "too many intermediates for path length constraint"
  29. case x509.IncompatibleUsage:
  30. return "csr specifies an incompatible key usage"
  31. case x509.NameMismatch:
  32. return "issuer name does not match subject from issuing certificate"
  33. case x509.NameConstraintsWithoutSANs:
  34. return "issuer has name constraints but csr doesn't have a SAN extension"
  35. case x509.UnconstrainedName:
  36. return "issuer has name constraints but csr contains unknown or unconstrained name: " + e.Detail
  37. }
  38. return "unknown error"
  39. }
  40. type NamePolicyEngine struct {
  41. options []NamePolicyOption
  42. permittedDNSDomains []string
  43. excludedDNSDomains []string
  44. permittedEmailAddresses []string
  45. excludedEmailAddresses []string
  46. permittedPrincipals []string // TODO: rename to usernames, as principals can be host, user@ (like mail) and usernames?
  47. excludedPrincipals []string
  48. }
  49. func New(opts ...NamePolicyOption) (*NamePolicyEngine, error) {
  50. e := &NamePolicyEngine{} // TODO: embed an x509 engine instead of building it again?
  51. e.options = append(e.options, opts...)
  52. for _, option := range e.options {
  53. if err := option(e); err != nil {
  54. return nil, err
  55. }
  56. }
  57. return e, nil
  58. }
  59. func (e *NamePolicyEngine) ArePrincipalsAllowed(cert *ssh.Certificate) (bool, error) {
  60. dnsNames, emails, userNames := splitPrincipals(cert.ValidPrincipals)
  61. if err := e.validateNames(dnsNames, emails, userNames); err != nil {
  62. return false, err
  63. }
  64. return true, nil
  65. }
  66. func (e *NamePolicyEngine) validateNames(dnsNames, emails, userNames []string) error {
  67. //"dns": ["*.smallstep.com"],
  68. //"email": ["@smallstep.com", "@google.com"],
  69. //"principal": ["max", "mariano", "mike"]
  70. /* No regexes for now. But if we ever implement them, they'd probably look like this */
  71. /*"principal": ["foo.smallstep.com", "/^*\.smallstep\.com$/"]*/
  72. // Principals can be single user names (mariano, max, mike, ...), hostnames/domains (*.smallstep.com, host.smallstep.com, ...) and "emails" (max@smallstep.com, @smallstep.com, ...)
  73. // All ValidPrincipals can thus be any one of those, and they can be mixed (mike@smallstep.com, mike, ...); we need to split this?
  74. // Should we assume a generic engine, or can we do it host vs. user based? If host vs. user based, then it becomes easier w.r.t. dns; hosts will only be DNS, right?
  75. // If we assume generic, we _may_ have a harder time distinguishing host vs. user certs. We propose to use host + user specific provisioners, though...
  76. // Perhaps we can do some heuristics on the principal names vs. hostnames (i.e. when only a single label and no dot, then it's a user principal)
  77. for _, dns := range dnsNames {
  78. if _, ok := domainToReverseLabels(dns); !ok {
  79. return errors.Errorf("cannot parse dns %q", dns)
  80. }
  81. if err := checkNameConstraints("dns", dns, dns,
  82. func(parsedName, constraint interface{}) (bool, error) {
  83. return matchDomainConstraint(parsedName.(string), constraint.(string))
  84. }, e.permittedDNSDomains, e.excludedDNSDomains); err != nil {
  85. return err
  86. }
  87. }
  88. for _, email := range emails {
  89. mailbox, ok := parseRFC2821Mailbox(email)
  90. if !ok {
  91. return fmt.Errorf("cannot parse rfc822Name %q", mailbox)
  92. }
  93. if err := checkNameConstraints("email", email, mailbox,
  94. func(parsedName, constraint interface{}) (bool, error) {
  95. return matchEmailConstraint(parsedName.(rfc2821Mailbox), constraint.(string))
  96. }, e.permittedEmailAddresses, e.excludedEmailAddresses); err != nil {
  97. return err
  98. }
  99. }
  100. for _, userName := range userNames {
  101. // TODO: some validation? I.e. allowed characters?
  102. if err := checkNameConstraints("username", userName, userName,
  103. func(parsedName, constraint interface{}) (bool, error) {
  104. return matchUserNameConstraint(parsedName.(string), constraint.(string))
  105. }, e.permittedPrincipals, e.excludedPrincipals); err != nil {
  106. return err
  107. }
  108. }
  109. return nil
  110. }
  111. // splitPrincipals splits SSH certificate principals into DNS names, emails and user names.
  112. func splitPrincipals(principals []string) (dnsNames, emails, userNames []string) {
  113. dnsNames = []string{}
  114. emails = []string{}
  115. userNames = []string{}
  116. for _, principal := range principals {
  117. if strings.Contains(principal, "@") {
  118. emails = append(emails, principal)
  119. } else if len(strings.Split(principal, ".")) > 1 {
  120. dnsNames = append(dnsNames, principal)
  121. } else {
  122. userNames = append(userNames, principal)
  123. }
  124. }
  125. return
  126. }
  127. // checkNameConstraints checks that c permits a child certificate to claim the
  128. // given name, of type nameType. The argument parsedName contains the parsed
  129. // form of name, suitable for passing to the match function. The total number
  130. // of comparisons is tracked in the given count and should not exceed the given
  131. // limit.
  132. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  133. func checkNameConstraints(
  134. nameType string,
  135. name string,
  136. parsedName interface{},
  137. match func(parsedName, constraint interface{}) (match bool, err error),
  138. permitted, excluded interface{}) error {
  139. excludedValue := reflect.ValueOf(excluded)
  140. // *count += excludedValue.Len()
  141. // if *count > maxConstraintComparisons {
  142. // return x509.CertificateInvalidError{c, x509.TooManyConstraints, ""}
  143. // }
  144. // TODO: fix the errors; return our own, because we don't have cert ...
  145. for i := 0; i < excludedValue.Len(); i++ {
  146. constraint := excludedValue.Index(i).Interface()
  147. match, err := match(parsedName, constraint)
  148. if err != nil {
  149. return CertificateInvalidError{
  150. Reason: x509.CANotAuthorizedForThisName,
  151. Detail: err.Error(),
  152. }
  153. }
  154. if match {
  155. return CertificateInvalidError{
  156. Reason: x509.CANotAuthorizedForThisName,
  157. Detail: fmt.Sprintf("%s %q is excluded by constraint %q", nameType, name, constraint),
  158. }
  159. }
  160. }
  161. permittedValue := reflect.ValueOf(permitted)
  162. // *count += permittedValue.Len()
  163. // if *count > maxConstraintComparisons {
  164. // return x509.CertificateInvalidError{c, x509.TooManyConstraints, ""}
  165. // }
  166. ok := true
  167. for i := 0; i < permittedValue.Len(); i++ {
  168. constraint := permittedValue.Index(i).Interface()
  169. var err error
  170. if ok, err = match(parsedName, constraint); err != nil {
  171. return CertificateInvalidError{
  172. Reason: x509.CANotAuthorizedForThisName,
  173. Detail: err.Error(),
  174. }
  175. }
  176. if ok {
  177. break
  178. }
  179. }
  180. if !ok {
  181. return CertificateInvalidError{
  182. Reason: x509.CANotAuthorizedForThisName,
  183. Detail: fmt.Sprintf("%s %q is not permitted by any constraint", nameType, name),
  184. }
  185. }
  186. return nil
  187. }
  188. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  189. func matchDomainConstraint(domain, constraint string) (bool, error) {
  190. // The meaning of zero length constraints is not specified, but this
  191. // code follows NSS and accepts them as matching everything.
  192. if constraint == "" {
  193. return true, nil
  194. }
  195. domainLabels, ok := domainToReverseLabels(domain)
  196. if !ok {
  197. return false, fmt.Errorf("cannot parse domain %q", domain)
  198. }
  199. // RFC 5280 says that a leading period in a domain name means that at
  200. // least one label must be prepended, but only for URI and email
  201. // constraints, not DNS constraints. The code also supports that
  202. // behavior for DNS constraints.
  203. mustHaveSubdomains := false
  204. if constraint[0] == '.' {
  205. mustHaveSubdomains = true
  206. constraint = constraint[1:]
  207. }
  208. constraintLabels, ok := domainToReverseLabels(constraint)
  209. if !ok {
  210. return false, fmt.Errorf("cannot parse domain %q", constraint)
  211. }
  212. if len(domainLabels) < len(constraintLabels) ||
  213. (mustHaveSubdomains && len(domainLabels) == len(constraintLabels)) {
  214. return false, nil
  215. }
  216. for i, constraintLabel := range constraintLabels {
  217. if !strings.EqualFold(constraintLabel, domainLabels[i]) {
  218. return false, nil
  219. }
  220. }
  221. return true, nil
  222. }
  223. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  224. func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error) {
  225. // If the constraint contains an @, then it specifies an exact mailbox name.
  226. if strings.Contains(constraint, "@") {
  227. constraintMailbox, ok := parseRFC2821Mailbox(constraint)
  228. if !ok {
  229. return false, fmt.Errorf("cannot parse constraint %q", constraint)
  230. }
  231. return mailbox.local == constraintMailbox.local && strings.EqualFold(mailbox.domain, constraintMailbox.domain), nil
  232. }
  233. // Otherwise the constraint is like a DNS constraint of the domain part
  234. // of the mailbox.
  235. return matchDomainConstraint(mailbox.domain, constraint)
  236. }
  237. // matchUserNameConstraint performs a string literal match against a constraint
  238. func matchUserNameConstraint(userName, constraint string) (bool, error) {
  239. return userName == constraint, nil
  240. }
  241. // TODO: decrease code duplication: single policy engine again, with principals added, but not used in x509?
  242. // Not sure how I'd like to model that in Go, though: use (embedded) structs? interfaces? An x509 name policy engine
  243. // interface could expose the methods that are useful to x509; the SSH name policy engine interfaces could do the
  244. // same for SSH ones. One interface for both (with no methods?); then two, so that not all name policy options
  245. // can be executed on both types? The shared ones could then maybe use the one with no methods? But we need protect
  246. // it from being applied to just any type, of course. Not sure if Go allows us to do something like that, though.
  247. // Maybe some kind of dummy function helps there?
  248. // domainToReverseLabels converts a textual domain name like foo.example.com to
  249. // the list of labels in reverse order, e.g. ["com", "example", "foo"].
  250. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  251. func domainToReverseLabels(domain string) (reverseLabels []string, ok bool) {
  252. for len(domain) > 0 {
  253. if i := strings.LastIndexByte(domain, '.'); i == -1 {
  254. reverseLabels = append(reverseLabels, domain)
  255. domain = ""
  256. } else {
  257. reverseLabels = append(reverseLabels, domain[i+1:])
  258. domain = domain[:i]
  259. }
  260. }
  261. if len(reverseLabels) > 0 && reverseLabels[0] == "" {
  262. // An empty label at the end indicates an absolute value.
  263. return nil, false
  264. }
  265. for _, label := range reverseLabels {
  266. if label == "" {
  267. // Empty labels are otherwise invalid.
  268. return nil, false
  269. }
  270. for _, c := range label {
  271. if c < 33 || c > 126 {
  272. // Invalid character.
  273. return nil, false
  274. }
  275. }
  276. }
  277. return reverseLabels, true
  278. }
  279. // rfc2821Mailbox represents a “mailbox” (which is an email address to most
  280. // people) by breaking it into the “local” (i.e. before the '@') and “domain”
  281. // parts.
  282. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  283. type rfc2821Mailbox struct {
  284. local, domain string
  285. }
  286. // parseRFC2821Mailbox parses an email address into local and domain parts,
  287. // based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
  288. // Section 4.2.1.6 that's correct for an rfc822Name from a certificate: “The
  289. // format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section 4.1.2”.
  290. // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go
  291. func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool) {
  292. if in == "" {
  293. return mailbox, false
  294. }
  295. localPartBytes := make([]byte, 0, len(in)/2)
  296. if in[0] == '"' {
  297. // Quoted-string = DQUOTE *qcontent DQUOTE
  298. // non-whitespace-control = %d1-8 / %d11 / %d12 / %d14-31 / %d127
  299. // qcontent = qtext / quoted-pair
  300. // qtext = non-whitespace-control /
  301. // %d33 / %d35-91 / %d93-126
  302. // quoted-pair = ("\" text) / obs-qp
  303. // text = %d1-9 / %d11 / %d12 / %d14-127 / obs-text
  304. //
  305. // (Names beginning with “obs-” are the obsolete syntax from RFC 2822,
  306. // Section 4. Since it has been 16 years, we no longer accept that.)
  307. in = in[1:]
  308. QuotedString:
  309. for {
  310. if in == "" {
  311. return mailbox, false
  312. }
  313. c := in[0]
  314. in = in[1:]
  315. switch {
  316. case c == '"':
  317. break QuotedString
  318. case c == '\\':
  319. // quoted-pair
  320. if in == "" {
  321. return mailbox, false
  322. }
  323. if in[0] == 11 ||
  324. in[0] == 12 ||
  325. (1 <= in[0] && in[0] <= 9) ||
  326. (14 <= in[0] && in[0] <= 127) {
  327. localPartBytes = append(localPartBytes, in[0])
  328. in = in[1:]
  329. } else {
  330. return mailbox, false
  331. }
  332. case c == 11 ||
  333. c == 12 ||
  334. // Space (char 32) is not allowed based on the
  335. // BNF, but RFC 3696 gives an example that
  336. // assumes that it is. Several “verified”
  337. // errata continue to argue about this point.
  338. // We choose to accept it.
  339. c == 32 ||
  340. c == 33 ||
  341. c == 127 ||
  342. (1 <= c && c <= 8) ||
  343. (14 <= c && c <= 31) ||
  344. (35 <= c && c <= 91) ||
  345. (93 <= c && c <= 126):
  346. // qtext
  347. localPartBytes = append(localPartBytes, c)
  348. default:
  349. return mailbox, false
  350. }
  351. }
  352. } else {
  353. // Atom ("." Atom)*
  354. NextChar:
  355. for len(in) > 0 {
  356. // atext from RFC 2822, Section 3.2.4
  357. c := in[0]
  358. switch {
  359. case c == '\\':
  360. // Examples given in RFC 3696 suggest that
  361. // escaped characters can appear outside of a
  362. // quoted string. Several “verified” errata
  363. // continue to argue the point. We choose to
  364. // accept it.
  365. in = in[1:]
  366. if in == "" {
  367. return mailbox, false
  368. }
  369. fallthrough
  370. case ('0' <= c && c <= '9') ||
  371. ('a' <= c && c <= 'z') ||
  372. ('A' <= c && c <= 'Z') ||
  373. c == '!' || c == '#' || c == '$' || c == '%' ||
  374. c == '&' || c == '\'' || c == '*' || c == '+' ||
  375. c == '-' || c == '/' || c == '=' || c == '?' ||
  376. c == '^' || c == '_' || c == '`' || c == '{' ||
  377. c == '|' || c == '}' || c == '~' || c == '.':
  378. localPartBytes = append(localPartBytes, in[0])
  379. in = in[1:]
  380. default:
  381. break NextChar
  382. }
  383. }
  384. if len(localPartBytes) == 0 {
  385. return mailbox, false
  386. }
  387. // From RFC 3696, Section 3:
  388. // “period (".") may also appear, but may not be used to start
  389. // or end the local part, nor may two or more consecutive
  390. // periods appear.”
  391. twoDots := []byte{'.', '.'}
  392. if localPartBytes[0] == '.' ||
  393. localPartBytes[len(localPartBytes)-1] == '.' ||
  394. bytes.Contains(localPartBytes, twoDots) {
  395. return mailbox, false
  396. }
  397. }
  398. if in == "" || in[0] != '@' {
  399. return mailbox, false
  400. }
  401. in = in[1:]
  402. // The RFC species a format for domains, but that's known to be
  403. // violated in practice so we accept that anything after an '@' is the
  404. // domain part.
  405. if _, ok := domainToReverseLabels(in); !ok {
  406. return mailbox, false
  407. }
  408. mailbox.local = string(localPartBytes)
  409. mailbox.domain = in
  410. return mailbox, true
  411. }