github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/pkg/mysqldriver/tls.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package mysqldriver 16 17 import ( 18 "crypto/tls" 19 "crypto/x509" 20 "fmt" 21 "io/ioutil" 22 23 "github.com/go-sql-driver/mysql" 24 ) 25 26 // OpenTLS according to the passed parameters, decide whether to register tls config for mysql driver 27 func OpenTLS(tlsName, mysqlCaCertPath, mysqlClientCertPath, mysqlClientKeyPath string) error { 28 if tlsName == "" || mysqlCaCertPath == "" { 29 return nil 30 } 31 32 rootCertPool := x509.NewCertPool() 33 pem, err := ioutil.ReadFile(mysqlCaCertPath) 34 if err != nil { 35 return err 36 } 37 if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { 38 return fmt.Errorf("failed to append PEM") 39 } 40 41 if mysqlClientCertPath == "" || mysqlClientKeyPath == "" { 42 // skip client cert 43 err = mysql.RegisterTLSConfig(tlsName, &tls.Config{ 44 RootCAs: rootCertPool, 45 }) 46 return err 47 } 48 49 clientCert := make([]tls.Certificate, 0, 1) 50 certs, err := tls.LoadX509KeyPair(mysqlClientCertPath, mysqlClientKeyPath) 51 if err != nil { 52 return fmt.Errorf("failed to append client PEM %v", err) 53 } 54 clientCert = append(clientCert, certs) 55 // two-way encryption 56 err = mysql.RegisterTLSConfig(tlsName, &tls.Config{ 57 RootCAs: rootCertPool, 58 Certificates: clientCert, 59 }) 60 return err 61 }