-
Notifications
You must be signed in to change notification settings - Fork 51
/
jwt.go
227 lines (174 loc) · 6.23 KB
/
jwt.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
package tokens
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"time"
"github.com/aporeto-inc/trireme-lib/controller/pkg/secrets"
"github.com/aporeto-inc/trireme-lib/utils/cache"
"github.com/aporeto-inc/trireme-lib/utils/crypto"
"github.com/dgrijalva/jwt-go"
)
var (
noncePosition = 2
tokenPosition = 2 + NonceLength
)
// JWTClaims captures all the custom clains
type JWTClaims struct {
*ConnectionClaims
jwt.StandardClaims
}
// JWTConfig configures the JWT token generator with the standard parameters. One
// configuration is assigned to each server
type JWTConfig struct {
// ValidityPeriod period of the JWT
ValidityPeriod time.Duration
// Issuer is the server that issues the JWT
Issuer string
// signMethod is the method used to sign the JWT
signMethod jwt.SigningMethod
// secrets is the secrets used for signing and verifying the JWT
secrets secrets.Secrets
// cache test
tokenCache cache.DataStore
}
// NewJWT creates a new JWT token processor
func NewJWT(validity time.Duration, issuer string, s secrets.Secrets) (*JWTConfig, error) {
if len(issuer) > MaxServerName {
return nil, fmt.Errorf("server id should be max %d chars. got %s", MaxServerName, issuer)
}
for i := len(issuer); i < MaxServerName; i++ {
issuer = issuer + " "
}
var signMethod jwt.SigningMethod
if s == nil {
return nil, errors.New("secrets can not be nil")
}
switch s.Type() {
case secrets.PKIType, secrets.PKICompactType:
signMethod = jwt.SigningMethodES256
case secrets.PSKType:
signMethod = jwt.SigningMethodHS256
default:
signMethod = jwt.SigningMethodNone
}
return &JWTConfig{
ValidityPeriod: validity,
Issuer: issuer,
signMethod: signMethod,
secrets: s,
tokenCache: cache.NewCacheWithExpiration("JWTTokenCache", time.Millisecond*500),
}, nil
}
// 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 *JWTConfig) CreateAndSign(isAck bool, claims *ConnectionClaims) (token []byte, nonce []byte, err error) {
// Combine the application claims with the standard claims
allclaims := &JWTClaims{
claims,
jwt.StandardClaims{
ExpiresAt: time.Now().Add(c.ValidityPeriod).Unix(),
Issuer: c.Issuer,
},
}
// Create the token and sign with our key
strtoken, err := jwt.NewWithClaims(c.signMethod, allclaims).SignedString(c.secrets.EncodingKey())
if err != nil {
return []byte{}, []byte{}, err
}
// Copy the certificate if needed. Note that we don't send the certificate
// again for Ack packets to reduce overhead
if !isAck {
nonce, err := crypto.GenerateRandomBytes(NonceLength)
if err != nil {
return []byte{}, []byte{}, err
}
txKey := c.secrets.TransmittedKey()
totalLength := len(strtoken) + len(txKey) + noncePosition + NonceLength + 1
token := make([]byte, totalLength)
// Offset of public key
binary.BigEndian.PutUint16(token[0:noncePosition], uint16(len(strtoken)))
// Attach the nonse
copy(token[noncePosition:], nonce)
// Copy the JWT tokenn
copy(token[tokenPosition:], []byte(strtoken))
token[tokenPosition+len(strtoken)] = []byte("%")[0]
// Copy the public key
if len(txKey) > 0 {
copy(token[tokenPosition+len(strtoken)+1:], txKey)
}
return token, nonce, nil
}
return []byte(strtoken), []byte{}, 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 *JWTConfig) Decode(isAck bool, data []byte, previousCert interface{}) (claims *ConnectionClaims, nonce []byte, publicKey interface{}, err error) {
var ackCert interface{}
token := data
jwtClaims := &JWTClaims{}
nonce = make([]byte, NonceLength)
// Get the token and data from the buffer and validate the certificate
// Ack packets don't have a certificate and it must be provided in the
// Decode function. If certificates are distributed out of band we
// will look in the certPool for the certificate
if !isAck {
// We must have at least enough data to get the length
if len(data) < tokenPosition {
return nil, nil, nil, errors.New("invalid token length")
}
tokenLength := int(binary.BigEndian.Uint16(data[0:noncePosition]))
// Data must be enought to accommodate the token
if len(data) < tokenPosition+tokenLength+1 {
return nil, nil, nil, errors.New("invalid token length")
}
copy(nonce, data[noncePosition:tokenPosition])
token = data[tokenPosition : tokenPosition+tokenLength]
certBytes := data[tokenPosition+tokenLength+1:]
ackCert, err = c.secrets.VerifyPublicKey(certBytes)
if err != nil {
return nil, nil, nil, fmt.Errorf("invalid public key: %s", err)
}
if cachedClaims, cerr := c.tokenCache.Get(string(token)); cerr == nil {
return cachedClaims.(*ConnectionClaims), nonce, ackCert, nil
}
}
// Parse the JWT token with the public key recovered
jwttoken, err := jwt.ParseWithClaims(string(token), jwtClaims, func(token *jwt.Token) (interface{}, error) {
server := token.Claims.(*JWTClaims).Issuer
server = strings.Trim(server, " ")
return c.secrets.DecodingKey(server, ackCert, previousCert)
})
// If error is returned or the token is not valid, reject it
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to parse token: %s", err)
}
if !jwttoken.Valid {
return nil, nil, nil, errors.New("invalid token")
}
c.tokenCache.AddOrUpdate(string(token), jwtClaims.ConnectionClaims)
return jwtClaims.ConnectionClaims, nonce, ackCert, nil
}
// Randomize adds a nonce to an existing token. Returns the nonce
func (c *JWTConfig) Randomize(token []byte) (nonce []byte, err error) {
if len(token) < tokenPosition {
return []byte{}, errors.New("token is too small")
}
nonce, err = crypto.GenerateRandomBytes(NonceLength)
if err != nil {
return []byte{}, err
}
copy(token[noncePosition:], nonce)
return nonce, nil
}
// RetrieveNonce returns the nonce of a token. It copies the value
func (c *JWTConfig) RetrieveNonce(token []byte) ([]byte, error) {
if len(token) < tokenPosition {
return []byte{}, errors.New("invalid token")
}
nonce := make([]byte, NonceLength)
copy(nonce, token[noncePosition:tokenPosition])
return nonce, nil
}