github.com/jandre/docker@v1.7.0/pkg/sockets/tcp_socket.go (about)

     1  package sockets
     2  
     3  import (
     4  	"crypto/tls"
     5  	"crypto/x509"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net"
     9  	"os"
    10  
    11  	"github.com/docker/docker/pkg/listenbuffer"
    12  )
    13  
    14  type TlsConfig struct {
    15  	CA          string
    16  	Certificate string
    17  	Key         string
    18  	Verify      bool
    19  }
    20  
    21  func NewTlsConfig(tlsCert, tlsKey, tlsCA string, verify bool) *TlsConfig {
    22  	return &TlsConfig{
    23  		Verify:      verify,
    24  		Certificate: tlsCert,
    25  		Key:         tlsKey,
    26  		CA:          tlsCA,
    27  	}
    28  }
    29  
    30  func NewTcpSocket(addr string, config *TlsConfig, activate <-chan struct{}) (net.Listener, error) {
    31  	l, err := listenbuffer.NewListenBuffer("tcp", addr, activate)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	if config != nil {
    36  		if l, err = setupTls(l, config); err != nil {
    37  			return nil, err
    38  		}
    39  	}
    40  	return l, nil
    41  }
    42  
    43  func setupTls(l net.Listener, config *TlsConfig) (net.Listener, error) {
    44  	tlsCert, err := tls.LoadX509KeyPair(config.Certificate, config.Key)
    45  	if err != nil {
    46  		if os.IsNotExist(err) {
    47  			return nil, fmt.Errorf("Could not load X509 key pair (%s, %s): %v", config.Certificate, config.Key, err)
    48  		}
    49  		return nil, fmt.Errorf("Error reading X509 key pair (%s, %s): %q. Make sure the key is encrypted.",
    50  			config.Certificate, config.Key, err)
    51  	}
    52  	tlsConfig := &tls.Config{
    53  		NextProtos:   []string{"http/1.1"},
    54  		Certificates: []tls.Certificate{tlsCert},
    55  		// Avoid fallback on insecure SSL protocols
    56  		MinVersion: tls.VersionTLS10,
    57  	}
    58  	if config.CA != "" {
    59  		certPool := x509.NewCertPool()
    60  		file, err := ioutil.ReadFile(config.CA)
    61  		if err != nil {
    62  			return nil, fmt.Errorf("Could not read CA certificate: %v", err)
    63  		}
    64  		certPool.AppendCertsFromPEM(file)
    65  		tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
    66  		tlsConfig.ClientCAs = certPool
    67  	}
    68  	return tls.NewListener(l, tlsConfig), nil
    69  }