/
binaryjwt.go
586 lines (460 loc) · 18.1 KB
/
binaryjwt.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package tokens
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/binary"
"fmt"
"math/big"
"strings"
"time"
"github.com/ugorji/go/codec"
enforcerconstants "go.aporeto.io/trireme-lib/controller/internal/enforcer/constants"
"go.aporeto.io/trireme-lib/controller/pkg/claimsheader"
"go.aporeto.io/trireme-lib/controller/pkg/pkiverifier"
"go.aporeto.io/trireme-lib/controller/pkg/secrets"
"go.aporeto.io/trireme-lib/utils/cache"
"go.uber.org/zap"
)
// Format of Binary Tokens
// 0 1 2 3 4
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | D |CT|E| Encoding | R (reserved) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Signature Position | nonce |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | token |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Signature |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ... |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// D [0:6] - Datapath version
// CT [6:8] - Compressed tag type
// E [8:9] - Encryption enabled
// C [9:12] - Codec selector
// R [12:32] - Reserved
// L [32:48] - Token Length
// Token bytes (equal to token length)
// Signature bytes
const (
binaryNoncePosition = 6
lengthPosition = 4
headerLength = 4
nonceLength = 16
)
// AckPattern is added in SYN and ACK tokens.
var AckPattern = []byte("PANWIDENTITY")
type sharedSecret struct {
key []byte
tags []string
}
// BinaryJWTConfig configures the JWT token generator with the standard parameters. One
// configuration is assigned to each server
type BinaryJWTConfig struct {
// ValidityPeriod period of the JWT
ValidityPeriod time.Duration
// Issuer is the server that issues the JWT
Issuer string
// cache test
tokenCache cache.DataStore
// sharedKeys is a cache of pre-shared keys.
sharedKeys cache.DataStore
}
// NewBinaryJWT creates a new JWT token processor
func NewBinaryJWT(validity time.Duration, issuer string) (*BinaryJWTConfig, error) {
return &BinaryJWTConfig{
ValidityPeriod: validity,
Issuer: issuer,
tokenCache: cache.NewCacheWithExpiration("JWTTokenCache", validity),
sharedKeys: cache.NewCacheWithExpiration("SharedKeysCache", time.Minute*5),
}, nil
}
// Decode takes as argument the JWT token and the certificate of the issuer.
// First it verifies the certificate with the local CA pool, and the decodes
// the JWT if the certificate is trusted
func (c *BinaryJWTConfig) Decode(isAck bool, data []byte, previousCert interface{}, secrets secrets.Secrets) (claims *ConnectionClaims, nonce []byte, publicKey interface{}, controller *pkiverifier.PKIControllerInfo, err error) {
if isAck {
return c.decodeAck(data)
}
return c.decodeSyn(data, secrets)
}
// CreateAndSign creates a new token, attaches an ephemeral key pair and signs with the issuer
// key. It also randomizes the source nonce of the token. It returns back the token and the private key.
func (c *BinaryJWTConfig) CreateAndSign(isAck bool, claims *ConnectionClaims, nonce []byte, header *claimsheader.ClaimsHeader, secrets secrets.Secrets) (token []byte, err error) {
// Set the appropriate claims header
header.SetCompressionType(claimsheader.CompressionTypeV1)
header.SetDatapathVersion(claimsheader.DatapathVersion1)
if isAck {
return c.createAckToken(claims, header)
}
return c.createSynToken(claims, nonce, header, secrets)
}
// Randomize adds a nonce to an existing token. Returns the nonce
func (c *BinaryJWTConfig) Randomize(token []byte, nonce []byte) (err error) {
if len(token) < 6+NonceLength {
return logError(ErrTokenTooSmall, err.Error())
}
copy(token[6:], nonce)
return nil
}
func (c *BinaryJWTConfig) createSynToken(claims *ConnectionClaims, nonce []byte, header *claimsheader.ClaimsHeader, secrets secrets.Secrets) (token []byte, err error) {
// Combine the application claims with the standard claims.
// In all cases for Syn/SynAck packets we also transmit our
// public key.
allclaims := ConvertToBinaryClaims(claims, c.ValidityPeriod)
allclaims.SignerKey = secrets.TransmittedKey()
// This is the hack of backward compatibility that has to be
// removed.
pruneTags(allclaims)
// Encode the claims in a buffer.
buf, err := encode(allclaims)
if err != nil {
return nil, logError(ErrTokenEncodeFailed, err.Error())
}
var sig []byte
if len(claims.RemoteID) == 0 {
buf = append(buf, AckPattern...)
sig, err = c.sign(buf, secrets.EncodingKey().(*ecdsa.PrivateKey))
} else {
sig, err = c.signWithSharedKey(buf, claims.RemoteID)
}
if err != nil {
return nil, err
}
// Pack and return the token.
return packToken(header.ToBytes(), nonce, buf, sig), nil
}
func (c *BinaryJWTConfig) createAckToken(claims *ConnectionClaims, header *claimsheader.ClaimsHeader) (token []byte, err error) {
// Combine the application claims with the standard claims
allclaims := ConvertToBinaryClaims(claims, c.ValidityPeriod)
// Encode the claims in a buffer.
buf, err := encode(allclaims)
if err != nil {
return nil, logError(ErrTokenEncodeFailed, err.Error())
}
buf = append(buf, AckPattern...)
// Sign the buffer with the pre-shared key.
sig, err := c.signWithSharedKey(buf, claims.RemoteID)
if err != nil {
return nil, err
}
// Pack and return the token.
return packToken(header.ToBytes(), nil, buf, sig), nil
}
func (c *BinaryJWTConfig) decodeSyn(data []byte, secrets secrets.Secrets) (claims *ConnectionClaims, nonce []byte, publicKey interface{}, controller *pkiverifier.PKIControllerInfo, err error) {
// Unpack the token first.
header, nonce, token, sig, err := unpackToken(false, data)
if err != nil {
return nil, nil, nil, nil, err
}
// Validate the header version.
if err := c.verifyClaimsHeader(claimsheader.HeaderBytes(header).ToClaimsHeader()); err != nil {
return nil, nil, nil, nil, err
}
// Decode the claims to a data structure.
binaryClaims, err := decode(token)
if err != nil {
return nil, nil, nil, nil, err
}
// Derive the transmitter public key and associated claims. This will also
// validate that the transmitter key is valid or provide it from a cache.
// Once it succeeds we know that the public key that was provide is correct.
publicKey, publicKeyClaims, expTime, controller, err := secrets.KeyAndClaims(binaryClaims.SignerKey)
if err != nil || publicKey == nil {
return nil, nil, nil, nil, ErrPublicKeyFailed
}
// Since we know that the signature is valid, we check if the token is already in
// the cache and accept it. We do that after the verification, in case the
// public key has expired and we still have it in the cache.
if cachedClaims, cerr := c.tokenCache.Get(string(token)); cerr == nil {
return cachedClaims.(*ConnectionClaims), nonce, publicKey, controller, nil
}
// We haven't seen this token again, so we will validate it with the
// public key and cache it for future calls.
// First we check if we know RMT attribute is set. This will indicate
// that this is SynAck packet that carries the remote nonce, and we
// can use the shared key approach. In the protocol we mandate
// that RMT in the SynAck is populated since it carries the nonce
// of the remote.
if len(binaryClaims.RMT) > 0 {
binaryClaims.RMT = nil
key, err := c.deriveSharedKey(binaryClaims.ID, publicKey, publicKeyClaims, expTime, secrets.EncodingKey())
if err != nil {
return nil, nil, nil, nil, err
}
if err := c.verifyWithSharedKey(token, key, sig); err != nil {
// We need to be cautious here. There is a chance that the remote public key
// has changed. In this case, we will re-calculate the shared key and try
// again. We don't have the option of doing that for Ack packets, but at least
// we can do it here.
key, err = c.newSharedKey(binaryClaims.ID, publicKey, publicKeyClaims, expTime, secrets.EncodingKey())
if err != nil {
return nil, nil, nil, nil, err
}
if err = c.verifyWithSharedKey(token, key, sig); err != nil {
return nil, nil, nil, nil, err
}
}
} else {
// If the token is not in the cache, we validate the token with the
// provided and validated public key. We will then add it in the
// cache for future reference.
if err := c.verify(token, sig, publicKey.(*ecdsa.PublicKey)); err != nil {
return nil, nil, nil, nil, err
}
// We create a new symetric key if we don't already have one.
_, err := c.newSharedKey(binaryClaims.ID, publicKey, publicKeyClaims, expTime, secrets.EncodingKey())
if err != nil {
return nil, nil, nil, nil, err
}
}
// Uncommpress the tags and add the public key claims to the tags that
// we return.
uncompressTags(binaryClaims, publicKeyClaims)
connClaims := ConvertToJWTClaims(binaryClaims, header).ConnectionClaims
// Cache the token and the token string and the claims and return the
// connection claims.
c.tokenCache.AddOrUpdate(string(token), connClaims)
return connClaims, nonce, publicKey, controller, nil
}
func (c *BinaryJWTConfig) decodeAck(data []byte) (claims *ConnectionClaims, nonce []byte, publicKey interface{}, controller *pkiverifier.PKIControllerInfo, err error) {
// Unpack the token first.
header, nonce, token, sig, err := unpackToken(true, data)
if err != nil {
return nil, nil, nil, nil, err
}
// Validate the header.
if err := c.verifyClaimsHeader(claimsheader.HeaderBytes(header).ToClaimsHeader()); err != nil {
return nil, nil, nil, nil, err
}
// Decode the claims to a data structure.
binaryClaims, err := decode(token)
if err != nil {
return nil, nil, nil, nil, err
}
// Find the shared key. This must already be in the cache and pre-calculated,
// since we have seen the syn and syn ack packets.
k, err := c.sharedKeys.Get(binaryClaims.ID)
if err != nil {
return nil, nil, nil, nil, ErrSharedSecretMissing
}
key := k.(*sharedSecret).key
// Calculate the signature on the token and compare it with the incoming
// signature. Since this is simple symetric hashing this is simple.
if err := c.verifyWithSharedKey(token, key, sig); err != nil {
return nil, nil, nil, nil, err
}
return ConvertToJWTClaims(binaryClaims, header).ConnectionClaims, nonce, nil, nil, nil
}
func (c *BinaryJWTConfig) verifyClaimsHeader(h *claimsheader.ClaimsHeader) error {
if h.CompressionType() != claimsheader.CompressionTypeV1 {
return ErrCompressedTagMismatch
}
if h.DatapathVersion() != claimsheader.DatapathVersion1 {
return ErrDatapathVersionMismatch
}
return nil
}
func (c *BinaryJWTConfig) sign(buf []byte, key *ecdsa.PrivateKey) ([]byte, error) {
// Create the hash and use this for the signature. This is a SHA256 hash
// of the token.
h, err := hash(buf, nil)
if err != nil {
return nil, logError(ErrTokenHashFailed, err.Error())
}
// Sign the hash with the private key using the ECDSA algorithm
// and properly format the resulting signature.
r, s, err := ecdsa.Sign(rand.Reader, key, h)
if err != nil {
return nil, logError(ErrTokenSignFailed, err.Error())
}
curveBits := key.Curve.Params().BitSize
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes++
}
// We serialize the outpus (r and s) into big-endian byte arrays and pad
// them with zeros on the left to make sure the sizes work out. Both arrays
// must be keyBytes long, and the output must be 2*keyBytes long.
tokenBytes := make([]byte, 2*keyBytes)
rBytes := r.Bytes()
copy(tokenBytes[keyBytes-len(rBytes):], rBytes)
sBytes := s.Bytes()
copy(tokenBytes[2*keyBytes-len(sBytes):], sBytes)
return tokenBytes, nil
}
func (c *BinaryJWTConfig) verify(buf []byte, sig []byte, key *ecdsa.PublicKey) error {
if len(sig) != 64 {
return ErrInvalidSignature
}
r := big.NewInt(0).SetBytes(sig[:32])
s := big.NewInt(0).SetBytes(sig[32:])
// Create the hash and use this for the signature. This is a SHA256 hash
// of the token.
h, err := hash(buf, nil)
if err != nil {
return logError(ErrTokenHashFailed, err.Error())
}
if verifyStatus := ecdsa.Verify(key, h, r, s); verifyStatus {
return nil
}
return ErrInvalidSignature
}
func (c *BinaryJWTConfig) signWithSharedKey(buf []byte, id string) ([]byte, error) {
s, err := c.sharedKeys.Get(id)
if err != nil {
return nil, ErrSharedSecretMissing
}
sk, ok := s.(*sharedSecret)
if !ok {
return nil, ErrInvalidSecret
}
b, err := hash(buf, sk.key)
if err != nil {
return nil, logError(ErrTokenHashFailed, err.Error())
}
return b, nil
}
func (c *BinaryJWTConfig) verifyWithSharedKey(buf []byte, key []byte, sig []byte) error {
ps, err := hash(buf, key)
if err != nil {
return logError(ErrTokenHashFailed, err.Error())
}
if !bytes.Equal(ps, sig) {
return logError(ErrSignatureMismatch, fmt.Sprintf("unable to verify token with shared secret: they don't match %d %d ", len(ps), len(sig)))
}
return nil
}
func (c *BinaryJWTConfig) deriveSharedKey(id string, publicKey interface{}, publicKeyClaims []string, expTime time.Time, privateKey interface{}) ([]byte, error) {
// We try to find the remote in the cache
k, err := c.sharedKeys.Get(id)
if err != nil {
// We don't have it in the cache. Let's create a new shared key.
return c.newSharedKey(id, publicKey, publicKeyClaims, expTime, privateKey)
}
// Key is already found in the cache.
return k.(*sharedSecret).key, nil
}
func (c *BinaryJWTConfig) newSharedKey(id string, publicKey interface{}, publicKeyClaims []string, expTime time.Time, privateKey interface{}) ([]byte, error) {
key, err := symmetricKey(privateKey, publicKey)
if err != nil {
return nil, logError(ErrSharedKeyHashFailed, err.Error())
}
// Add it in the cache
c.sharedKeys.AddOrUpdate(id, &sharedSecret{
key: key,
tags: publicKeyClaims,
})
// if the token expires before our default validity, update the timer
// so that we expire it no longer than its validity.
if time.Now().Add(c.ValidityPeriod).After(expTime) {
if err := c.sharedKeys.SetTimeOut(id, time.Until(expTime)); err != nil {
zap.L().Warn("Failed to update cache validity for token", zap.Error(err))
}
}
return key, nil
}
func encode(c *BinaryJWTClaims) ([]byte, error) {
// Encode and sign the token
buf := make([]byte, 0, 1400)
var h codec.Handle = new(codec.CborHandle)
enc := codec.NewEncoderBytes(&buf, h)
if err := enc.Encode(c); err != nil {
return nil, fmt.Errorf("unable to encode message: %s", err)
}
return buf, nil
}
func decode(buf []byte) (*BinaryJWTClaims, error) {
// Decode the token into a structure.
binaryClaims := &BinaryJWTClaims{}
var h codec.Handle = new(codec.CborHandle)
dec := codec.NewDecoderBytes(buf, h)
if err := dec.Decode(binaryClaims); err != nil {
return nil, logError(ErrTokenDecodeFailed, err.Error())
}
if binaryClaims.ExpiresAt < time.Now().Unix() {
return nil, logError(ErrTokenExpired, fmt.Sprintf("token is expired since: %s", time.Unix(binaryClaims.ExpiresAt, 0)))
}
return binaryClaims, nil
}
func packToken(header, nonce, token, sig []byte) []byte {
binaryTokenPosition := binaryNoncePosition + len(nonce)
sigPosition := binaryTokenPosition + len(token)
// Token is the concatenation of
// [Position of Signature] [nonce] [token] [signature]
data := make([]byte, sigPosition+len(sig))
// Header bytes
copy(data[0:headerLength], header)
// Length of token
binary.BigEndian.PutUint16(data[lengthPosition:], uint16(sigPosition))
// nonce not required for ack packets
if len(nonce) > 0 {
copy(data[binaryNoncePosition:], nonce)
}
// token
copy(data[binaryTokenPosition:], token)
// signature
copy(data[sigPosition:], sig)
return data
}
// unpackToken returns nonce, token, signature or error if something fails
func unpackToken(isAck bool, data []byte) ([]byte, []byte, []byte, []byte, error) {
// We must have enough data to read the length.
if len(data) < binaryNoncePosition {
return nil, nil, nil, nil, ErrInvalidTokenLength
}
header := data[:lengthPosition]
sigPosition := int(binary.BigEndian.Uint16(data[lengthPosition : lengthPosition+2]))
// The token must be long enough to have at least 1 byte of signature.
if len(data) < sigPosition+1 || sigPosition == 0 {
return nil, nil, nil, nil, ErrMissingSignature
}
var nonce []byte
if !isAck {
nonce = make([]byte, 16)
copy(nonce, data[binaryNoncePosition:binaryNoncePosition+nonceLength])
}
// Only if nonce is found do we need to advance. So, use the
// actual length of the nonce and not just a constant here.
token := data[binaryNoncePosition+len(nonce) : sigPosition]
sig := data[sigPosition:]
return header, nonce, token, sig, nil
}
func hash(buf []byte, key []byte) ([]byte, error) {
hasher := crypto.SHA256.New()
if _, err := hasher.Write(buf); err != nil {
return nil, fmt.Errorf("unable to hash data structure: %s", err)
}
return hasher.Sum(key), nil
}
// symmetricKey returns a symmetric key for encryption
func symmetricKey(privateKey interface{}, remotePublic interface{}) ([]byte, error) {
c := elliptic.P256()
x, _ := c.ScalarMult(remotePublic.(*ecdsa.PublicKey).X, remotePublic.(*ecdsa.PublicKey).Y, privateKey.(*ecdsa.PrivateKey).D.Bytes())
return hash(x.Bytes(), nil)
}
func pruneTags(claims *BinaryJWTClaims) {
// Handling compression here. If we need to use compression, we will copy
// the claims to the C claim and remove all the other fields.
for _, t := range claims.T {
if strings.HasPrefix(t, enforcerconstants.TransmitterLabel) {
claims.ID = t[len(enforcerconstants.TransmitterLabel)+1:]
break
}
}
claims.T = nil
}
func uncompressTags(binaryClaims *BinaryJWTClaims, publicKeyClaims []string) {
binaryClaims.T = append(binaryClaims.CT, enforcerconstants.TransmitterLabel+"="+binaryClaims.ID)
if len(publicKeyClaims) > 0 {
binaryClaims.T = append(binaryClaims.T, publicKeyClaims...)
}
}