This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine.go
276 lines (252 loc) · 9.32 KB
/
engine.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
/*
* Nuts crypto
* Copyright (C) 2019. Nuts community
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package engine
import (
"crypto"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/nuts-foundation/nuts-crypto/api"
"github.com/nuts-foundation/nuts-crypto/client"
"github.com/nuts-foundation/nuts-crypto/log"
"github.com/nuts-foundation/nuts-crypto/pkg"
"github.com/nuts-foundation/nuts-crypto/pkg/cert"
"github.com/nuts-foundation/nuts-crypto/pkg/types"
engine "github.com/nuts-foundation/nuts-go-core"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// NewCryptoEngine the engine configuration for nuts-go.
func NewCryptoEngine() *engine.Engine {
cb := pkg.CryptoInstance()
return &engine.Engine{
Cmd: cmd(),
Config: &cb.Config,
ConfigKey: "crypto",
Configure: cb.Configure,
FlagSet: flagSet(),
Name: "Crypto",
Routes: func(router engine.EchoRouter) {
api.RegisterHandlers(router, &api.Wrapper{C: cb})
},
Start: cb.Start,
Shutdown: cb.Shutdown,
}
}
// FlagSet returns the configuration flags for crypto
func flagSet() *pflag.FlagSet {
flags := pflag.NewFlagSet("crypto", pflag.ContinueOnError)
defs := pkg.DefaultCryptoConfig()
flags.String(types.ConfigMode, defs.Mode, fmt.Sprintf("Server or client, when client it uses the HttpClient, default: %s", defs.Mode))
flags.String(types.ConfigAddress, defs.Address, fmt.Sprintf("Interface and port for http server to bind to, default: %s", defs.Address))
flags.Int(types.ConfigClientTimeout, defs.ClientTimeout, fmt.Sprintf("Time-out for the client in seconds (e.g. when using the CLI), default: %d", defs.ClientTimeout))
flags.String(types.ConfigStorage, defs.Storage, fmt.Sprintf("Storage to use, 'fs' for file system, default: %s", defs.Storage))
flags.String(types.ConfigFSPath, defs.Fspath, fmt.Sprintf("When file system is used as storage, this configures the path where key material and the truststore are persisted, default: %v", defs.Fspath))
flags.Int(types.ConfigKeySize, defs.Keysize, fmt.Sprintf("Number of bits to use when creating new RSA keys, default: %d", defs.Keysize))
return flags
}
// Cmd gives the sub-commands made available through crypto:
// * generateKeyPair: generate a new keyPair for a given legalEntity
// * publicKey: retrieve the keyPair for a given legalEntity
func cmd() *cobra.Command {
cmd := &cobra.Command{
Use: "crypto",
Short: "crypto commands",
}
cmd.AddCommand(&cobra.Command{
Use: "server",
Short: "Run standalone crypto server",
Run: func(cmd *cobra.Command, args []string) {
cryptoEngine := pkg.CryptoInstance()
echoServer := echo.New()
echoServer.HideBanner = true
echoServer.Use(middleware.Logger())
api.RegisterHandlers(echoServer, &api.Wrapper{C: cryptoEngine})
logrus.Fatal(echoServer.Start(":1324"))
},
})
{
var overwrite *bool
generateKeyPairCmd := cobra.Command{
Use: "generateKeyPair [legalEntityURI]",
Short: "generate a new keyPair for a legalEntity",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires a URI argument")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
cc := client.NewCryptoClient()
if _, err := cc.GenerateKeyPair(types.KeyForEntity(types.LegalEntity{URI: args[0]}), *overwrite); err != nil {
cmd.Printf("Error generating keyPair: %v\n", err)
} else {
cmd.Println("KeyPair generated")
}
},
}
flagSet := pflag.NewFlagSet(generateKeyPairCmd.Name(), pflag.ContinueOnError)
overwrite = flagSet.BoolP("force", "f", false, "overwrite if the given key already exists")
generateKeyPairCmd.Flags().AddFlagSet(flagSet)
cmd.AddCommand(&generateKeyPairCmd)
}
cmd.AddCommand(&cobra.Command{
Use: "publicKey [legalEntityURI]",
Short: "views the publicKey for a given legal entity",
Long: "views the publicKey for a given legal entity. It'll output a JWK encoded public key and a (deprecated, <= 0.11.0) PEM encoded public key.",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires a URI argument")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
cc := client.NewCryptoClient()
le := types.LegalEntity{URI: args[0]}
// printout in JWK
jwk, err := cc.GetPublicKeyAsJWK(types.KeyForEntity(le))
if err != nil {
cmd.Printf("Error printing publicKey: %v", err)
return
}
asJSON, err := json.MarshalIndent(jwk, "", " ")
if err != nil {
cmd.Printf("Error printing publicKey: %v\n", err)
return
}
cmd.Println("Public key in JWK:")
cmd.Println(string(asJSON))
cmd.Println("")
// printout in PEM
var publicKey interface{}
if err := jwk.Raw(&publicKey); err != nil {
cmd.Printf("Error printing publicKey: %v\n", err)
return
}
publicKeyAsPEM, err := cert.PublicKeyToPem(publicKey.(crypto.PublicKey))
if err != nil {
cmd.Printf("Error printing publicKey: %v\n", err)
return
}
cmd.Println("Public key in PEM:")
cmd.Println(publicKeyAsPEM)
},
})
cmd.AddCommand(&cobra.Command{
Use: "generate-vendor-csr [name] [OPTIONAL output-file]",
Short: "Generates a CSR for the current vendor with the given name.",
Long: "Generates a CSR for the current vendor with the given name. If output-file is specified, the resulting PKCS#10 is written to that location in PEM format.",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
log.Logger().Infof("Generating Vendor CA CSR for '%s'", args[0])
cc := client.NewCryptoClient()
csr, err := cc.GenerateVendorCACSR(args[0])
if err != nil {
log.Logger().Errorf("Error while generating CSR: %v", err)
return err
}
csrAsPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
})
if len(args) == 1 {
cmd.Println(string(csrAsPEM))
} else {
outputFile := args[1]
cmd.Println(fmt.Sprintf("Writing CSR to %s", outputFile))
return ioutil.WriteFile(outputFile, csrAsPEM, 0777)
}
return nil
},
})
cmd.AddCommand(&cobra.Command{
Use: "selfsign-vendor-cert [name] [OPTIONAL output-file]",
Short: "Self-signs a X.509 certificate for the current vendor with the given name.",
Long: "Self-signs a X.509 certificate for the current vendor with the given name. " +
"This is the self-signed variant of the 'generate-vendor-csr' command. " +
"If there is an existing key pair for the vendor that one is reused, otherwise a new key pair is generated. " +
"The certificate is printed in PEM encoded form.",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
log.Logger().Infof("Self-signing Vendor CA certificate for '%s'", args[0])
cc := client.NewCryptoClient()
certificate, err := cc.SelfSignVendorCACertificate(args[0])
if err != nil {
log.Logger().Errorf("Error while self-signing : %v", err)
return err
}
certificateAsPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certificate.Raw,
})
if len(args) == 1 {
cmd.Println(string(certificateAsPEM))
} else {
outputFile := args[1]
cmd.Println(fmt.Sprintf("Writing certificate to %s", outputFile))
return ioutil.WriteFile(outputFile, certificateAsPEM, 0777)
}
return nil
},
})
cmd.AddCommand(&cobra.Command{
Use: "sign-tls-cert [public-key-file] [OPTIONAL output-file]",
Short: "Creates and signs a certificate for usage as TLS client certificate",
Long: "Creates a CSR for the given public-key using a TLS client certificate template. " +
"It's signed with the vendor CA. " +
"The certificate is printed to stdout in PEM encoded form or stored in the given location",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
log.Logger().Info("Creating and signging TLS Client certificate")
cc := client.NewCryptoClient()
pp, err := ioutil.ReadFile(args[0])
if err != nil {
log.Logger().Errorf("Error while reading %s : %v", args[0], err)
return err
}
pk, err := cert.PemToPublicKey(pp)
if err != nil {
log.Logger().Errorf("Error while parsing %s : %v", args[0], err)
return err
}
certificate, err := cc.SignTLSCertificate(pk)
if err != nil {
log.Logger().Errorf("Error while signing : %v", err)
return err
}
certificateAsPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certificate.Raw,
})
if len(args) == 1 {
cmd.Println(string(certificateAsPEM))
} else {
outputFile := args[1]
cmd.Println(fmt.Sprintf("Writing certificate to %s", outputFile))
return ioutil.WriteFile(outputFile, certificateAsPEM, 0777)
}
return nil
},
})
return cmd
}