forked from moby/swarmkit
/
externalutils.go
171 lines (144 loc) · 5.5 KB
/
externalutils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package testutils
import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"path/filepath"
"strconv"
"sync/atomic"
"github.com/cloudflare/cfssl/api"
"github.com/cloudflare/cfssl/errors"
"github.com/cloudflare/cfssl/signer"
"github.com/docker/swarmkit/ca"
)
// NewExternalSigningServer creates and runs a new ExternalSigningServer which
// uses the given rootCA to sign node certificates. A server key and cert are
// generated and saved into the given basedir and then a TLS listener is
// started on a random available port. On success, an HTTPS server will be
// running in a separate goroutine. The URL of the singing endpoint is
// available in the returned *ExternalSignerServer value. Calling the Close()
// method will stop the server.
func NewExternalSigningServer(rootCA ca.RootCA, basedir string) (*ExternalSigningServer, error) {
serverCN := "external-ca-example-server"
serverOU := "localhost" // Make a valid server cert for localhost.
// Create TLS credentials for the external CA server which we will run.
serverPaths := ca.CertPaths{
Cert: filepath.Join(basedir, "server.crt"),
Key: filepath.Join(basedir, "server.key"),
}
serverCert, err := ca.GenerateAndSignNewTLSCert(rootCA, serverCN, serverOU, "", serverPaths)
if err != nil {
return nil, fmt.Errorf("unable to get TLS server certificate: %s", err)
}
serverTLSConfig := &tls.Config{
Certificates: []tls.Certificate{*serverCert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: rootCA.Pool,
}
tlsListener, err := tls.Listen("tcp", "localhost:0", serverTLSConfig)
if err != nil {
return nil, fmt.Errorf("unable to create TLS connection listener: %s", err)
}
assignedPort := tlsListener.Addr().(*net.TCPAddr).Port
signURL := url.URL{
Scheme: "https",
Host: net.JoinHostPort("localhost", strconv.Itoa(assignedPort)),
Path: "/sign",
}
ess := &ExternalSigningServer{
listener: tlsListener,
URL: signURL.String(),
}
mux := http.NewServeMux()
handler := &signHandler{
numIssued: &ess.NumIssued,
rootCA: rootCA,
}
mux.Handle(signURL.Path, handler)
server := &http.Server{
Handler: mux,
}
go server.Serve(tlsListener)
return ess, nil
}
// ExternalSigningServer runs an HTTPS server with an endpoint at a specified
// URL which signs node certificate requests from a swarm manager client.
type ExternalSigningServer struct {
listener net.Listener
NumIssued uint64
URL string
}
// Stop stops this signing server by closing the underlying TCP/TLS listener.
func (ess *ExternalSigningServer) Stop() error {
return ess.listener.Close()
}
type signHandler struct {
numIssued *uint64
rootCA ca.RootCA
}
func (h *signHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check client authentication via mutual TLS.
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
cfsslErr := errors.New(errors.APIClientError, errors.AuthenticationFailure)
errResponse := api.NewErrorResponse("must authenticate sign request with mutual TLS", cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
clientSub := r.TLS.PeerCertificates[0].Subject
// The client certificate OU should be for a swarm manager.
if len(clientSub.OrganizationalUnit) == 0 || clientSub.OrganizationalUnit[0] != ca.ManagerRole {
cfsslErr := errors.New(errors.APIClientError, errors.AuthenticationFailure)
errResponse := api.NewErrorResponse(fmt.Sprintf("client certificate OU must be %q", ca.ManagerRole), cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
// The client certificate must have an Org.
if len(clientSub.Organization) == 0 {
cfsslErr := errors.New(errors.APIClientError, errors.AuthenticationFailure)
errResponse := api.NewErrorResponse("client certificate must have an Organization", cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
clientOrg := clientSub.Organization[0]
// Decode the certificate signing request.
var signReq signer.SignRequest
if err := json.NewDecoder(r.Body).Decode(&signReq); err != nil {
cfsslErr := errors.New(errors.APIClientError, errors.JSONError)
errResponse := api.NewErrorResponse(fmt.Sprintf("unable to decode sign request: %s", err), cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
// The signReq should have additional subject info.
reqSub := signReq.Subject
if reqSub == nil {
cfsslErr := errors.New(errors.CSRError, errors.BadRequest)
errResponse := api.NewErrorResponse("sign request must contain a subject field", cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
// The client's Org should match the Org in the sign request subject.
if len(reqSub.Name().Organization) == 0 || reqSub.Name().Organization[0] != clientOrg {
cfsslErr := errors.New(errors.CSRError, errors.BadRequest)
errResponse := api.NewErrorResponse("sign request subject org does not match client certificate org", cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
// Finally, sign the requested certificate.
certPEM, err := h.rootCA.Signer.Sign(signReq)
if err != nil {
cfsslErr := errors.New(errors.APIClientError, errors.ServerRequestFailed)
errResponse := api.NewErrorResponse(fmt.Sprintf("unable to sign requested certificate: %s", err), cfsslErr.ErrorCode)
json.NewEncoder(w).Encode(errResponse)
return
}
result := map[string]string{
"certificate": string(certPEM),
}
// Increment the number of certs issued.
atomic.AddUint64(h.numIssued, 1)
// Return a successful JSON response.
json.NewEncoder(w).Encode(api.NewSuccessResponse(result))
}