You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

238 lines
7.6 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package security
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "os"
  7. "slices"
  8. "strings"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. "github.com/seaweedfs/seaweedfs/weed/util"
  12. "google.golang.org/grpc"
  13. "google.golang.org/grpc/credentials/insecure"
  14. "google.golang.org/grpc/credentials/tls/certprovider/pemfile"
  15. "google.golang.org/grpc/security/advancedtls"
  16. )
  17. const CredRefreshingInterval = time.Duration(5) * time.Hour
  18. type Authenticator struct {
  19. AllowedWildcardDomain string
  20. AllowedCommonNames map[string]bool
  21. }
  22. func LoadServerTLS(config *util.ViperProxy, component string) (grpc.ServerOption, grpc.ServerOption) {
  23. if config == nil {
  24. return nil, nil
  25. }
  26. serverOptions := pemfile.Options{
  27. CertFile: config.GetString(component + ".cert"),
  28. KeyFile: config.GetString(component + ".key"),
  29. RefreshDuration: CredRefreshingInterval,
  30. }
  31. if serverOptions.CertFile == "" || serverOptions.KeyFile == "" {
  32. return nil, nil
  33. }
  34. serverIdentityProvider, err := pemfile.NewProvider(serverOptions)
  35. if err != nil {
  36. glog.Warningf("pemfile.NewProvider(%v) %v failed: %v", serverOptions, component, err)
  37. return nil, nil
  38. }
  39. serverRootOptions := pemfile.Options{
  40. RootFile: config.GetString("grpc.ca"),
  41. RefreshDuration: CredRefreshingInterval,
  42. }
  43. serverRootProvider, err := pemfile.NewProvider(serverRootOptions)
  44. if err != nil {
  45. glog.Warningf("pemfile.NewProvider(%v) failed: %v", serverRootOptions, err)
  46. return nil, nil
  47. }
  48. // Start a server and create a client using advancedtls API with Provider.
  49. options := &advancedtls.Options{
  50. IdentityOptions: advancedtls.IdentityCertificateOptions{
  51. IdentityProvider: serverIdentityProvider,
  52. },
  53. RootOptions: advancedtls.RootCertificateOptions{
  54. RootProvider: serverRootProvider,
  55. },
  56. RequireClientCert: true,
  57. VerificationType: advancedtls.CertVerification,
  58. }
  59. options.MinTLSVersion, err = TlsVersionByName(config.GetString("tls.min_version"))
  60. if err != nil {
  61. glog.Warningf("tls min version parse failed, %v", err)
  62. return nil, nil
  63. }
  64. options.MaxTLSVersion, err = TlsVersionByName(config.GetString("tls.max_version"))
  65. if err != nil {
  66. glog.Warningf("tls max version parse failed, %v", err)
  67. return nil, nil
  68. }
  69. options.CipherSuites, err = TlsCipherSuiteByNames(config.GetString("tls.cipher_suites"))
  70. if err != nil {
  71. glog.Warningf("tls cipher suite parse failed, %v", err)
  72. return nil, nil
  73. }
  74. allowedCommonNames := config.GetString(component + ".allowed_commonNames")
  75. allowedWildcardDomain := config.GetString("grpc.allowed_wildcard_domain")
  76. if allowedCommonNames != "" || allowedWildcardDomain != "" {
  77. allowedCommonNamesMap := make(map[string]bool)
  78. for _, s := range strings.Split(allowedCommonNames, ",") {
  79. allowedCommonNamesMap[s] = true
  80. }
  81. auther := Authenticator{
  82. AllowedCommonNames: allowedCommonNamesMap,
  83. AllowedWildcardDomain: allowedWildcardDomain,
  84. }
  85. options.AdditionalPeerVerification = auther.Authenticate
  86. } else {
  87. options.AdditionalPeerVerification = func(params *advancedtls.HandshakeVerificationInfo) (*advancedtls.PostHandshakeVerificationResults, error) {
  88. return &advancedtls.PostHandshakeVerificationResults{}, nil
  89. }
  90. }
  91. ta, err := advancedtls.NewServerCreds(options)
  92. if err != nil {
  93. glog.Warningf("advancedtls.NewServerCreds(%v) failed: %v", options, err)
  94. return nil, nil
  95. }
  96. return grpc.Creds(ta), nil
  97. }
  98. func LoadClientTLS(config *util.ViperProxy, component string) grpc.DialOption {
  99. if config == nil {
  100. return grpc.WithTransportCredentials(insecure.NewCredentials())
  101. }
  102. certFileName, keyFileName, caFileName := config.GetString(component+".cert"), config.GetString(component+".key"), config.GetString("grpc.ca")
  103. if certFileName == "" || keyFileName == "" || caFileName == "" {
  104. return grpc.WithTransportCredentials(insecure.NewCredentials())
  105. }
  106. clientOptions := pemfile.Options{
  107. CertFile: certFileName,
  108. KeyFile: keyFileName,
  109. RefreshDuration: CredRefreshingInterval,
  110. }
  111. clientProvider, err := pemfile.NewProvider(clientOptions)
  112. if err != nil {
  113. glog.Warningf("pemfile.NewProvider(%v) failed %v", clientOptions, err)
  114. return grpc.WithTransportCredentials(insecure.NewCredentials())
  115. }
  116. clientRootOptions := pemfile.Options{
  117. RootFile: config.GetString("grpc.ca"),
  118. RefreshDuration: CredRefreshingInterval,
  119. }
  120. clientRootProvider, err := pemfile.NewProvider(clientRootOptions)
  121. if err != nil {
  122. glog.Warningf("pemfile.NewProvider(%v) failed: %v", clientRootOptions, err)
  123. return grpc.WithTransportCredentials(insecure.NewCredentials())
  124. }
  125. options := &advancedtls.Options{
  126. IdentityOptions: advancedtls.IdentityCertificateOptions{
  127. IdentityProvider: clientProvider,
  128. },
  129. AdditionalPeerVerification: func(params *advancedtls.HandshakeVerificationInfo) (*advancedtls.PostHandshakeVerificationResults, error) {
  130. return &advancedtls.PostHandshakeVerificationResults{}, nil
  131. },
  132. RootOptions: advancedtls.RootCertificateOptions{
  133. RootProvider: clientRootProvider,
  134. },
  135. VerificationType: advancedtls.CertVerification,
  136. }
  137. ta, err := advancedtls.NewClientCreds(options)
  138. if err != nil {
  139. glog.Warningf("advancedtls.NewClientCreds(%v) failed: %v", options, err)
  140. return grpc.WithTransportCredentials(insecure.NewCredentials())
  141. }
  142. return grpc.WithTransportCredentials(ta)
  143. }
  144. func LoadClientTLSHTTP(clientCertFile string) *tls.Config {
  145. clientCerts, err := os.ReadFile(clientCertFile)
  146. if err != nil {
  147. glog.Fatal(err)
  148. }
  149. certPool := x509.NewCertPool()
  150. ok := certPool.AppendCertsFromPEM(clientCerts)
  151. if !ok {
  152. glog.Fatalf("Error processing client certificate in %s\n", clientCertFile)
  153. }
  154. return &tls.Config{
  155. ClientCAs: certPool,
  156. ClientAuth: tls.RequireAndVerifyClientCert,
  157. }
  158. }
  159. func (a Authenticator) Authenticate(params *advancedtls.HandshakeVerificationInfo) (*advancedtls.PostHandshakeVerificationResults, error) {
  160. if a.AllowedWildcardDomain != "" && strings.HasSuffix(params.Leaf.Subject.CommonName, a.AllowedWildcardDomain) {
  161. return &advancedtls.PostHandshakeVerificationResults{}, nil
  162. }
  163. if _, ok := a.AllowedCommonNames[params.Leaf.Subject.CommonName]; ok {
  164. return &advancedtls.PostHandshakeVerificationResults{}, nil
  165. }
  166. err := fmt.Errorf("Authenticate: invalid subject client common name: %s", params.Leaf.Subject.CommonName)
  167. glog.Error(err)
  168. return nil, err
  169. }
  170. func FixTlsConfig(viper *util.ViperProxy, config *tls.Config) error {
  171. var err error
  172. config.MinVersion, err = TlsVersionByName(viper.GetString("tls.min_version"))
  173. if err != nil {
  174. return err
  175. }
  176. config.MaxVersion, err = TlsVersionByName(viper.GetString("tls.max_version"))
  177. if err != nil {
  178. return err
  179. }
  180. config.CipherSuites, err = TlsCipherSuiteByNames(viper.GetString("tls.cipher_suites"))
  181. return err
  182. }
  183. func TlsVersionByName(name string) (uint16, error) {
  184. switch name {
  185. case "":
  186. return 0, nil
  187. case "SSLv3":
  188. return tls.VersionSSL30, nil
  189. case "TLS 1.0":
  190. return tls.VersionTLS10, nil
  191. case "TLS 1.1":
  192. return tls.VersionTLS11, nil
  193. case "TLS 1.2":
  194. return tls.VersionTLS12, nil
  195. case "TLS 1.3":
  196. return tls.VersionTLS13, nil
  197. default:
  198. return 0, fmt.Errorf("invalid tls version %s", name)
  199. }
  200. }
  201. func TlsCipherSuiteByNames(cipherSuiteNames string) ([]uint16, error) {
  202. cipherSuiteNames = strings.TrimSpace(cipherSuiteNames)
  203. if cipherSuiteNames == "" {
  204. return nil, nil
  205. }
  206. names := strings.Split(cipherSuiteNames, ",")
  207. cipherSuites := tls.CipherSuites()
  208. cipherIds := make([]uint16, 0, len(names))
  209. for _, name := range names {
  210. name = strings.TrimSpace(name)
  211. index := slices.IndexFunc(cipherSuites, func(suite *tls.CipherSuite) bool {
  212. return name == suite.Name
  213. })
  214. if index == -1 {
  215. return nil, fmt.Errorf("invalid tls cipher suite name %s", name)
  216. }
  217. cipherIds = append(cipherIds, cipherSuites[index].ID)
  218. }
  219. return cipherIds, nil
  220. }