Debian Codegraph @

jose.go

raw
1 // Package jose provides high level functions for producing (signing, encrypting and
2 // compressing) or consuming (decoding) Json Web Tokens using Java Object Signing and Encryption spec
3 package jose
4
5 import (
6 "encoding/json"
7 "errors"
8 "fmt"
9
10 "github.com/dvsekhvalnov/jose2go/compact"
11 )
12
13 const (
14 NONE = "none" //plaintext (unprotected) without signature / encryption
15
16 HS256 = "HS256" //HMAC using SHA-256 hash
17 HS384 = "HS384" //HMAC using SHA-384 hash
18 HS512 = "HS512" //HMAC using SHA-512 hash
19 RS256 = "RS256" //RSASSA-PKCS-v1_5 using SHA-256 hash
20 RS384 = "RS384" //RSASSA-PKCS-v1_5 using SHA-384 hash
21 RS512 = "RS512" //RSASSA-PKCS-v1_5 using SHA-512 hash
22 PS256 = "PS256" //RSASSA-PSS using SHA-256 hash
23 PS384 = "PS384" //RSASSA-PSS using SHA-384 hash
24 PS512 = "PS512" //RSASSA-PSS using SHA-512 hash
25 ES256 = "ES256" //ECDSA using P-256 curve and SHA-256 hash
26 ES384 = "ES384" //ECDSA using P-384 curve and SHA-384 hash
27 ES512 = "ES512" //ECDSA using P-521 curve and SHA-512 hash
28
29 A128CBC_HS256 = "A128CBC-HS256" //AES in CBC mode with PKCS #5 (NIST.800-38A) padding with HMAC using 256 bit key
30 A192CBC_HS384 = "A192CBC-HS384" //AES in CBC mode with PKCS #5 (NIST.800-38A) padding with HMAC using 384 bit key
31 A256CBC_HS512 = "A256CBC-HS512" //AES in CBC mode with PKCS #5 (NIST.800-38A) padding with HMAC using 512 bit key
32 A128GCM = "A128GCM" //AES in GCM mode with 128 bit key
33 A192GCM = "A192GCM" //AES in GCM mode with 192 bit key
34 A256GCM = "A256GCM" //AES in GCM mode with 256 bit key
35
36 DIR = "dir" //Direct use of pre-shared symmetric key
37 RSA1_5 = "RSA1_5" //RSAES with PKCS #1 v1.5 padding, RFC 3447
38 RSA_OAEP = "RSA-OAEP" //RSAES using Optimal Assymetric Encryption Padding, RFC 3447
39 RSA_OAEP_256 = "RSA-OAEP-256" //RSAES using Optimal Assymetric Encryption Padding with SHA-256, RFC 3447
40 RSA_OAEP_384 = "RSA-OAEP-384" //RSAES using Optimal Assymetric Encryption Padding with SHA-384, RFC 3447
41 RSA_OAEP_512 = "RSA-OAEP-512" //RSAES using Optimal Assymetric Encryption Padding with SHA-512, RFC 3447
42 A128KW = "A128KW" //AES Key Wrap Algorithm using 128 bit keys, RFC 3394
43 A192KW = "A192KW" //AES Key Wrap Algorithm using 192 bit keys, RFC 3394
44 A256KW = "A256KW" //AES Key Wrap Algorithm using 256 bit keys, RFC 3394
45 A128GCMKW = "A128GCMKW" //AES GCM Key Wrap Algorithm using 128 bit keys
46 A192GCMKW = "A192GCMKW" //AES GCM Key Wrap Algorithm using 192 bit keys
47 A256GCMKW = "A256GCMKW" //AES GCM Key Wrap Algorithm using 256 bit keys
48 PBES2_HS256_A128KW = "PBES2-HS256+A128KW" //Password Based Encryption using PBES2 schemes with HMAC-SHA and AES Key Wrap using 128 bit key
49 PBES2_HS384_A192KW = "PBES2-HS384+A192KW" //Password Based Encryption using PBES2 schemes with HMAC-SHA and AES Key Wrap using 192 bit key
50 PBES2_HS512_A256KW = "PBES2-HS512+A256KW" //Password Based Encryption using PBES2 schemes with HMAC-SHA and AES Key Wrap using 256 bit key
51 ECDH_ES = "ECDH-ES" //Elliptic Curve Diffie Hellman key agreement
52 ECDH_ES_A128KW = "ECDH-ES+A128KW" //Elliptic Curve Diffie Hellman key agreement with AES Key Wrap using 128 bit key
53 ECDH_ES_A192KW = "ECDH-ES+A192KW" //Elliptic Curve Diffie Hellman key agreement with AES Key Wrap using 192 bit key
54 ECDH_ES_A256KW = "ECDH-ES+A256KW" //Elliptic Curve Diffie Hellman key agreement with AES Key Wrap using 256 bit key
55
56 DEF = "DEF" //DEFLATE compression, RFC 1951
57 )
58
59 var jwsHashers = map[string]JwsAlgorithm{}
60 var jweEncryptors = map[string]JweEncryption{}
61 var jwaAlgorithms = map[string]JwaAlgorithm{}
62 var jwcCompressors = map[string]JwcAlgorithm{}
63
64 // RegisterJwe register new encryption algorithm
65 func RegisterJwe(alg JweEncryption) {
66 jweEncryptors[alg.Name()] = alg
67 }
68
69 // RegisterJwa register new key management algorithm
70 func RegisterJwa(alg JwaAlgorithm) {
71 jwaAlgorithms[alg.Name()] = alg
72 }
73
74 // RegisterJws register new signing algorithm
75 func RegisterJws(alg JwsAlgorithm) {
76 jwsHashers[alg.Name()] = alg
77 }
78
79 // RegisterJwc register new compression algorithm
80 func RegisterJwc(alg JwcAlgorithm) {
81 jwcCompressors[alg.Name()] = alg
82 }
83
84 // DeregisterJwa deregister existing key management algorithm
85 func DeregisterJwa(alg string) JwaAlgorithm {
86 jwa := jwaAlgorithms[alg]
87
88 delete(jwaAlgorithms, alg)
89
90 return jwa
91 }
92
93 // DeregisterJws deregister existing signing algorithm
94 func DeregisterJws(alg string) JwsAlgorithm {
95 jws := jwsHashers[alg]
96
97 delete(jwsHashers, alg)
98
99 return jws
100 }
101
102 // DeregisterJws deregister existing encryption algorithm
103 func DeregisterJwe(alg string) JweEncryption {
104 jwe := jweEncryptors[alg]
105
106 delete(jweEncryptors, alg)
107
108 return jwe
109 }
110
111 // DeregisterJwc deregister existing compression algorithm
112 func DeregisterJwc(alg string) JwcAlgorithm {
113 jwc := jwcCompressors[alg]
114
115 delete(jwcCompressors, alg)
116
117 return jwc
118 }
119
120 // JweEncryption is a contract for implementing encryption algorithm
121 type JweEncryption interface {
122 Encrypt(aad, plainText, cek []byte) (iv, cipherText, authTag []byte, err error)
123 Decrypt(aad, cek, iv, cipherText, authTag []byte) (plainText []byte, err error)
124 KeySizeBits() int
125 Name() string
126 }
127
128 // JwaAlgorithm is a contract for implementing key management algorithm
129 type JwaAlgorithm interface {
130 WrapNewKey(cekSizeBits int, key interface{}, header map[string]interface{}) (cek []byte, encryptedCek []byte, err error)
131 Unwrap(encryptedCek []byte, key interface{}, cekSizeBits int, header map[string]interface{}) (cek []byte, err error)
132 Name() string
133 }
134
135 // JwsAlgorithm is a contract for implementing signing algorithm
136 type JwsAlgorithm interface {
137 Verify(securedInput, signature []byte, key interface{}) error
138 Sign(securedInput []byte, key interface{}) (signature []byte, err error)
139 Name() string
140 }
141
142 // JwcAlgorithm is a contract for implementing compression algorithm
143 type JwcAlgorithm interface {
144 Compress(plainText []byte) []byte
145 Decompress(compressedText []byte) ([]byte, error)
146 Name() string
147 }
148
149 func Zip(alg string) func(cfg *JoseConfig) {
150 return func(cfg *JoseConfig) {
151 cfg.CompressionAlg = alg
152 }
153 }
154
155 func Header(name string, value interface{}) func(cfg *JoseConfig) {
156 return func(cfg *JoseConfig) {
157 cfg.Headers[name] = value
158 }
159 }
160
161 func Headers(headers map[string]interface{}) func(cfg *JoseConfig) {
162 return func(cfg *JoseConfig) {
163 for k, v := range headers {
164 cfg.Headers[k] = v
165 }
166 }
167 }
168
169 type JoseConfig struct {
170 CompressionAlg string
171 Headers map[string]interface{}
172 }
173
174 // Sign produces signed JWT token given arbitrary string payload, signature algorithm to use (see constants for list of supported algs), signing key and extra options (see option functions)
175 // Signing key is of different type for different signing alg, see specific
176 // signing alg implementation documentation.
177 //
178 // It returns 3 parts signed JWT token as string and not nil error if something went wrong.
179 func Sign(payload string, signingAlg string, key interface{}, options ...func(*JoseConfig)) (token string, err error) {
180 return SignBytes([]byte(payload), signingAlg, key, options...)
181 }
182
183 // Sign produces signed JWT token given arbitrary binary payload, signature algorithm to use (see constants for list of supported algs), signing key and extra options (see option functions)
184 // Signing key is of different type for different signing alg, see specific
185 // signing alg implementation documentation.
186 //
187 // It returns 3 parts signed JWT token as string and not nil error if something went wrong.
188 func SignBytes(payload []byte, signingAlg string, key interface{}, options ...func(*JoseConfig)) (token string, err error) {
189 if signer, ok := jwsHashers[signingAlg]; ok {
190
191 cfg := &JoseConfig{CompressionAlg: "", Headers: make(map[string]interface{})}
192
193 //apply extra options
194 for _, option := range options {
195 option(cfg)
196 }
197
198 //make sure defaults and requires are managed by us
199 cfg.Headers["alg"] = signingAlg
200
201 paloadBytes := payload
202 var header []byte
203 var signature []byte
204
205 if header, err = json.Marshal(cfg.Headers); err == nil {
206 securedInput := []byte(compact.Serialize(header, paloadBytes))
207
208 if signature, err = signer.Sign(securedInput, key); err == nil {
209 return compact.Serialize(header, paloadBytes, signature), nil
210 }
211 }
212
213 return "", err
214 }
215
216 return "", errors.New(fmt.Sprintf("jwt.Sign(): unknown algorithm: '%v'", signingAlg))
217 }
218
219 // Encrypt produces encrypted JWT token given arbitrary string payload, key management and encryption algorithms to use (see constants for list of supported algs) and management key.
220 // Management key is of different type for different key management alg, see specific
221 // key management alg implementation documentation.
222 //
223 // It returns 5 parts encrypted JWT token as string and not nil error if something went wrong.
224 func Encrypt(payload string, alg string, enc string, key interface{}, options ...func(*JoseConfig)) (token string, err error) {
225 return EncryptBytes([]byte(payload), alg, enc, key, options...)
226 }
227
228 // Encrypt produces encrypted JWT token given arbitrary binary payload, key management and encryption algorithms to use (see constants for list of supported algs) and management key.
229 // Management key is of different type for different key management alg, see specific
230 // key management alg implementation documentation.
231 //
232 // It returns 5 parts encrypted JWT token as string and not nil error if something went wrong.
233 func EncryptBytes(payload []byte, alg string, enc string, key interface{}, options ...func(*JoseConfig)) (token string, err error) {
234
235 cfg := &JoseConfig{CompressionAlg: "", Headers: make(map[string]interface{})}
236
237 //apply extra options
238 for _, option := range options {
239 option(cfg)
240 }
241
242 //make sure required headers are managed by us
243 cfg.Headers["alg"] = alg
244 cfg.Headers["enc"] = enc
245
246 byteContent := payload
247
248 if cfg.CompressionAlg != "" {
249 if zipAlg, ok := jwcCompressors[cfg.CompressionAlg]; ok {
250 byteContent = zipAlg.Compress([]byte(payload))
251 cfg.Headers["zip"] = cfg.CompressionAlg
252 } else {
253 return "", errors.New(fmt.Sprintf("jwt.Compress(): Unknown compression method '%v'", cfg.CompressionAlg))
254 }
255
256 } else {
257 delete(cfg.Headers, "zip") //we not allow to manage 'zip' header manually for encryption
258 }
259
260 return encrypt(byteContent, cfg.Headers, key)
261 }
262
263 // This method is DEPRICATED and subject to be removed in next version.
264 // Use Encrypt(..) with Zip option instead.
265 //
266 // Compress produces encrypted & comressed JWT token given arbitrary payload, key management , encryption and compression algorithms to use (see constants for list of supported algs) and management key.
267 // Management key is of different type for different key management alg, see specific
268 // key management alg implementation documentation.
269 //
270 // It returns 5 parts encrypted & compressed JWT token as string and not nil error if something went wrong.
271 func Compress(payload string, alg string, enc string, zip string, key interface{}) (token string, err error) {
272
273 if zipAlg, ok := jwcCompressors[zip]; ok {
274 compressed := zipAlg.Compress([]byte(payload))
275
276 jwtHeader := map[string]interface{}{
277 "enc": enc,
278 "alg": alg,
279 "zip": zip,
280 }
281
282 return encrypt(compressed, jwtHeader, key)
283 }
284
285 return "", errors.New(fmt.Sprintf("jwt.Compress(): Unknown compression method '%v'", zip))
286 }
287
288 // Decode verifies, decrypts and decompresses given JWT token using management key.
289 // Management key is of different type for different key management or signing algorithms, see specific alg implementation documentation.
290 //
291 // Returns decoded payload as a string, headers and not nil error if something went wrong.
292 func Decode(token string, key interface{}) (string, map[string]interface{}, error) {
293
294 payload, headers, err := DecodeBytes(token, key)
295
296 if err != nil {
297 return "", nil, err
298 }
299
300 return string(payload), headers, nil
301 }
302
303 // Decode verifies, decrypts and decompresses given JWT token using management key.
304 // Management key is of different type for different key management or signing algorithms, see specific alg implementation documentation.
305 //
306 // Returns decoded payload as a raw bytes, headers and not nil error if something went wrong.
307 func DecodeBytes(token string, key interface{}) ([]byte, map[string]interface{}, error) {
308 parts, err := compact.Parse(token)
309
310 if err != nil {
311 return nil, nil, err
312 }
313
314 if len(parts) == 3 {
315 return verify(parts, key)
316 }
317
318 if len(parts) == 5 {
319 return decrypt(parts, key)
320 }
321
322 return nil, nil, errors.New(fmt.Sprintf("jwt.DecodeBytes() expects token of 3 or 5 parts, but was given: %v parts", len(parts)))
323 }
324
325 func encrypt(payload []byte, jwtHeader map[string]interface{}, key interface{}) (token string, err error) {
326 var ok bool
327 var keyMgmtAlg JwaAlgorithm
328 var encAlg JweEncryption
329
330 alg := jwtHeader["alg"].(string)
331 enc := jwtHeader["enc"].(string)
332
333 if keyMgmtAlg, ok = jwaAlgorithms[alg]; !ok {
334 return "", errors.New(fmt.Sprintf("jwt.encrypt(): Unknown key management algorithm '%v'", alg))
335 }
336
337 if encAlg, ok = jweEncryptors[enc]; !ok {
338 return "", errors.New(fmt.Sprintf("jwt.encrypt(): Unknown encryption algorithm '%v'", enc))
339 }
340
341 var cek, encryptedCek, header, iv, cipherText, authTag []byte
342
343 if cek, encryptedCek, err = keyMgmtAlg.WrapNewKey(encAlg.KeySizeBits(), key, jwtHeader); err != nil {
344 return "", err
345 }
346
347 if header, err = json.Marshal(jwtHeader); err != nil {
348 return "", err
349 }
350
351 if iv, cipherText, authTag, err = encAlg.Encrypt([]byte(compact.Serialize(header)), payload, cek); err != nil {
352 return "", err
353 }
354
355 return compact.Serialize(header, encryptedCek, iv, cipherText, authTag), nil
356 }
357
358 func verify(parts [][]byte, key interface{}) (plainText []byte, headers map[string]interface{}, err error) {
359
360 header, payload, signature := parts[0], parts[1], parts[2]
361
362 secured := []byte(compact.Serialize(header, payload))
363
364 var jwtHeader map[string]interface{}
365
366 if err = json.Unmarshal(header, &jwtHeader); err != nil {
367 return nil, nil, err
368 }
369
370 if alg, ok := jwtHeader["alg"].(string); ok {
371 if verifier, ok := jwsHashers[alg]; ok {
372 if key, err = retrieveActualKey(jwtHeader, string(payload), key); err != nil {
373 return nil, nil, err
374 }
375
376 if err = verifier.Verify(secured, signature, key); err == nil {
377 return payload, jwtHeader, nil
378 }
379
380 return nil, nil, err
381 }
382
383 return nil, nil, errors.New(fmt.Sprintf("jwt.Decode(): Unknown algorithm: '%v'", alg))
384 }
385
386 return nil, nil, errors.New(fmt.Sprint("jwt.Decode(): required 'alg' header is missing or of invalid type"))
387 }
388
389 func decrypt(parts [][]byte, key interface{}) (plainText []byte, headers map[string]interface{}, err error) {
390
391 header, encryptedCek, iv, cipherText, authTag := parts[0], parts[1], parts[2], parts[3], parts[4]
392
393 var jwtHeader map[string]interface{}
394
395 if e := json.Unmarshal(header, &jwtHeader); e != nil {
396 return nil, nil, e
397 }
398
399 var keyMgmtAlg JwaAlgorithm
400 var encAlg JweEncryption
401 var zipAlg JwcAlgorithm
402 var cek, plainBytes []byte
403 var ok bool
404 var alg, enc string
405
406 if alg, ok = jwtHeader["alg"].(string); !ok {
407 return nil, nil, errors.New(fmt.Sprint("jwt.Decode(): required 'alg' header is missing or of invalid type"))
408 }
409
410 if enc, ok = jwtHeader["enc"].(string); !ok {
411 return nil, nil, errors.New(fmt.Sprint("jwt.Decode(): required 'enc' header is missing or of invalid type"))
412 }
413
414 aad := []byte(compact.Serialize(header))
415
416 if keyMgmtAlg, ok = jwaAlgorithms[alg]; ok {
417 if encAlg, ok = jweEncryptors[enc]; ok {
418
419 if key, err = retrieveActualKey(jwtHeader, string(cipherText), key); err != nil {
420 return nil, nil, err
421 }
422
423 if cek, err = keyMgmtAlg.Unwrap(encryptedCek, key, encAlg.KeySizeBits(), jwtHeader); err == nil {
424 if plainBytes, err = encAlg.Decrypt(aad, cek, iv, cipherText, authTag); err == nil {
425
426 if zip, compressed := jwtHeader["zip"].(string); compressed {
427
428 if zipAlg, ok = jwcCompressors[zip]; !ok {
429 return nil, nil, errors.New(fmt.Sprintf("jwt.decrypt(): Unknown compression algorithm '%v'", zip))
430 }
431
432 if plainBytes, err = zipAlg.Decompress(plainBytes); err != nil {
433 return nil, nil, err
434 }
435 }
436
437 return plainBytes, jwtHeader, nil
438 }
439
440 return nil, nil, err
441 }
442
443 return nil, nil, err
444 }
445
446 return nil, nil, errors.New(fmt.Sprintf("jwt.decrypt(): Unknown encryption algorithm '%v'", enc))
447 }
448
449 return nil, nil, errors.New(fmt.Sprintf("jwt.decrypt(): Unknown key management algorithm '%v'", alg))
450 }
451
452 func retrieveActualKey(headers map[string]interface{}, payload string, key interface{}) (interface{}, error) {
453 if keyCallback, ok := key.(func(headers map[string]interface{}, payload string) interface{}); ok {
454 result := keyCallback(headers, payload)
455
456 if err, ok := result.(error); ok {
457 return nil, err
458 }
459
460 return result, nil
461 }
462
463 return key, nil
464 }
465
466 func Alg(key interface{}, jws string) func(headers map[string]interface{}, payload string) interface{} {
467 return func(headers map[string]interface{}, payload string) interface{} {
468 alg := headers["alg"].(string)
469
470 if jws == alg {
471 return key
472 }
473
474 return errors.New("Expected alg to be '" + jws + "' but got '" + alg + "'")
475 }
476 }
477
478 func Enc(key interface{}, jwa string, jwe string) func(headers map[string]interface{}, payload string) interface{} {
479 return func(headers map[string]interface{}, payload string) interface{} {
480 alg := headers["alg"].(string)
481 enc := headers["enc"].(string)
482
483 if jwa == alg && jwe == enc {
484 return key
485 }
486
487 return errors.New("Expected alg to be '" + jwa + "' and enc to be '" + jwe + "' but got '" + alg + "' and '" + enc + "'")
488 }
489 }