forked from lestrrat-go/jwx
/
message.go
534 lines (471 loc) · 11.3 KB
/
message.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package jwe
import (
"bytes"
"compress/flate"
"encoding/json"
"errors"
"fmt"
"net/url"
"github.com/lestrrat/go-jwx/buffer"
"github.com/lestrrat/go-jwx/internal/debug"
"github.com/lestrrat/go-jwx/internal/emap"
"github.com/lestrrat/go-jwx/jwa"
"github.com/lestrrat/go-jwx/jwk"
)
// NewRecipient creates a Recipient object
func NewRecipient() *Recipient {
return &Recipient{
Header: NewHeader(),
}
}
// NewHeader creates a new Header object
func NewHeader() *Header {
return &Header{
EssentialHeader: &EssentialHeader{},
PrivateParams: map[string]interface{}{},
}
}
// NewEncodedHeader creates a new encoded Header object
func NewEncodedHeader() *EncodedHeader {
return &EncodedHeader{
Header: NewHeader(),
}
}
// Get returns the header key
func (h *Header) Get(key string) (interface{}, error) {
switch key {
case "alg":
return h.Algorithm, nil
case "apu":
return h.AgreementPartyUInfo, nil
case "apv":
return h.AgreementPartyVInfo, nil
case "enc":
return h.ContentEncryption, nil
case "epk":
return h.EphemeralPublicKey, nil
case "cty":
return h.ContentType, nil
case "kid":
return h.KeyID, nil
case "typ":
return h.Type, nil
case "x5t":
return h.X509CertThumbprint, nil
case "x5t#256":
return h.X509CertThumbprintS256, nil
case "x5c":
return h.X509CertChain, nil
case "crit":
return h.Critical, nil
case "jku":
return h.JwkSetURL, nil
case "x5u":
return h.X509Url, nil
default:
v, ok := h.PrivateParams[key]
if !ok {
return nil, errors.New("invalid header name")
}
return v, nil
}
}
// Set sets the value of the given key to the given value. If it's
// one of the known keys, it will be set in EssentialHeader field.
// Otherwise, it is set in PrivateParams field.
func (h *Header) Set(key string, value interface{}) error {
switch key {
case "alg":
var v jwa.KeyEncryptionAlgorithm
s, ok := value.(string)
if ok {
v = jwa.KeyEncryptionAlgorithm(s)
} else {
v, ok = value.(jwa.KeyEncryptionAlgorithm)
if !ok {
return ErrInvalidHeaderValue
}
}
h.Algorithm = v
case "apu":
var v buffer.Buffer
switch value.(type) {
case buffer.Buffer:
v = value.(buffer.Buffer)
case []byte:
v = buffer.Buffer(value.([]byte))
case string:
v = buffer.Buffer(value.(string))
default:
return ErrInvalidHeaderValue
}
h.AgreementPartyUInfo = v
case "apv":
var v buffer.Buffer
switch value.(type) {
case buffer.Buffer:
v = value.(buffer.Buffer)
case []byte:
v = buffer.Buffer(value.([]byte))
case string:
v = buffer.Buffer(value.(string))
default:
return ErrInvalidHeaderValue
}
h.AgreementPartyVInfo = v
case "enc":
var v jwa.ContentEncryptionAlgorithm
s, ok := value.(string)
if ok {
v = jwa.ContentEncryptionAlgorithm(s)
} else {
v, ok = value.(jwa.ContentEncryptionAlgorithm)
if !ok {
return ErrInvalidHeaderValue
}
}
h.ContentEncryption = v
case "cty":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
h.ContentType = v
case "epk":
v, ok := value.(*jwk.EcdsaPublicKey)
if !ok {
return ErrInvalidHeaderValue
}
h.EphemeralPublicKey = v
case "kid":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
h.KeyID = v
case "typ":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
h.Type = v
case "x5t":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
h.X509CertThumbprint = v
case "x5t#256":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
h.X509CertThumbprintS256 = v
case "x5c":
v, ok := value.([]string)
if !ok {
return ErrInvalidHeaderValue
}
h.X509CertChain = v
case "crit":
v, ok := value.([]string)
if !ok {
return ErrInvalidHeaderValue
}
h.Critical = v
case "jku":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
u, err := url.Parse(v)
if err != nil {
return ErrInvalidHeaderValue
}
h.JwkSetURL = u
case "x5u":
v, ok := value.(string)
if !ok {
return ErrInvalidHeaderValue
}
u, err := url.Parse(v)
if err != nil {
return ErrInvalidHeaderValue
}
h.X509Url = u
default:
h.PrivateParams[key] = value
}
return nil
}
// Merge merges the current header with another.
func (h *Header) Merge(h2 *Header) (*Header, error) {
if h2 == nil {
return nil, errors.New("merge target is nil")
}
h3 := NewHeader()
if err := h3.Copy(h); err != nil {
return nil, err
}
h3.EssentialHeader.Merge(h2.EssentialHeader)
for k, v := range h2.PrivateParams {
h3.PrivateParams[k] = v
}
return h3, nil
}
// Merge merges the current header with another.
func (h *EssentialHeader) Merge(h2 *EssentialHeader) {
if h2.AgreementPartyUInfo.Len() != 0 {
h.AgreementPartyUInfo = h2.AgreementPartyUInfo
}
if h2.AgreementPartyVInfo.Len() != 0 {
h.AgreementPartyVInfo = h2.AgreementPartyVInfo
}
if h2.Algorithm != "" {
h.Algorithm = h2.Algorithm
}
if h2.ContentEncryption != "" {
h.ContentEncryption = h2.ContentEncryption
}
if h2.ContentType != "" {
h.ContentType = h2.ContentType
}
if h2.Compression != "" {
h.Compression = h2.Compression
}
if h2.Critical != nil {
h.Critical = h2.Critical
}
if h2.EphemeralPublicKey != nil {
h.EphemeralPublicKey = h2.EphemeralPublicKey
}
if h2.Jwk != nil {
h.Jwk = h2.Jwk
}
if h2.JwkSetURL != nil {
h.JwkSetURL = h2.JwkSetURL
}
if h2.KeyID != "" {
h.KeyID = h2.KeyID
}
if h2.Type != "" {
h.Type = h2.Type
}
if h2.X509Url != nil {
h.X509Url = h2.X509Url
}
if h2.X509CertChain != nil {
h.X509CertChain = h2.X509CertChain
}
if h2.X509CertThumbprint != "" {
h.X509CertThumbprint = h2.X509CertThumbprint
}
if h2.X509CertThumbprintS256 != "" {
h.X509CertThumbprintS256 = h2.X509CertThumbprintS256
}
}
// Copy copies the other heder over this one
func (h *Header) Copy(h2 *Header) error {
if h == nil {
return errors.New("copy destination is nil")
}
if h2 == nil {
return errors.New("copy target is nil")
}
h.EssentialHeader.Copy(h2.EssentialHeader)
for k, v := range h2.PrivateParams {
h.PrivateParams[k] = v
}
return nil
}
// Copy copies the other heder over this one
func (h *EssentialHeader) Copy(h2 *EssentialHeader) {
h.AgreementPartyUInfo = h2.AgreementPartyUInfo
h.AgreementPartyVInfo = h2.AgreementPartyVInfo
h.Algorithm = h2.Algorithm
h.ContentEncryption = h2.ContentEncryption
h.ContentType = h2.ContentType
h.Compression = h2.Compression
h.Critical = h2.Critical
h.EphemeralPublicKey = h2.EphemeralPublicKey
h.Jwk = h2.Jwk
h.JwkSetURL = h2.JwkSetURL
h.KeyID = h2.KeyID
h.Type = h2.Type
h.X509Url = h2.X509Url
h.X509CertChain = h2.X509CertChain
h.X509CertThumbprint = h2.X509CertThumbprint
h.X509CertThumbprintS256 = h2.X509CertThumbprintS256
}
// MarshalJSON generates the JSON representation of this header
func (h Header) MarshalJSON() ([]byte, error) {
return emap.MergeMarshal(h.EssentialHeader, h.PrivateParams)
}
// UnmarshalJSON parses the JSON buffer into a Header
func (h *Header) UnmarshalJSON(data []byte) error {
if h.EssentialHeader == nil {
h.EssentialHeader = &EssentialHeader{}
}
if h.PrivateParams == nil {
h.PrivateParams = map[string]interface{}{}
}
if err := json.Unmarshal(data, h.EssentialHeader); err != nil {
return err
}
m := map[string]interface{}{}
if err := json.Unmarshal(data, &m); err != nil {
return err
}
for _, n := range []string{"alg", "apu", "apv", "enc", "cty", "zip", "crit", "epk", "jwk", "jku", "kid", "typ", "x5u", "x5c", "x5t", "x5t#S256"} {
delete(m, n)
}
for name, value := range m {
if err := h.Set(name, value); err != nil {
return err
}
}
return nil
}
// Base64Encode creates the base64 encoded version of the JSON
// representation of this header
func (e EncodedHeader) Base64Encode() ([]byte, error) {
buf, err := json.Marshal(e.Header)
if err != nil {
return nil, err
}
buf, err = buffer.Buffer(buf).Base64Encode()
if err != nil {
return nil, err
}
return buf, nil
}
// MarshalJSON generates the JSON representation of this header
func (e EncodedHeader) MarshalJSON() ([]byte, error) {
buf, err := e.Base64Encode()
if err != nil {
return nil, err
}
return json.Marshal(string(buf))
}
// UnmarshalJSON parses the JSON buffer into a Header
func (e *EncodedHeader) UnmarshalJSON(buf []byte) error {
b := buffer.Buffer{}
// base646 json string -> json object representation of header
if err := json.Unmarshal(buf, &b); err != nil {
return err
}
if err := json.Unmarshal(b.Bytes(), &e.Header); err != nil {
return err
}
return nil
}
// NewMessage creates a new message
func NewMessage() *Message {
return &Message{
ProtectedHeader: NewEncodedHeader(),
UnprotectedHeader: NewHeader(),
}
}
// Decrypt decrypts the message using the specified algorithm and key
func (m *Message) Decrypt(alg jwa.KeyEncryptionAlgorithm, key interface{}) ([]byte, error) {
var err error
if len(m.Recipients) == 0 {
return nil, errors.New("no recipients, can not proceed with decrypt")
}
enc := m.ProtectedHeader.ContentEncryption
h := NewHeader()
if err := h.Copy(m.ProtectedHeader.Header); err != nil {
return nil, err
}
h, err = h.Merge(m.UnprotectedHeader)
if err != nil {
if debug.Enabled {
debug.Printf("failed to merge unprotected header")
}
return nil, err
}
aad, err := m.AuthenticatedData.Base64Encode()
if err != nil {
return nil, err
}
ciphertext := m.CipherText.Bytes()
iv := m.InitializationVector.Bytes()
tag := m.Tag.Bytes()
cipher, err := buildContentCipher(enc)
if err != nil {
return nil, fmt.Errorf("unsupported content cipher algorithm '%s'", enc)
}
keysize := cipher.KeySize()
var plaintext []byte
for _, recipient := range m.Recipients {
if debug.Enabled {
debug.Printf("Attempting to check if we can decode for recipient (alg = %s)", recipient.Header.Algorithm)
}
if recipient.Header.Algorithm != alg {
continue
}
h2 := NewHeader()
if err := h2.Copy(h); err != nil {
if debug.Enabled {
debug.Printf("failed to copy header: %s", err)
}
continue
}
h2, err := h2.Merge(recipient.Header)
if err != nil {
if debug.Enabled {
debug.Printf("Failed to merge! %s", err)
}
continue
}
k, err := BuildKeyDecrypter(h2.Algorithm, h2, key, keysize)
if err != nil {
if debug.Enabled {
debug.Printf("failed to create key decrypter: %s", err)
}
continue
}
cek, err := k.KeyDecrypt(recipient.EncryptedKey.Bytes())
if err != nil {
if debug.Enabled {
debug.Printf("failed to decrypt key: %s", err)
}
continue
}
plaintext, err = cipher.decrypt(cek, iv, ciphertext, tag, aad)
if err == nil {
break
}
if debug.Enabled {
debug.Printf("DecryptMessage: failed to decrypt using %s: %s", h2.Algorithm, err)
}
// Keep looping because there might be another key with the same algo
}
if plaintext == nil {
return nil, errors.New("failed to find matching recipient to decrypt key")
}
if h.Compression == jwa.Deflate {
output := bytes.Buffer{}
w, _ := flate.NewWriter(&output, 1)
in := plaintext
for len(in) > 0 {
n, err := w.Write(in)
if err != nil {
return nil, err
}
in = in[n:]
}
if err := w.Close(); err != nil {
return nil, err
}
plaintext = output.Bytes()
}
return plaintext, nil
}
func buildContentCipher(alg jwa.ContentEncryptionAlgorithm) (ContentCipher, error) {
switch alg {
case jwa.A128GCM, jwa.A192GCM, jwa.A256GCM, jwa.A128CBC_HS256, jwa.A192CBC_HS384, jwa.A256CBC_HS512:
return NewAesContentCipher(alg)
}
return nil, ErrUnsupportedAlgorithm
}