github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/gossip/comm/crypto.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package comm
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"crypto/elliptic"
    22  	"crypto/rand"
    23  	"crypto/tls"
    24  	"crypto/x509"
    25  	"encoding/pem"
    26  	"math/big"
    27  	"net"
    28  	"os"
    29  	"time"
    30  
    31  	"github.com/hyperledger/fabric/common/util"
    32  	"golang.org/x/net/context"
    33  	"google.golang.org/grpc/credentials"
    34  	"google.golang.org/grpc/peer"
    35  )
    36  
    37  func writeFile(filename string, keyType string, data []byte) error {
    38  	f, err := os.Create(filename)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	defer f.Close()
    43  	return pem.Encode(f, &pem.Block{Type: keyType, Bytes: data})
    44  }
    45  
    46  func generateCertificates(privKeyFile string, certKeyFile string) error {
    47  	privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	sn, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
    53  	template := x509.Certificate{
    54  		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
    55  		SerialNumber: sn,
    56  		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
    57  	}
    58  	rawBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	err = writeFile(certKeyFile, "CERTIFICATE", rawBytes)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	privBytes, err := x509.MarshalECPrivateKey(privateKey)
    67  	if err != nil {
    68  		return err
    69  	}
    70  	err = writeFile(privKeyFile, "EC PRIVATE KEY", privBytes)
    71  	return err
    72  }
    73  
    74  func certHashFromRawCert(rawCert []byte) []byte {
    75  	if len(rawCert) == 0 {
    76  		return nil
    77  	}
    78  	return util.ComputeSHA256(rawCert)
    79  }
    80  
    81  // ExtractCertificateHash extracts the hash of the certificate from the stream
    82  func extractCertificateHashFromContext(ctx context.Context) []byte {
    83  	pr, extracted := peer.FromContext(ctx)
    84  	if !extracted {
    85  		return nil
    86  	}
    87  
    88  	authInfo := pr.AuthInfo
    89  	if authInfo == nil {
    90  		return nil
    91  	}
    92  
    93  	tlsInfo, isTLSConn := authInfo.(credentials.TLSInfo)
    94  	if !isTLSConn {
    95  		return nil
    96  	}
    97  	certs := tlsInfo.State.PeerCertificates
    98  	if len(certs) == 0 {
    99  		return nil
   100  	}
   101  	raw := certs[0].Raw
   102  	return certHashFromRawCert(raw)
   103  }
   104  
   105  type authCreds struct {
   106  	tlsCreds credentials.TransportCredentials
   107  }
   108  
   109  func (c authCreds) Info() credentials.ProtocolInfo {
   110  	return c.tlsCreds.Info()
   111  }
   112  
   113  func (c *authCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (_ net.Conn, _ credentials.AuthInfo, err error) {
   114  	conn, auth, err := c.tlsCreds.ClientHandshake(addr, rawConn, timeout)
   115  	if auth == nil && conn != nil {
   116  		auth = credentials.TLSInfo{State: conn.(*tls.Conn).ConnectionState()}
   117  	}
   118  	return conn, auth, err
   119  }
   120  
   121  func (c *authCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
   122  	return c.tlsCreds.ServerHandshake(rawConn)
   123  }