Debian Codegraph @

jose/parse.go

raw symbols SCIP
1 package jose
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/ecdsa"
7 "crypto/ed25519"
8 "crypto/elliptic"
9 "crypto/rsa"
10 "crypto/x509"
11 "encoding/base64"
12 "encoding/json"
13 "fmt"
14 "io/ioutil"
15 "net/http"
16 "strings"
17 "time"
18
19 "github.com/pkg/errors"
20 "github.com/smallstep/cli/crypto/pemutil"
21 "github.com/smallstep/cli/ui"
22 jose "gopkg.in/square/go-jose.v2"
23 )
24
25 type keyType int
26
27 const (
28 jwkKeyType keyType = iota
29 pemKeyType
30 octKeyType
31 )
32
33 // MaxDecryptTries is the maximum number of attempts to decrypt a file.
34 const MaxDecryptTries = 3
35
36 // Decrypt returns the decrypted version of the given data if it's encrypted,
37 // it will return the raw data if it's not encrypted or the format is not
38 // valid.
39 func Decrypt(prompt string, data []byte, opts ...Option) ([]byte, error) {
40 ctx, err := new(context).apply(opts...)
41 if err != nil {
42 return nil, err
43 }
44
45 enc, err := jose.ParseEncrypted(string(data))
46 if err != nil {
47 return data, nil
48 }
49
50 // Decrypt flow
51 var pass []byte
52 for i := 0; i < MaxDecryptTries; i++ {
53 if len(ctx.password) == 0 {
54 pass, err = ui.PromptPassword(prompt, ctx.uiOptions...)
55 if err != nil {
56 return nil, err
57 }
58 } else {
59 pass = ctx.password
60 }
61
62 if data, err = enc.Decrypt(pass); err == nil {
63 return data, nil
64 }
65 }
66
67 return nil, errors.New("failed to decrypt JWK: invalid password")
68 }
69
70 func defKeyID(jwk *JSONWebKey) error {
71 var (
72 err error
73 hash []byte
74 )
75 hash, err = jwk.Thumbprint(crypto.SHA256)
76 if err != nil {
77 return errors.Wrap(err, "error generating JWK thumbprint")
78 }
79 jwk.KeyID = base64.RawURLEncoding.EncodeToString(hash)
80 return nil
81 }
82
83 // ParseKey returns a JSONWebKey from the given JWK file or a PEM file. For
84 // password protected keys, it will ask the user for a password.
85 // func ParseKey(filename, use, alg, kid string, subtle bool) (*JSONWebKey, error) {
86 func ParseKey(filename string, opts ...Option) (*JSONWebKey, error) {
87 ctx, err := new(context).apply(opts...)
88 if err != nil {
89 return nil, err
90 }
91
92 b, err := ioutil.ReadFile(filename)
93 if err != nil {
94 return nil, errors.Wrapf(err, "error reading %s", filename)
95 }
96
97 jwk := new(JSONWebKey)
98 switch guessKeyType(ctx, b) {
99 case jwkKeyType:
100 // Attempt to parse an encrypted file
101 prompt := fmt.Sprintf("Please enter the password to decrypt %s", filename)
102 if b, err = Decrypt(prompt, b, opts...); err != nil {
103 return nil, err
104 }
105
106 // Unmarshal the plain (or decrypted JWK)
107 if err = json.Unmarshal(b, jwk); err != nil {
108 return nil, errors.Errorf("error reading %s: unsupported format", filename)
109 }
110
111 // If KeyID not set by environment, then use the default.
112 // NOTE: we do not set this value by default in the case of jwkKeyType
113 // because it is assumed to have been left empty on purpose.
114 case pemKeyType:
115 jwk.Key, err = pemutil.ParseKey(b, pemutil.WithFilename(filename), pemutil.WithPassword(ctx.password))
116 if err != nil {
117 return nil, err
118 }
119 if len(ctx.kid) == 0 {
120 if err = defKeyID(jwk); err != nil {
121 return nil, err
122 }
123 }
124
125 case octKeyType:
126 jwk.Key = b
127 if len(ctx.kid) == 0 {
128 if err = defKeyID(jwk); err != nil {
129 return nil, err
130 }
131 }
132 }
133
134 // Validate key id
135 if ctx.kid != "" && jwk.KeyID != "" && ctx.kid != jwk.KeyID {
136 return nil, errors.Errorf("kid %s does not match the kid on %s", ctx.kid, filename)
137 }
138 if jwk.KeyID == "" {
139 jwk.KeyID = ctx.kid
140 }
141 if jwk.Use == "" {
142 jwk.Use = ctx.use
143 }
144
145 // Set the algorithm if empty
146 guessJWKAlgorithm(ctx, jwk)
147
148 // Validate alg: if the flag '--subtle' is passed we will allow to overwrite it
149 if !ctx.subtle && ctx.alg != "" && jwk.Algorithm != "" && ctx.alg != jwk.Algorithm {
150 return nil, errors.Errorf("alg %s does not match the alg on %s", ctx.alg, filename)
151 }
152 if ctx.subtle && ctx.alg != "" {
153 jwk.Algorithm = ctx.alg
154 }
155
156 return jwk, nil
157 }
158
159 // ReadJWKSet reads a JWK Set from a URL or filename. URLs must start with "https://".
160 func ReadJWKSet(filename string) ([]byte, error) {
161 if strings.HasPrefix(filename, "https://") {
162 resp, err := http.Get(filename)
163 if err != nil {
164 return nil, errors.Wrapf(err, "error retrieving %s", filename)
165 }
166 defer resp.Body.Close()
167 b, err := ioutil.ReadAll(resp.Body)
168 if err != nil {
169 return nil, errors.Wrapf(err, "error retrieving %s", filename)
170 }
171 return b, nil
172 }
173 b, err := ioutil.ReadFile(filename)
174 if err != nil {
175 return nil, errors.Wrapf(err, "error reading %s", filename)
176 }
177 return b, nil
178 }
179
180 // ParseKeySet returns the JWK with the given key after parsing a JWKSet from
181 // a given file.
182 // func ParseKeySet(filename, alg, kid string, isSubtle bool) (*jose.JSONWebKey, error) {
183 func ParseKeySet(filename string, opts ...Option) (*jose.JSONWebKey, error) {
184 ctx, err := new(context).apply(opts...)
185 if err != nil {
186 return nil, err
187 }
188
189 b, err := ReadJWKSet(filename)
190 if err != nil {
191 return nil, err
192 }
193
194 // Attempt to parse an encrypted file
195 prompt := fmt.Sprintf("Please enter the password to decrypt %s", filename)
196 if b, err = Decrypt(prompt, b); err != nil {
197 return nil, err
198 }
199
200 // Unmarshal the plain or decrypted JWKSet
201 jwkSet := new(jose.JSONWebKeySet)
202 if err := json.Unmarshal(b, jwkSet); err != nil {
203 return nil, errors.Errorf("error reading %s: unsupported format", filename)
204 }
205
206 jwks := jwkSet.Key(ctx.kid)
207 switch len(jwks) {
208 case 0:
209 return nil, errors.Errorf("cannot find key with kid %s on %s", ctx.kid, filename)
210 case 1:
211 jwk := &jwks[0]
212
213 // Set the algorithm if empty
214 guessJWKAlgorithm(ctx, jwk)
215
216 // Validate alg: if the flag '--subtle' is passed we will allow the
217 // overwrite of the alg
218 if !ctx.subtle && ctx.alg != "" && jwk.Algorithm != "" && ctx.alg != jwk.Algorithm {
219 return nil, errors.Errorf("alg %s does not match the alg on %s", ctx.alg, filename)
220 }
221 if ctx.subtle && ctx.alg != "" {
222 jwk.Algorithm = ctx.alg
223 }
224 return jwk, nil
225 default:
226 return nil, errors.Errorf("multiple keys with kid %s have been found on %s", ctx.kid, filename)
227 }
228 }
229
230 func decodeCerts(l []interface{}) ([]*x509.Certificate, error) {
231 certs := make([]*x509.Certificate, len(l))
232 for i, j := range l {
233 certStr, ok := j.(string)
234 if !ok {
235 return nil, errors.Errorf("wrong type in x5c header list; expected string but %T", i)
236 }
237 certB, err := base64.StdEncoding.DecodeString(certStr)
238 if err != nil {
239 return nil, errors.Wrap(err, "error decoding base64 encoded x5c cert")
240 }
241 cert, err := x509.ParseCertificate(certB)
242 if err != nil {
243 return nil, errors.Wrap(err, "error parsing x5c cert")
244 }
245 certs[i] = cert
246 }
247 return certs, nil
248 }
249
250 // X5cInsecureKey is the key used to store the x5cInsecure cert chain in the JWT header.
251 var X5cInsecureKey = "x5cInsecure"
252
253 // GetX5cInsecureHeader extracts the x5cInsecure certificate chain from the token.
254 func GetX5cInsecureHeader(jwt *JSONWebToken) ([]*x509.Certificate, error) {
255 x5cVal, ok := jwt.Headers[0].ExtraHeaders[jose.HeaderKey(X5cInsecureKey)]
256 if !ok {
257 return nil, errors.New("ssh check-host token missing x5cInsecure header")
258 }
259 interfaces, ok := x5cVal.([]interface{})
260 if !ok {
261 return nil, errors.Errorf("ssh check-host token x5cInsecure header has wrong type; expected []string, but got %T", x5cVal)
262 }
263 chain, err := decodeCerts(interfaces)
264 if err != nil {
265 return nil, errors.Wrap(err, "error decoding x5cInsecure header certs")
266 }
267 return chain, nil
268 }
269
270 // ParseX5cInsecure parses an x5cInsecure token, validates the certificate chain
271 // in the token, and returns the JWT struct along with all the verified chains.
272 func ParseX5cInsecure(tok string, roots []*x509.Certificate) (*JSONWebToken, [][]*x509.Certificate, error) {
273 jwt, err := ParseSigned(tok)
274 if err != nil {
275 return nil, nil, errors.Wrapf(err, "error parsing x5cInsecure token")
276 }
277
278 chain, err := GetX5cInsecureHeader(jwt)
279 if err != nil {
280 return nil, nil, errors.Wrap(err, "error extracting x5cInsecure cert chain")
281 }
282 leaf := chain[0]
283
284 interPool := x509.NewCertPool()
285 for _, crt := range chain[1:] {
286 interPool.AddCert(crt)
287 }
288 rootPool := x509.NewCertPool()
289 for _, crt := range roots {
290 rootPool.AddCert(crt)
291 }
292 // Correctly parse and validate the x5c certificate chain.
293 verifiedChains, err := leaf.Verify(x509.VerifyOptions{
294 Roots: rootPool,
295 Intermediates: interPool,
296 // A hack so we skip validity period validation.
297 CurrentTime: leaf.NotAfter.Add(-1 * time.Minute),
298 })
299 if err != nil {
300 return nil, nil, errors.Wrap(err, "error verifying x5cInsecure certificate chain")
301 }
302 leaf = verifiedChains[0][0]
303
304 if leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {
305 return nil, nil, errors.New("certificate used to sign x5cInsecure token cannot be used for digital signature")
306 }
307
308 return jwt, verifiedChains, nil
309 }
310
311 // guessKeyType returns the key type of the given data. Key types are JWK, PEM
312 // or oct.
313 func guessKeyType(ctx *context, data []byte) keyType {
314 switch ctx.alg {
315 // jwk or file with oct data
316 case "HS256", "HS384", "HS512":
317 // Encrypted JWK ?
318 if _, err := jose.ParseEncrypted(string(data)); err == nil {
319 return jwkKeyType
320 }
321 // JSON JWK ?
322 if err := json.Unmarshal(data, &JSONWebKey{}); err == nil {
323 return jwkKeyType
324 }
325 // Default to oct
326 return octKeyType
327 default:
328 // PEM or default to JWK
329 if bytes.HasPrefix(data, []byte("-----BEGIN ")) {
330 return pemKeyType
331 }
332 return jwkKeyType
333 }
334 }
335
336 // guessJWKAlgorithm set the algorithm if it's not set and we can guess it
337 func guessJWKAlgorithm(ctx *context, jwk *jose.JSONWebKey) {
338 if jwk.Algorithm == "" {
339 // Force default algorithm if passed.
340 if ctx.alg != "" {
341 jwk.Algorithm = ctx.alg
342 return
343 }
344
345 // Guess only fixed algorithms if no defaults is enabled
346 if ctx.noDefaults {
347 guessKnownJWKAlgorithm(ctx, jwk)
348 return
349 }
350
351 // Use defaults for each key type
352 switch k := jwk.Key.(type) {
353 case []byte:
354 if jwk.Use == "enc" {
355 jwk.Algorithm = string(DefaultOctKeyAlgorithm)
356 } else {
357 jwk.Algorithm = string(DefaultOctSigsAlgorithm)
358 }
359 case *ecdsa.PrivateKey:
360 if jwk.Use == "enc" {
361 jwk.Algorithm = string(DefaultECKeyAlgorithm)
362 } else {
363 jwk.Algorithm = getECAlgorithm(k.Curve)
364 }
365 case *ecdsa.PublicKey:
366 if jwk.Use == "enc" {
367 jwk.Algorithm = string(DefaultECKeyAlgorithm)
368 } else {
369 jwk.Algorithm = getECAlgorithm(k.Curve)
370 }
371 case *rsa.PrivateKey, *rsa.PublicKey:
372 if jwk.Use == "enc" {
373 jwk.Algorithm = string(DefaultRSAKeyAlgorithm)
374 } else {
375 jwk.Algorithm = string(DefaultRSASigAlgorithm)
376 }
377 // Ed25519 can only be used for signing operations
378 case ed25519.PrivateKey, ed25519.PublicKey:
379 jwk.Algorithm = EdDSA
380 }
381 }
382 }
383
384 // guessKnownJWKAlgorithm sets the algorithm for keys that only have one
385 // possible algorithm.
386 func guessKnownJWKAlgorithm(ctx *context, jwk *jose.JSONWebKey) {
387 if jwk.Algorithm == "" && jwk.Use != "enc" {
388 switch k := jwk.Key.(type) {
389 case *ecdsa.PrivateKey:
390 jwk.Algorithm = getECAlgorithm(k.Curve)
391 case *ecdsa.PublicKey:
392 jwk.Algorithm = getECAlgorithm(k.Curve)
393 case ed25519.PrivateKey, ed25519.PublicKey:
394 jwk.Algorithm = EdDSA
395 }
396 }
397 }
398
399 // getECAlgorithm returns the JWA algorithm name for the given elliptic curve.
400 // If the curve is not supported it will return an empty string.
401 //
402 // Supported curves are P-256, P-384, and P-521.
403 func getECAlgorithm(crv elliptic.Curve) string {
404 switch crv.Params().Name {
405 case P256:
406 return ES256
407 case P384:
408 return ES384
409 case P521:
410 return ES512
411 default:
412 return ""
413 }
414 }