/
utils.go
413 lines (361 loc) · 9.65 KB
/
utils.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
/*
* Copyright 2017-2019 Kopano and its licensors
*
* 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 main
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/crypto/ed25519"
"gopkg.in/square/go-jose.v2"
"stash.kopano.io/kc/konnect/signing"
)
func commandUtils() *cobra.Command {
jwkCmd := &cobra.Command{
Use: "utils",
Short: "Konnect related utilities",
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
os.Exit(2)
},
}
jwkCmd.AddCommand(commandJwkFromPem())
return jwkCmd
}
func parseJSONWebKey(jsonBytes []byte) (*jose.JSONWebKey, error) {
k := &jose.JSONWebKey{}
if err := k.UnmarshalJSON(jsonBytes); err != nil {
return nil, err
}
return k, nil
}
func loadSignerFromFile(fn string) (string, crypto.Signer, error) {
readBytes, errRead := ioutil.ReadFile(fn)
if errRead != nil {
return "", nil, fmt.Errorf("failed to parse key file: %v", errRead)
}
ext := filepath.Ext(fn)
switch ext {
case ".json":
k, err := parseJSONWebKey(readBytes)
if err != nil {
return "", nil, fmt.Errorf("failed to parse key file as JWK: %v", err)
}
if !k.Valid() {
return "", nil, fmt.Errorf("json file is not a valid JWK")
}
if k.IsPublic() {
return "", nil, fmt.Errorf("JWK is a public key, private key required to use as signer")
}
signer, ok := k.Key.(crypto.Signer)
if !ok {
return "", nil, fmt.Errorf("JWS key type %T is not a signer", k.Key)
}
return k.KeyID, signer, nil
case ".pem":
fallthrough
default:
// Try PEM if not otherwise detected.
signer, err := parsePEMSigner(readBytes)
return "", signer, err
}
}
func parsePEMSigner(pemBytes []byte) (crypto.Signer, error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, fmt.Errorf("no PEM block found")
}
var signer crypto.Signer
for {
pkcs1Key, errParse1 := x509.ParsePKCS1PrivateKey(block.Bytes)
if errParse1 == nil {
signer = pkcs1Key
break
}
pkcs8Key, errParse2 := x509.ParsePKCS8PrivateKey(block.Bytes)
if errParse2 == nil {
signerSigner, ok := pkcs8Key.(crypto.Signer)
if !ok {
return nil, fmt.Errorf("failed to use key as crypto signer")
}
signer = signerSigner
break
}
ecKey, errParse3 := x509.ParseECPrivateKey(block.Bytes)
if errParse3 == nil {
signer = ecKey
break
}
return nil, fmt.Errorf("failed to parse signer key - valid PKCS#1, PKCS#8 ...? %v, %v, %v", errParse1, errParse2, errParse3)
}
return signer, nil
}
func loadValidatorFromFile(fn string) (string, crypto.PublicKey, error) {
readBytes, errRead := ioutil.ReadFile(fn)
if errRead != nil {
return "", nil, fmt.Errorf("failed to parse key file: %v", errRead)
}
ext := filepath.Ext(fn)
switch ext {
case ".json":
k, err := parseJSONWebKey(readBytes)
if err != nil {
return "", nil, fmt.Errorf("failed to parse key file as JWK: %v", err)
}
if !k.Valid() {
return "", nil, fmt.Errorf("json file is not a valid JWK")
}
if !k.IsPublic() {
public := k.Public()
k = &public
}
return k.KeyID, k.Key, nil
case ".pem":
fallthrough
default:
// Try PEM if not otherwise detected.
validator, err := parsePEMValidator(readBytes)
return "", validator, err
}
}
func parsePEMValidator(pemBytes []byte) (crypto.PublicKey, error) {
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, fmt.Errorf("no PEM block found")
}
var validator crypto.PublicKey
for {
pkixPubKey, errParse0 := x509.ParsePKIXPublicKey(block.Bytes)
if errParse0 == nil {
validator = pkixPubKey
break
}
pkcs1PubKey, errParse1 := x509.ParsePKCS1PublicKey(block.Bytes)
if errParse1 == nil {
validator = pkcs1PubKey
break
}
pkcs1PrivKey, errParse2 := x509.ParsePKCS1PrivateKey(block.Bytes)
if errParse2 == nil {
validator = pkcs1PrivKey.Public()
break
}
pkcs8Key, errParse3 := x509.ParsePKCS8PrivateKey(block.Bytes)
if errParse3 == nil {
signerSigner, ok := pkcs8Key.(crypto.Signer)
if !ok {
return nil, fmt.Errorf("failed to use key as crypto signer")
}
validator = signerSigner.Public()
break
}
ecKey, errParse4 := x509.ParseECPrivateKey(block.Bytes)
if errParse4 == nil {
validator = ecKey.Public()
break
}
return nil, fmt.Errorf("failed to parse validator key - valid PKCS#1, PKCS#8 ...? %v, %v, %v, %v, %v", errParse0, errParse1, errParse2, errParse3, errParse4)
}
return validator, nil
}
func addSignerWithIDFromFile(fn string, kid string, bs *bootstrap) error {
fi, err := os.Lstat(fn)
if err != nil {
return fmt.Errorf("failed load load signer key: %v", err)
}
mode := fi.Mode()
switch {
case mode.IsDir():
return fmt.Errorf("signer key must be a file")
}
// Load file.
signerKid, signer, err := loadSignerFromFile(fn)
if err != nil {
return err
}
if kid == "" {
kid = signerKid
}
if kid == "" {
// Get ID from file, following symbolic link.
var real string
if mode&os.ModeSymlink != 0 {
real, err = os.Readlink(fn)
if err != nil {
return err
}
_, real = filepath.Split(real)
} else {
real = fi.Name()
}
kid = getKeyIDFromFilename(real)
}
if _, ok := bs.signers[kid]; ok {
bs.cfg.Logger.WithFields(logrus.Fields{
"path": fn,
"kid": kid,
}).Warnln("skipped as signer with same kid already loaded")
return nil
} else {
bs.cfg.Logger.WithFields(logrus.Fields{
"path": fn,
"kid": kid,
}).Debugln("loaded signer key")
}
bs.signers[kid] = signer
return nil
}
func validateSigners(bs *bootstrap) error {
haveRSA := false
haveECDSA := false
haveEd25519 := false
for _, signer := range bs.signers {
switch s := signer.(type) {
case *rsa.PrivateKey:
// Ensure the private key is not vulnerable with PKCS-1.5 signatures. See
// https://paragonie.com/blog/2018/04/protecting-rsa-based-protocols-against-adaptive-chosen-ciphertext-attacks#rsa-anti-bb98
// for details.
if s.PublicKey.E < 65537 {
return fmt.Errorf("RSA signing key with public exponent < 65537")
}
haveRSA = true
case *ecdsa.PrivateKey:
haveECDSA = true
case ed25519.PrivateKey:
haveEd25519 = true
default:
return fmt.Errorf("unsupported signer type: %v", s)
}
}
// Validate signing method
switch bs.signingMethod.(type) {
case *jwt.SigningMethodRSA:
if !haveRSA {
return fmt.Errorf("no private key for signing method: %s", bs.signingMethod.Alg())
}
case *jwt.SigningMethodRSAPSS:
if !haveRSA {
return fmt.Errorf("no private key for signing method: %s", bs.signingMethod.Alg())
}
case *jwt.SigningMethodECDSA:
if !haveECDSA {
return fmt.Errorf("no private key for signing method: %s", bs.signingMethod.Alg())
}
case *signing.SigningMethodEdwardsCurve:
if !haveEd25519 {
return fmt.Errorf("no private key for signing method: %s", bs.signingMethod.Alg())
}
default:
return fmt.Errorf("unsupported signing method: %s", bs.signingMethod.Alg())
}
if !haveRSA {
bs.cfg.Logger.Warnln("no RSA signing private key, some clients might not be compatible")
}
return nil
}
func addValidatorsFromPath(pn string, bs *bootstrap) error {
fi, err := os.Lstat(pn)
if err != nil {
return fmt.Errorf("failed load load validator keys: %v", err)
}
switch mode := fi.Mode(); {
case mode.IsDir():
// OK.
default:
return fmt.Errorf("validator path must be a directory")
}
// Load all files.
files := []string{}
if pemFiles, err := filepath.Glob(filepath.Join(pn, "*.pem")); err != nil {
return fmt.Errorf("validator path err: %v", err)
} else {
files = append(files, pemFiles...)
}
if jsonFiles, err := filepath.Glob(filepath.Join(pn, "*.json")); err != nil {
return fmt.Errorf("validator path err: %v", err)
} else {
files = append(files, jsonFiles...)
}
for _, file := range files {
kid, validator, err := loadValidatorFromFile(file)
if err != nil {
bs.cfg.Logger.WithError(err).WithField("path", file).Warnln("failed to load validator key")
continue
}
// Get ID from file, without following symbolic links.
if kid == "" {
_, fn := filepath.Split(file)
kid = getKeyIDFromFilename(fn)
}
if _, ok := bs.validators[kid]; ok {
bs.cfg.Logger.WithFields(logrus.Fields{
"path": file,
"kid": kid,
}).Warnln("skipped as validator with same kid already loaded")
continue
} else {
bs.cfg.Logger.WithFields(logrus.Fields{
"path": file,
"kid": kid,
}).Debugln("loaded validator key")
}
bs.validators[kid] = validator
}
return nil
}
func withSchemeAndHost(u, base *url.URL) *url.URL {
if u.Host != "" && u.Scheme != "" {
return u
}
r, _ := url.Parse(u.String())
r.Scheme = base.Scheme
r.Host = base.Host
return r
}
func getKeyIDFromFilename(fn string) string {
ext := filepath.Ext(fn)
return strings.TrimSuffix(fn, ext)
}
func getCommonURLPathPrefix(p1, p2 string) (string, error) {
parts1 := strings.Split(p1, "/")
parts2 := strings.Split(p2, "/")
common := make([]string, 0)
for idx, p := range parts1 {
if idx >= len(parts2) {
break
}
if p != parts2[idx] {
break
}
common = append(common, p)
}
if len(common) == 0 {
return "", errors.New("no common path prefix")
}
return strings.Join(common, "/"), nil
}