github.com/binyushen/fabric@v2.1.1+incompatible/core/operations/tls.go (about)

     1  /*
     2  Copyright IBM Corp All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package operations
     8  
     9  import (
    10  	"crypto/tls"
    11  	"crypto/x509"
    12  	"io/ioutil"
    13  
    14  	"github.com/hyperledger/fabric/internal/pkg/comm"
    15  )
    16  
    17  type TLS struct {
    18  	Enabled            bool
    19  	CertFile           string
    20  	KeyFile            string
    21  	ClientCertRequired bool
    22  	ClientCACertFiles  []string
    23  }
    24  
    25  func (t TLS) Config() (*tls.Config, error) {
    26  	var tlsConfig *tls.Config
    27  
    28  	if t.Enabled {
    29  		cert, err := tls.LoadX509KeyPair(t.CertFile, t.KeyFile)
    30  		if err != nil {
    31  			return nil, err
    32  		}
    33  		caCertPool := x509.NewCertPool()
    34  		for _, caPath := range t.ClientCACertFiles {
    35  			caPem, err := ioutil.ReadFile(caPath)
    36  			if err != nil {
    37  				return nil, err
    38  			}
    39  			caCertPool.AppendCertsFromPEM(caPem)
    40  		}
    41  		tlsConfig = &tls.Config{
    42  			Certificates: []tls.Certificate{cert},
    43  			CipherSuites: comm.DefaultTLSCipherSuites,
    44  			ClientCAs:    caCertPool,
    45  		}
    46  		if t.ClientCertRequired {
    47  			tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
    48  		} else {
    49  			tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
    50  		}
    51  	}
    52  
    53  	return tlsConfig, nil
    54  }