Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TLS support to HTTP Server #185

Merged
merged 10 commits into from
Apr 22, 2020
20 changes: 20 additions & 0 deletions server/certs/client.crt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDLjCCApcCCQCt9iAWqkDJxzANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMRAwDgYDVQQKEwdyZXF1
ZXN0MSYwJAYDVQQLEx1yZXF1ZXN0IENlcnRpZmljYXRlIEF1dGhvcml0eTESMBAG
A1UEAxMJcmVxdWVzdENBMSYwJAYJKoZIhvcNAQkBFhdtaWtlYWxAbWlrZWFscm9n
ZXJzLmNvbTAeFw0xODExMjIxNTIzMjNaFw0yMTExMjExNTIzMjNaMIGPMQswCQYD
VQQGEwJVUzELMAkGA1UECAwCQ0ExEDAOBgNVBAcMB09ha2xhbmQxEDAOBgNVBAoM
B3JlcXVlc3QxGjAYBgNVBAsMEXJlcXVlc3RAbG9jYWxob3N0MRMwEQYDVQQDDApU
ZXN0Q2xpZW50MR4wHAYJKoZIhvcNAQkBFg9kby5ub3RAZW1haWwubWUwggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDFNIUKI5I/cOYMv7dYJzPMNEpd9d80
lXueDWOtFflpKpnt3ssCk+pFIxlbnlBnFl1CIkpjAY9pqB4WoGpDARkkW0RqVleZ
mlxBRMwfkzzTriURb0PtB7P7iRp+lcr+uraJg4sP9xEpZbq/CO1q584EQmiANVL3
NAPdXf2kP91lUy+F5gZgZqkuPtDRXk1jqxTswRLqBmP5ublM/b9ZQS2Jmih7rVL4
FiTo6E2DdjSYiZ1cQKSBw3rFWhiFLe3R2BjqK+/uD/hDdcT9sEtdqxLyLqFFBKLa
cYcHcnZOMaohmN8vup26D199r5VP6cJvAh93XfxpCiNDl/S4KSCDq5G5AgMBAAEw
DQYJKoZIhvcNAQEFBQADgYEAjINjRQxACmbp77ymVwaiUiy9YXbXLSsu8auZYDlu
LqiZMIjm6hOOHZPlCC7QXBBRyUKXQnRC4+mOxWfcMwEztYqrX51fP/hVB0aF7hXg
hcn0Ge65N9P8Kby6k/2ha/NQW7I17Sgg1PrvN5BkDFnZBrhNwZbzWwxwezifUwob
ITQ=
-----END CERTIFICATE-----
27 changes: 27 additions & 0 deletions server/certs/client.key
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxTSFCiOSP3DmDL+3WCczzDRKXfXfNJV7ng1jrRX5aSqZ7d7L
ApPqRSMZW55QZxZdQiJKYwGPaageFqBqQwEZJFtEalZXmZpcQUTMH5M8064lEW9D
7Qez+4kafpXK/rq2iYOLD/cRKWW6vwjtaufOBEJogDVS9zQD3V39pD/dZVMvheYG
YGapLj7Q0V5NY6sU7MES6gZj+bm5TP2/WUEtiZooe61S+BYk6OhNg3Y0mImdXECk
gcN6xVoYhS3t0dgY6ivv7g/4Q3XE/bBLXasS8i6hRQSi2nGHB3J2TjGqIZjfL7qd
ug9ffa+VT+nCbwIfd138aQojQ5f0uCkgg6uRuQIDAQABAoIBAF062haUAIT7k9a9
ICmNxwAoTGwlXBOZA+sRu2jNta7RVBpPtLwQP7XVxRw6ORqzSP2GBpLN3wX9U9Qw
nGv27fLxLuPy09ErV6gHpVTcH+qXLrESYBOEC8PD6oGjwWcx0DAsvyaaEEP48xNz
XgKneg8rcgoCq6lwrs8Nq2bmRn2qw6pnecQRt/xuJMMn83UforHyiH5Xy+WFart9
5Oz4VJmngOzd/dRXuziCmfDpJnCYP7YPbG+ATbsWR9BhGoO4x0cxZP73lQKMc9l/
tPo+42rtJCjhHoqZaBVzQmY9kWrb5ItF6Nma11M5Uf0YsEM7XbsWw1gfOeJvVIPw
Q3w3NQECgYEA9wm4QQjtrCvBjkMwY4tkegD3F3SgVDwxqGco3ZJlLK4JX4oHH8oC
P5vMXjy+3SigFNeTVo3MKNkADimkQ1E3R2ar07S31fBHAW7ymeZbK3ixJgB55JEk
pBWT6vgBtZQfW0DfdVIAQz8rZlcqNrGBp2ZlgKKswy2HIVTwXU9UXiECgYEAzFv+
rDPOp4pK0LPeDwSDUflasq7Dc52xcWfYupajAvK/4pzeDr07Frv8gh+EhhCp4kwN
YtmHJ0KfE0R4Ijh8LH5MNhl2YBhTCqp3NZf3jhdiPTDRHMNfUq5aUbercU5Yi1W/
FrqBeTbid1k7tHV/EqwWqcYQBVdFuSjuUkA1UJkCgYEA4UT5wkRUBzZ3cDUQwRVx
cFfE+pydP3MMjVZUy4gdvpqNbZO+X1ykpEB8IkseeSn8oETc1IbFb1JCXKfYZJKA
6BlWAt2+7dYHyeTUUUbgSEnssIyqmqVIVmBe3Ft/o4cI+Pu1SZSXLLtD5jUCB5Hi
ezZCxQSSqgCwQtLjxRL8CkECgYEAwI6OUUQfnM454J0ax5vBASSryWHS2MXlxK3N
EUOPJeAF3klhExJK8wj+zL1V6d0ZthljI5lEOEIWEdmaOORwXJxEw1UKrVE+Lfah
jOY8ZK6z6mRtJWUSFJ4kjIs8B++Cjwekno3uIYENstdp4ogzzCxKzn3J6r5o/CcN
KINHuUECgYB82O06BuRuSWYYM3qHxgo4bKqIQYHZKI528p90bMSyTH7M2sXcGR+z
ADcs1Ald0acyJkI4IpzBs+YK+WVihQKuSh69YGKKru0xq0hONN8j2pgphVDS0hbk
bMzyxx1QHK9cRVAXFdiqeQ36U3f70enItxXvOYGwWGvD5v7bCpYuCA==
-----END RSA PRIVATE KEY-----
17 changes: 17 additions & 0 deletions server/certs/root.crt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-----BEGIN CERTIFICATE-----
MIICvTCCAiYCCQDn+P/MSbDsWjANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQHEwdPYWtsYW5kMRAwDgYDVQQKEwdyZXF1
ZXN0MSYwJAYDVQQLEx1yZXF1ZXN0IENlcnRpZmljYXRlIEF1dGhvcml0eTESMBAG
A1UEAxMJcmVxdWVzdENBMSYwJAYJKoZIhvcNAQkBFhdtaWtlYWxAbWlrZWFscm9n
ZXJzLmNvbTAeFw0xMjAzMDEyMjUwNTZaFw0yMjAyMjcyMjUwNTZaMIGiMQswCQYD
VQQGEwJVUzELMAkGA1UECBMCQ0ExEDAOBgNVBAcTB09ha2xhbmQxEDAOBgNVBAoT
B3JlcXVlc3QxJjAkBgNVBAsTHXJlcXVlc3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5
MRIwEAYDVQQDEwlyZXF1ZXN0Q0ExJjAkBgkqhkiG9w0BCQEWF21pa2VhbEBtaWtl
YWxyb2dlcnMuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7t9pQUAK4
5XJYTI6NrF0n3G2HZsfN+rPYSVzzL8SuVyb1tHXos+vbPm3NKI4E8X1yVAXU8CjJ
5SqXnp4DAypAhaseho81cbhk7LXUhFz78OvAa+OD+xTAEAnNQ8tGUr4VGyplEjfD
xsBVuqV2j8GPNTftr+drOCFlqfAgMrBn4wIDAQABMA0GCSqGSIb3DQEBBQUAA4GB
ADVdTlVAL45R+PACNS7Gs4o81CwSclukBu4FJbxrkd4xGQmurgfRrYYKjtqiopQm
D7ysRamS3HMN9/VKq2T7r3z1PMHPAy7zM4uoXbbaTKwlnX4j/8pGPn8Ca3qHXYlo
88L/OOPc6Di7i7qckS3HFbXQCTiULtxWmy97oEuTwrAj
-----END CERTIFICATE-----
25 changes: 25 additions & 0 deletions server/certs/server.crt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-----BEGIN CERTIFICATE-----
MIIEQjCCA6sCCQCt9iAWqkDJxzANBgkqhkiG9w0BAQsFADCBojELMAkGA1U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h+V9/qPCVYVPKSRGKXP8BI6ujvarOiKx96Pjly
A7BBDGblF2FJEnKGNGV2XCUJnjV2fNuFRrV3UYkMhbq0SXpSA8FcK/0YhKxKxIsV
/pUrR//nTlsoYHwQR4AFp0Rhpy6XntO9vsrDetE3AgMBAAEwDQYJKoZIhvcNAQEL
BQADgYEAnjXSTIfGpBx9/0ZkOQRSGdTjtpy5TQ/VDHtEhRKZYY6dpe6lVpT0hSoT
SzA8YF+bpFIF+1ZpAgQldBFCmPpVDBCy/ymf8t/V2zSd2c80w6pmxXWQEFq25pib
OLCcTex2nVGmiUXwIbwnEhWPJvB8T8L8a75x0fPZDHHHoi+K/wQ=
-----END CERTIFICATE-----
51 changes: 51 additions & 0 deletions server/certs/server.key
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
-----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEA1BzpWbtTArUlBzyCKlr77SqwBSraK/08Z6jxwT57BbOMoKiH
iE5igNL3mirfTdCr7S+/N5j2x97V5kk53CoJY88KV/YOR32sQG1DDpmbl2h1OypR
C0gsuKigNSLzc689wKdtzbnLmo8L4RtE1g8X2l6emvL8yFa6o487o3NNuwiNbUpG
86yK80h61Sv/jxLUKaZIgu9VACpvMoZ1rjJwyQXxdmoi8OdQ4E8MCjmKgRj3Z411
9wp4lW70a/s8XJsRYPn6NnD+fD17TWrnm34HMXQqr3LKV14C6V27bmeHNlPJmL66
Ymwjaam/xHnSu8K1htfiSxDLXtSXG8S30KUBgXVyzTh/p4CK/Mo0Di95VIHd49Er
AYLAIjA8DfcLNkU7enDWIxn3fqdV5v2g0UrhgLu1iJ3+Po8jb7Tfa0bFLXwwYHwV
JIbJMKOwyocIlw6L18vCfXKItxe3gEqpV9bKL6+xczdeHZx1IpBWAgyhEeevjvyU
r2BPxDC3E0hsXcX05HqrKtnVUeVMOnWtIQSPq5X+DLHieH5X3+o8JVhU8pJEYpc/
wEjq6O9qs6IrH3o+OXIDsEEMZuUXYUkScoY0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
OKbMK94R5yp6P4aVYVari83UA3rh0O7pAoIBAAUJ+l+Z7ZV/mG0AuQ8CxDyapHjE
LCFLUcZuelgpzYBLabejwVKWa49e87mE+OLVJxpb23az16ILAz/717BPSeBssBSN
o33M2oEP79INlUGpc2rBxQi6uQA9DYASoLn1T8Fs/dhvIN/qxL3+sK3gCA9AKIyF
IAgYpcQrlMAl07jjzSl47R/0BDOe/jzmH7JqpFQOfw9e7U0XThgaVEVHSF9qJVRS
LlFUhijpG14Qyr8gwfR3RrnO7TKfdXW3GX/5ts0Oac9B+gOMkrksNalgLHnOZSzO
JuiTAH7CdUt1OC0NaaCBZiI3A5C1Gn1J9vskW4yCwhW0UNnW4h7m+eru0ok=
-----END RSA PRIVATE KEY-----
67 changes: 59 additions & 8 deletions server/server.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package server

import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"math"
"net"
"net/http"
Expand All @@ -18,6 +21,7 @@ import (
"golang.org/x/net/context"
"golang.org/x/net/netutil"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"

"github.com/weaveworks/common/httpgrpc"
Expand All @@ -34,6 +38,9 @@ type Config struct {
HTTPListenAddress string `yaml:"http_listen_address"`
HTTPListenPort int `yaml:"http_listen_port"`
HTTPConnLimit int `yaml:"http_listen_conn_limit"`
HTTPCertPath string `yaml:"http_cert_path"`
HTTPKeyPath string `yaml:"http_key_path"`
HTTPCAPath string `yaml:"http_ca_path"`
GRPCListenAddress string `yaml:"grpc_listen_address"`
GRPCListenPort int `yaml:"grpc_listen_port"`
GRPCConnLimit int `yaml:"grpc_listen_conn_limit"`
Expand Down Expand Up @@ -71,6 +78,9 @@ var infinty = time.Duration(math.MaxInt64)
// RegisterFlags adds the flags required to config this to the given FlagSet
func (cfg *Config) RegisterFlags(f *flag.FlagSet) {
f.StringVar(&cfg.HTTPListenAddress, "server.http-listen-address", "", "HTTP server listen address.")
f.StringVar(&cfg.HTTPCertPath, "server.http-cert-path", "", "HTTP server cert path.")
f.StringVar(&cfg.HTTPKeyPath, "server.http-key-path", "", "HTTP server key path.")
f.StringVar(&cfg.HTTPKeyPath, "server.http-ca-path", "", "HTTP CA path.")
annanay25 marked this conversation as resolved.
Show resolved Hide resolved
f.IntVar(&cfg.HTTPListenPort, "server.http-listen-port", 80, "HTTP server listen port.")
f.IntVar(&cfg.HTTPConnLimit, "server.http-conn-limit", 0, "Maximum number of simultaneous http connections, <=0 to disable")
f.StringVar(&cfg.GRPCListenAddress, "server.grpc-listen-address", "", "gRPC server listen address.")
Expand Down Expand Up @@ -128,6 +138,42 @@ func New(cfg Config) (*Server, error) {
grpcListener = netutil.LimitListener(grpcListener, cfg.GRPCConnLimit)
}

// If user doesn't supply a logging implementation, by default instantiate
// logrus.
log := cfg.Log
if log == nil {
log = logging.NewLogrus(cfg.LogLevel)
}

// Setup TLS
var cert tls.Certificate
if cfg.HTTPCertPath != "" && cfg.HTTPKeyPath != "" {
cert, err = tls.LoadX509KeyPair(cfg.HTTPCertPath, cfg.HTTPKeyPath)
if err != nil {
log.Warnf("error loading cert %s or key %s, tls disabled", cfg.HTTPCertPath, cfg.HTTPKeyPath)
annanay25 marked this conversation as resolved.
Show resolved Hide resolved
}
}

var caCertPool *x509.CertPool
if cfg.HTTPCAPath != "" {
caCert, err := ioutil.ReadFile(cfg.HTTPCAPath)
if err != nil {
log.Warnf("error loading ca cert %s, tls disabled", cfg.HTTPCAPath)
} else {
caCertPool = x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
}
}

var tlsConfig *tls.Config
if len(cert.Certificate) > 0 && caCertPool != nil {
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: caCertPool,
}
}
annanay25 marked this conversation as resolved.
Show resolved Hide resolved

// Prometheus histograms for requests.
requestDuration := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Expand All @@ -137,13 +183,6 @@ func New(cfg Config) (*Server, error) {
}, []string{"method", "route", "status_code", "ws"})
prometheus.MustRegister(requestDuration)

// If user doesn't supply a logging implementation, by default instantiate
// logrus.
log := cfg.Log
if log == nil {
log = logging.NewLogrus(cfg.LogLevel)
}

log.WithField("http", httpListener.Addr()).WithField("grpc", grpcListener.Addr()).Infof("server listening on addresses")

// Setup gRPC server
Expand Down Expand Up @@ -186,6 +225,10 @@ func New(cfg Config) (*Server, error) {
grpc.MaxConcurrentStreams(uint32(cfg.GPRCServerMaxConcurrentStreams)),
}
grpcOptions = append(grpcOptions, cfg.GRPCOptions...)
if tlsConfig != nil {
grpcCreds := credentials.NewTLS(tlsConfig)
grpcOptions = append(grpcOptions, grpc.Creds(grpcCreds))
}
grpcServer := grpc.NewServer(grpcOptions...)

// Setup HTTP server
Expand Down Expand Up @@ -218,6 +261,9 @@ func New(cfg Config) (*Server, error) {
IdleTimeout: cfg.HTTPServerIdleTimeout,
Handler: middleware.Merge(httpMiddleware...).Wrap(router),
}
if tlsConfig != nil {
httpServer.TLSConfig = tlsConfig
}

return &Server{
cfg: cfg,
Expand Down Expand Up @@ -252,7 +298,12 @@ func (s *Server) Run() error {
}()

go func() {
err := s.HTTPServer.Serve(s.httpListener)
var err error
if s.HTTPServer.TLSConfig == nil {
err = s.HTTPServer.Serve(s.httpListener)
} else {
err = s.HTTPServer.ServeTLS(s.httpListener, s.cfg.HTTPCertPath, s.cfg.HTTPKeyPath)
}
if err == http.ErrServerClosed {
err = nil
}
Expand Down
77 changes: 77 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
package server

import (
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"io/ioutil"
"net/http"
"strconv"
"testing"
"time"

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

google_protobuf "github.com/golang/protobuf/ptypes/empty"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
"github.com/stretchr/testify/require"
"github.com/weaveworks/common/httpgrpc"
"github.com/weaveworks/common/logging"
Expand Down Expand Up @@ -287,3 +292,75 @@ func TestMiddlewareLogging(t *testing.T) {
require.NoError(t, err)
http.DefaultClient.Do(req)
}

func TestTLSServer(t *testing.T) {
var level logging.Level
level.Set("info")
cfg := Config{
HTTPListenAddress: "localhost",
HTTPListenPort: 9193,
HTTPCertPath: "certs/server.crt",
HTTPKeyPath: "certs/server.key",
HTTPCAPath: "certs/root.crt",
MetricsNamespace: "testing_tls",
GRPCListenAddress: "localhost",
GRPCListenPort: 9194,
}
server, err := New(cfg)
require.NoError(t, err)

server.HTTP.HandleFunc("/testhttps", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!"))
})

fakeServer := FakeServer{}
RegisterFakeServerServer(server.GRPC, fakeServer)

go server.Run()
defer server.Shutdown()

clientCert, err := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key")
if err != nil {
log.Warnf("error loading cert %s or key %s, tls disabled", "certs/client.crt", "certs/client.key")
annanay25 marked this conversation as resolved.
Show resolved Hide resolved
}

var caCertPool *x509.CertPool
caCert, err := ioutil.ReadFile(cfg.HTTPCAPath)
if err != nil {
log.Warnf("error loading ca cert %s, tls disabled", cfg.HTTPCAPath)
} else {
caCertPool = x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
}

tlsConfig := &tls.Config{
InsecureSkipVerify: true,
Certificates: []tls.Certificate{clientCert},
RootCAs: caCertPool,
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
}

client := &http.Client{Transport: tr}
res, err := client.Get("https://localhost:9193/testhttps")
require.NoError(t, err)
defer res.Body.Close()

require.Equal(t, res.StatusCode, http.StatusOK)

body, err := ioutil.ReadAll(res.Body)
require.NoError(t, err)
expected := []byte("Hello World!")
require.Equal(t, expected, body)

conn, err := grpc.Dial("localhost:9194", grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
defer conn.Close()
require.NoError(t, err)

empty := google_protobuf.Empty{}
grpcClient := NewFakeServerClient(conn)
grpcRes, err := grpcClient.Succeed(context.Background(), &empty)
require.NoError(t, err)
require.EqualValues(t, &empty, grpcRes)
}