github.com/openimsdk/tools@v0.0.49/mq/kafka/tls.go (about) 1 // Copyright © 2024 OpenIM open source community. All rights reserved. 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 kafka 16 17 import ( 18 "crypto/tls" 19 "crypto/x509" 20 "encoding/pem" 21 "os" 22 23 "github.com/openimsdk/tools/errs" 24 ) 25 26 // decryptPEM decrypts a PEM block using a password. 27 func decryptPEM(data []byte, passphrase []byte) ([]byte, error) { 28 if len(passphrase) == 0 { 29 return data, nil 30 } 31 b, _ := pem.Decode(data) 32 d, err := x509.DecryptPEMBlock(b, passphrase) 33 if err != nil { 34 return nil, errs.WrapMsg(err, "DecryptPEMBlock failed") 35 } 36 return pem.EncodeToMemory(&pem.Block{ 37 Type: b.Type, 38 Bytes: d, 39 }), nil 40 } 41 42 func readEncryptablePEMBlock(path string, pwd []byte) ([]byte, error) { 43 data, err := os.ReadFile(path) 44 if err != nil { 45 return nil, errs.WrapMsg(err, "ReadFile failed", "path", path) 46 } 47 return decryptPEM(data, pwd) 48 } 49 50 // newTLSConfig setup the TLS config from general config file. 51 func newTLSConfig(clientCertFile, clientKeyFile, caCertFile string, keyPwd []byte, insecureSkipVerify bool) (*tls.Config, error) { 52 var tlsConfig tls.Config 53 if clientCertFile != "" && clientKeyFile != "" { 54 certPEMBlock, err := os.ReadFile(clientCertFile) 55 if err != nil { 56 return nil, errs.WrapMsg(err, "ReadFile failed", "clientCertFile", clientCertFile) 57 } 58 keyPEMBlock, err := readEncryptablePEMBlock(clientKeyFile, keyPwd) 59 if err != nil { 60 return nil, err 61 } 62 63 cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) 64 if err != nil { 65 return nil, errs.WrapMsg(err, "X509KeyPair failed") 66 } 67 tlsConfig.Certificates = []tls.Certificate{cert} 68 } 69 70 if caCertFile != "" { 71 caCert, err := os.ReadFile(caCertFile) 72 if err != nil { 73 return nil, errs.WrapMsg(err, "ReadFile failed", "caCertFile", caCertFile) 74 } 75 caCertPool := x509.NewCertPool() 76 if ok := caCertPool.AppendCertsFromPEM(caCert); !ok { 77 return nil, errs.New("AppendCertsFromPEM failed") 78 } 79 tlsConfig.RootCAs = caCertPool 80 } 81 tlsConfig.InsecureSkipVerify = insecureSkipVerify 82 return &tlsConfig, nil 83 }