forked from intel/trustauthority-kbs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
224 lines (193 loc) · 6.64 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
/*
* Copyright (c) 2024 Intel Corporation
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
package kbs
import (
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
jwtStrategy "github.com/shaj13/go-guardian/v2/auth/strategies/jwt"
"intel/kbs/v1/clients/ita"
"intel/kbs/v1/config"
"intel/kbs/v1/tasks"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"intel/kbs/v1/constant"
"intel/kbs/v1/keymanager"
"intel/kbs/v1/repository"
"intel/kbs/v1/service"
httpTransport "intel/kbs/v1/transport/http"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
func (app *App) startServer() error {
configuration := app.Config
if configuration == nil {
return errors.New("Failed to load configuration")
}
if err := configuration.Validate(); err != nil {
return errors.Wrap(err, "Invalid configuration")
}
// Initialize log
if err := app.configureLogs(); err != nil {
return err
}
log.WithFields(log.Fields{
"ServicePort": configuration.ServicePort,
"LogLevel": configuration.LogLevel,
"LogCaller": configuration.LogCaller,
"TrustAuthorityBaseUrl": configuration.TrustAuthorityBaseUrl,
"TrustAuthorityApiUrl": configuration.TrustAuthorityApiUrl,
"KeyManager": configuration.KeyManager,
"BearerTokenValidityInMinutes": configuration.BearerTokenValidityInMinutes,
"HttpReadHeaderTimeout": configuration.HttpReadHeaderTimeout,
"AuthenticationDefendLockoutMinutes": configuration.AuthenticationDefendLockoutMinutes,
"AuthenticationDefendIntervalMinutes": configuration.AuthenticationDefendIntervalMinutes,
"AuthenticationDefendMaxAttempts": configuration.AuthenticationDefendMaxAttempts,
}).Info("Parse configs from environment")
// Initialize KeyManager
keyManager, err := keymanager.NewKeyManager(configuration)
if err != nil {
return err
}
// Create repository layer and remote manager
repository := repository.NewDirectoryRepository(constant.HomeDir)
remoteManager := keymanager.NewRemoteManager(repository.KeyStore, keyManager)
itaApiServername, err := url.Parse(config.TrustAuthorityApiUrl)
if err != nil {
return errors.Wrap(err, "Error parsing Trust Authority API url")
}
// initialize ITA client
itaApiClient, err := ita.NewITAClient(configuration, itaApiServername.Hostname())
if err != nil {
return errors.Wrap(err, "Failed to initialize TrustAuthority Client")
}
// initialize ITA client for token verification
itaTokenVerifierServername, err := url.Parse(config.TrustAuthorityBaseUrl)
if err != nil {
return errors.Wrap(err, "Error parsing Trust Authority Base url")
}
itaTokenVerifierClient, err := ita.NewITAClient(configuration, itaTokenVerifierServername.Hostname())
if err != nil {
return errors.Wrap(err, "Failed to initialize TrustAuthority Client for attestation token verification")
}
// Initialize the Service
svc, err := service.NewService(itaApiClient, itaTokenVerifierClient, repository, remoteManager, configuration)
if err != nil {
msg := "Failed to initialize Service"
log.WithError(err).Error(msg)
return errors.New(msg)
}
if _, err := os.Stat(constant.DefaultJWTSigningKeyPath); errors.Is(err, os.ErrNotExist) {
// create JWT signing key
csk := tasks.CreateSigningKey{
JWTSigningKeyPath: constant.DefaultJWTSigningKeyPath,
}
err := csk.CreateJWTSigningKey()
if err != nil {
log.WithError(err).Error("Error while creating JWT signing key")
return err
}
}
bytes, err := os.ReadFile(filepath.Clean(constant.DefaultJWTSigningKeyPath))
if err != nil {
log.WithError(err).Error("Error while reading JWT signing key")
return err
}
block, _ := pem.Decode(bytes)
if block == nil {
return errors.New("Error while pem decoding JWT signing key")
}
privKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return err
}
signingKey := privKey.(*rsa.PrivateKey)
jwtKeeper := jwtStrategy.StaticSecret{
ID: "secret-id",
Secret: signingKey,
Algorithm: jwtStrategy.PS384,
}
jwtAuthZ, err := service.SetupAuthZ(&jwtKeeper)
if err != nil {
return err
}
// initialize defender
service.InitDefender(configuration.AuthenticationDefendMaxAttempts, configuration.AuthenticationDefendIntervalMinutes, configuration.AuthenticationDefendLockoutMinutes)
// Associate the service to rest endpoints/http
httpHandlers, err := httpTransport.NewHTTPHandler(svc, configuration, jwtAuthZ)
if err != nil {
return errors.Wrap(err, "Failed to initialize HTTP handler")
}
// Setup signal handlers to gracefully handle termination
stop := make(chan os.Signal)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", configuration.ServicePort),
Handler: httpHandlers,
ReadHeaderTimeout: time.Duration(configuration.HttpReadHeaderTimeout) * time.Second,
}
// TLS support is enabled
if _, err := os.Stat(constant.DefaultTLSCertPath); os.IsNotExist(err) {
// TLS certificate and key does not exist, so creating the cert and key
tlsKc := tasks.TLSKeyAndCert{
TLSCertPath: constant.DefaultTLSCertPath,
TLSKeyPath: constant.DefaultTLSKeyPath,
TlsSanList: configuration.SanList,
}
err = tlsKc.GenerateTLSKeyandCert()
if err != nil {
return errors.Wrap(err, "Failed to generate TLS certificate and key")
}
}
log.Debugf("Starting HTTPS server with TLS cert: %s", constant.DefaultTLSCertPath)
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS13,
CipherSuites: []uint16{tls.TLS_AES_256_GCM_SHA384,
tls.TLS_AES_128_GCM_SHA256,
// TLS_AES_128_CCM_SHA256 is not supported by go crypto/tls package
tls.TLS_CHACHA20_POLY1305_SHA256},
}
httpServer.TLSConfig = tlsConfig
// Dispatch web server go routine
log.Info("Starting server")
go func() {
serveErr := httpServer.ListenAndServeTLS(constant.DefaultTLSCertPath, constant.DefaultTLSKeyPath)
if serveErr != nil {
if serveErr != http.ErrServerClosed {
log.WithError(serveErr).Fatal("Failed to start HTTP server")
}
stop <- syscall.SIGTERM
}
}()
// create an admin user
ac := tasks.CreateAdminUser{
AdminUsername: app.Config.AdminUsername,
AdminPassword: app.Config.AdminPassword,
UserStore: repository.UserStore,
}
err = ac.CreateAdminUser()
if err != nil {
return err
}
log.Info("service started")
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.WithError(err).Error("Failed to gracefully shutdown webserver")
return err
}
log.Info("service stopped")
return nil
}