forked from hyperledger/fabric-ca
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
429 lines (361 loc) · 11.5 KB
/
server.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
Copyright IBM Corp. 2016 All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
rice "github.com/GeertJohan/go.rice"
"github.com/cloudflare/cfssl/api"
"github.com/cloudflare/cfssl/api/bundle"
"github.com/cloudflare/cfssl/api/certinfo"
"github.com/cloudflare/cfssl/api/crl"
"github.com/cloudflare/cfssl/api/generator"
"github.com/cloudflare/cfssl/api/info"
"github.com/cloudflare/cfssl/api/initca"
apiocsp "github.com/cloudflare/cfssl/api/ocsp"
"github.com/cloudflare/cfssl/api/scan"
"github.com/cloudflare/cfssl/api/signhandler"
"github.com/cloudflare/cfssl/bundler"
"github.com/cloudflare/cfssl/cli"
"github.com/cloudflare/cfssl/cli/ocspsign"
"github.com/cloudflare/cfssl/config"
"github.com/cloudflare/cfssl/helpers"
"github.com/cloudflare/cfssl/log"
"github.com/cloudflare/cfssl/ocsp"
"github.com/cloudflare/cfssl/signer"
"github.com/cloudflare/cfssl/signer/universal"
"github.com/cloudflare/cfssl/ubiquity"
"github.com/hyperledger/fabric-ca/cli/server/spi"
libcsp "github.com/hyperledger/fabric-ca/lib/csp"
"github.com/hyperledger/fabric-ca/util"
"github.com/hyperledger/fabric/bccsp"
"github.com/jmoiron/sqlx"
)
var (
// Usage text of 'fabric-ca server start'
serverUsageText = `fabric-ca server start -- start the fabric-ca server
Usage:
fabric-ca server start [-address address] [-ca cert] [-ca-bundle bundle] \
[-ca-key key] [-int-bundle bundle] [-int-dir dir] [-port port] \
[-metadata file] [-remote remote_host] [-config config] \
[-responder cert] [-responder-key key] [-tls-cert cert] [-tls-key key] \
[-mutual-tls-ca ca] [-mutual-tls-cn regex] \
[-tls-remote-ca ca] [-mutual-tls-client-cert cert] [-mutual-tls-client-key key] \
[-db-config db-config]
Flags:
`
// Flags used by 'cfssl serve'
serverFlags = []string{"address", "port", "ca", "ca-key", "ca-bundle", "int-bundle", "int-dir", "metadata",
"remote", "config", "responder", "responder-key", "tls-key", "tls-cert", "mutual-tls-ca", "mutual-tls-cn",
"tls-remote-ca", "mutual-tls-client-cert", "mutual-tls-client-key", "db-config"}
// V1APIPrefix is the prefix of all CFSSL V1 API Endpoints.
V1APIPrefix = "/api/v1/cfssl/"
)
var (
conf cli.Config
enrollSigner signer.Signer
ocspSigner ocsp.Signer
db *sqlx.DB
homeDir string
configDir string
configFile string
userRegistry spi.UserRegistry
certDBAccessor *CertDBAccessor
csp bccsp.BCCSP
)
var (
errBadSigner = errors.New("signer not initialized")
errNoCertDBConfigured = errors.New("cert db not configured (missing -db-config)")
)
const (
sqlite = "sqlite3"
)
// Command defines the server-related commands and calls cli.Start to process args
func Command() error {
util.SetDefaultServerPort()
// The server commands
cmds := map[string]*cli.Command{
"init": InitServerCommand,
"start": StartCommand,
}
return cli.Start(cmds)
}
// Server ...
type Server struct {
}
// CreateHome will create a home directory if it does not exist
func (s *Server) CreateHome() (string, error) {
log.Debug("CreateHome")
home := util.GetDefaultHomeDir()
if _, err := os.Stat(home); err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(home, 0755)
if err != nil {
return "", err
}
}
}
return home, nil
}
// BootstrapDB loads the database based on config file
func bootstrapDB() error {
log.Debug("Bootstrap DB")
b := BootstrapDB()
b.PopulateGroupsTable()
b.PopulateUsersTable()
log.Debug("Completed BootstrapDB")
return nil
}
// startMain is the command line entry point to the fabric-ca server.
// It sets up a new HTTP server to handle fabric-ca requests.
func startMain(args []string, c cli.Config) error {
log.Debug("server.startMain")
var err error
s := new(Server)
home, err := s.CreateHome()
if err != nil {
return err
}
homeDir = home
configInit(&c)
// Initialize the Crypto Service Provider
csp, err = libcsp.Get(CFG.CSP)
if err != nil {
log.Errorf("Failed to get the crypto service provider: %s", err)
return err
}
// Initialize the user registry
err = InitUserRegistry(CFG)
if err != nil {
log.Errorf("Failed to initialize user registry: %s", err)
return err
}
return serverMain(args, c)
}
// serverMain is the command line entry point to the API server. It sets up a
// new HTTP server to handle all endpoints
func serverMain(args []string, c cli.Config) error {
conf = c
// serve doesn't support arguments.
if len(args) > 0 {
return errors.New("argument is provided but not defined; please refer to the usage by flag -h")
}
bundler.IntermediateStash = conf.IntDir
var err error
if err = ubiquity.LoadPlatforms(conf.Metadata); err != nil {
return err
}
log.Info("Initializing signer")
if enrollSigner, err = SignerFromConfigAndDB(c, db); err != nil {
log.Warningf("couldn't initialize signer: %v", err)
}
if ocspSigner, err = ocspsign.SignerFromConfig(c); err != nil {
log.Warningf("couldn't initialize ocsp signer: %v", err)
}
registerHandlers()
addr := net.JoinHostPort(conf.Address, strconv.Itoa(conf.Port))
if !CFG.TLSDisable {
log.Debug("TLS Enabled")
if conf.MutualTLSCAFile != "" {
clientPool, err := helpers.LoadPEMCertPool(conf.MutualTLSCAFile)
if err != nil {
return fmt.Errorf("failed to load mutual TLS CA file: %s", err)
}
server := http.Server{
Addr: addr,
TLSConfig: &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientPool,
},
}
log.Info("Now listening with mutual TLS on https://", addr)
return server.ListenAndServeTLS(conf.TLSCertFile, conf.TLSKeyFile)
}
log.Info("Now listening on https://", addr)
return http.ListenAndServeTLS(addr, conf.TLSCertFile, conf.TLSKeyFile, nil)
}
log.Info("Now listening on ", addr)
return http.ListenAndServe(addr, nil)
}
// registerHandlers instantiates various handlers and associate them to corresponding endpoints.
func registerHandlers() {
for path, getHandler := range endpoints {
log.Debugf("getHandler for %s", path)
if handler, err := getHandler(); err != nil {
log.Warningf("endpoint '%s' is disabled: %v", path, err)
} else {
if path, handler, err = NewAuthWrapper(path, handler, err); err != nil {
log.Warningf("endpoint '%s' has been disabled: %v", path, err)
} else {
log.Infof("endpoint '%s' is enabled", path)
http.Handle(path, handler)
}
}
}
log.Info("Handler set up complete.")
}
// httpBox implements http.FileSystem which allows the use of Box with a http.FileServer.
// Atempting to Open an API endpoint will result in an error.
type httpBox struct {
*rice.Box
redirects map[string]string
}
func (hb *httpBox) findStaticBox() (err error) {
hb.Box, err = rice.FindBox("static")
return
}
// Open returns a File for non-API enpoints using the http.File interface.
func (hb *httpBox) Open(name string) (http.File, error) {
if strings.HasPrefix(name, V1APIPrefix) {
return nil, os.ErrNotExist
}
if location, ok := hb.redirects[name]; ok {
return hb.Box.Open(location)
}
return hb.Box.Open(name)
}
// staticBox is the box containing all static assets.
var staticBox = &httpBox{
redirects: map[string]string{
"/scan": "/index.html",
"/bundle": "/index.html",
},
}
var endpoints = map[string]func() (http.Handler, error){
// The following are the fabric-ca specific endpoints
"register": NewRegisterHandler,
"enroll": NewEnrollHandler,
"reenroll": NewReenrollHandler,
"revoke": NewRevokeHandler,
"tcert": NewTCertHandler,
// The remainder are the CFSSL endpoints
"sign": func() (http.Handler, error) {
if enrollSigner == nil {
return nil, errBadSigner
}
return signhandler.NewHandlerFromSigner(enrollSigner)
},
"authsign": func() (http.Handler, error) {
if enrollSigner == nil {
return nil, errBadSigner
}
return signhandler.NewAuthHandlerFromSigner(enrollSigner)
},
"info": func() (http.Handler, error) {
if enrollSigner == nil {
return nil, errBadSigner
}
return info.NewHandler(enrollSigner)
},
"gencrl": func() (http.Handler, error) {
if enrollSigner == nil {
return nil, errBadSigner
}
return crl.NewHandler(), nil
},
"newcert": func() (http.Handler, error) {
if enrollSigner == nil {
return nil, errBadSigner
}
h := generator.NewCertGeneratorHandlerFromSigner(generator.CSRValidate, enrollSigner)
if conf.CABundleFile != "" && conf.IntBundleFile != "" {
cg := h.(api.HTTPHandler).Handler.(*generator.CertGeneratorHandler)
if err := cg.SetBundler(conf.CABundleFile, conf.IntBundleFile); err != nil {
return nil, err
}
}
return h, nil
},
"bundle": func() (http.Handler, error) {
return bundle.NewHandler(conf.CABundleFile, conf.IntBundleFile)
},
"newkey": func() (http.Handler, error) {
return generator.NewHandler(generator.CSRValidate)
},
"init_ca": func() (http.Handler, error) {
return initca.NewHandler(), nil
},
"scan": func() (http.Handler, error) {
return scan.NewHandler(conf.CABundleFile)
},
"scaninfo": func() (http.Handler, error) {
return scan.NewInfoHandler(), nil
},
"certinfo": func() (http.Handler, error) {
return certinfo.NewHandler(), nil
},
"ocspsign": func() (http.Handler, error) {
if ocspSigner == nil {
return nil, errBadSigner
}
return apiocsp.NewHandler(ocspSigner), nil
},
"/": func() (http.Handler, error) {
if err := staticBox.findStaticBox(); err != nil {
return nil, err
}
return http.FileServer(staticBox), nil
},
}
// SignerFromConfigAndDB takes the Config and creates the appropriate
// signer.Signer object with a specified db
func SignerFromConfigAndDB(c cli.Config, db *sqlx.DB) (signer.Signer, error) {
// If there is a config, use its signing policy. Otherwise create a default policy.
var policy *config.Signing
if c.CFG != nil {
policy = c.CFG.Signing
} else {
policy = &config.Signing{
Profiles: map[string]*config.SigningProfile{},
Default: config.DefaultConfig(),
}
}
// Make sure the policy reflects the new remote
if c.Remote != "" {
err := policy.OverrideRemotes(c.Remote)
if err != nil {
log.Infof("Invalid remote %v, reverting to configuration default", c.Remote)
return nil, err
}
}
enrollSigner, err := universal.NewSigner(cli.RootFromConfig(&c), policy)
if err != nil {
return nil, err
}
if db != nil {
certAccessor := InitCertificateAccessor(db)
enrollSigner.SetDBAccessor(certAccessor)
}
return enrollSigner, nil
}
// Start will start server
// THIS IS ONLY USED FOR TEST CASE EXECUTION
func Start(dir string, cfg string) {
log.Debug("Server starting")
osArgs := os.Args
cert := filepath.Join(dir, "ec.pem")
key := filepath.Join(dir, "ec-key.pem")
config := filepath.Join(dir, cfg)
os.Args = []string{"server", "start", "-ca", cert, "-ca-key", key, "-config", config}
Command()
os.Args = osArgs
}
// StartCommand assembles the definition of Command 'fabric-ca server start'
var StartCommand = &cli.Command{UsageText: serverUsageText, Flags: serverFlags, Main: startMain}