Skip to content

Commit

Permalink
Merge pull request #18 from irisnet/ht/TLS
Browse files Browse the repository at this point in the history
grpcOption增加TLS的配置项
  • Loading branch information
MaricoHan authored Apr 26, 2022
2 parents dc2516a + 621b55e commit 47e4250
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
22 changes: 20 additions & 2 deletions types/config.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package types

import (
"crypto/x509"
"fmt"
"os"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"

"github.com/irisnet/core-sdk-go/common/crypto"
"github.com/irisnet/core-sdk-go/types/store"
Expand Down Expand Up @@ -333,9 +335,25 @@ func WSAddrOption(wsAddr string) Option {
}
}

func GRPCOptions(gRPCOptions []grpc.DialOption) Option {
func GRPCOptions(gRPCOptions []grpc.DialOption, TLS bool, rpcAddr string) Option {
return func(cfg *ClientConfig) error {
cfg.GRPCOptions = gRPCOptions
if !TLS {
cfg.GRPCOptions = gRPCOptions
return nil
}

certificateList, err := GetTLSCertPool(rpcAddr)
if err != nil {
panic(err)
}

roots := x509.NewCertPool()
for i := range certificateList {
roots.AddCert(certificateList[i])
}
cert := credentials.NewClientTLSFromCert(roots, "")
cfg.GRPCOptions = append(gRPCOptions, grpc.WithTransportCredentials(cert))

return nil
}
}
Expand Down
30 changes: 30 additions & 0 deletions types/utils.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package types

import (
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
)

Expand Down Expand Up @@ -73,3 +78,28 @@ func CopyBytes(bz []byte) (ret []byte) {
copy(ret, bz)
return ret
}

// GetTLSCertPool get certificates from target server
func GetTLSCertPool(gateWayURL string) ([]*x509.Certificate, error) {
if !strings.Contains(strings.ToLower(gateWayURL), "https://") {
return nil, errors.New("this function requires HTTPS protocol")
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}

resp, err := client.Get(gateWayURL)
defer func() {
closeErr := resp.Body.Close()
if err == nil {
err = closeErr
}
}()

if err != nil {
return nil, err
}

return resp.TLS.PeerCertificates, err
}

0 comments on commit 47e4250

Please sign in to comment.