tls.go 786 B

1234567891011121314151617181920212223242526272829303132
  1. package missinggo
  2. import (
  3. "crypto/tls"
  4. "strings"
  5. )
  6. // Select the best named certificate per the usual behaviour if
  7. // c.GetCertificate is nil, and c.NameToCertificate is not.
  8. func BestNamedCertificate(c *tls.Config, clientHello *tls.ClientHelloInfo) (*tls.Certificate, bool) {
  9. name := strings.ToLower(clientHello.ServerName)
  10. for len(name) > 0 && name[len(name)-1] == '.' {
  11. name = name[:len(name)-1]
  12. }
  13. if cert, ok := c.NameToCertificate[name]; ok {
  14. return cert, true
  15. }
  16. // try replacing labels in the name with wildcards until we get a
  17. // match.
  18. labels := strings.Split(name, ".")
  19. for i := range labels {
  20. labels[i] = "*"
  21. candidate := strings.Join(labels, ".")
  22. if cert, ok := c.NameToCertificate[candidate]; ok {
  23. return cert, true
  24. }
  25. }
  26. return nil, false
  27. }