-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
379 lines (338 loc) · 11.5 KB
/
main.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
package main
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/spf13/cobra"
jose "gopkg.in/go-jose/go-jose.v2"
)
const (
TOKEN_URI_PATH = "/token"
OIDC_URI_PATH = "/.well-known/openid-configuration"
JWKS_URI_PATH = "/.well-known/jwks.json"
PUBLIC_KEY_FILENAME = "public-key.pem"
)
var fireflyClaimMap = map[string]string{
"configuration": "venafi-firefly.configuration",
"allowedPolicies": "venafi-firefly.allowedPolicies",
"allowAllPolicies": "venafi-firefly.allowAllPolicies",
}
func claimsSupported() []string {
return []string{
"iss",
"sub",
"aud",
"exp",
"iat",
fireflyClaimMap["configuration"],
fireflyClaimMap["allowAllPolicies"],
fireflyClaimMap["allowedPolicies"],
}
}
type Endpoint struct {
Host string
Port int
UseTLS bool
KeyCert *[]tls.Certificate
BaseURL string
}
type OidcDiscovery struct {
Issuer string `json:"issuer"`
TokenEndpoint string `json:"token_endpoint"`
JwksURI string `json:"jwks_uri"`
ClaimsSupported []string `json:"claims_supported"`
}
type OAuthToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
}
func init() {
if value, ok := os.LookupEnv("CLAIM_CONFIGURATION"); ok {
fireflyClaimMap["configuration"] = value
}
if value, ok := os.LookupEnv("CLAIM_ALLOW_ALL_POLICIES"); ok {
fireflyClaimMap["allowAllPolicies"] = value
}
if value, ok := os.LookupEnv("CLAIM_ALLOWED_POLICIES"); ok {
fireflyClaimMap["allowedPolicies"] = value
}
}
func main() {
var (
endpoint = Endpoint{}
signingKeyType string
audience string
fireflyClaims FireflyClaims
validTime string
)
var rootCmd = &cobra.Command{
Use: "jwt-this",
Version: "1.2.5",
Long: "JSON Web Token (JWT) generator & JSON Web Key Set (JWKS) server for evaluating Venafi Firefly",
Args: cobra.NoArgs,
CompletionOptions: cobra.CompletionOptions{HiddenDefaultCmd: true, DisableDefaultCmd: true},
Run: func(cmd *cobra.Command, args []string) {
validity, err := time.ParseDuration(validTime)
if err != nil {
log.Fatalf("error: could not parse validity: %v\n", err)
}
err = checkPortAvailablity(endpoint.Port)
if err != nil {
log.Fatalf("error: port not available: %v\n", err)
}
signingKey, err := generateKeyPair(signingKeyType)
if err != nil {
log.Fatalf("error: could not generate key pair: %v\n", err)
}
tokenConfig := TokenConfig{
Audience: audience,
FireflyClaims: &fireflyClaims,
Validity: validity,
}
cred, err := generateToken(signingKey, endpoint.httpURL(), tokenConfig, nil)
if err != nil {
log.Fatalf("error: could not generate token: %v\n", err)
}
os.WriteFile(".token", []byte(cred.Token), 0644)
fmt.Printf("Token\n=====\n%s\n\n", cred.Token)
fmt.Printf("Header\n======\n%s\n\n", cred.HeaderJSON)
fmt.Printf("Claims\n======\n%s\n\n", cred.ClaimsJSON)
// verify the signature
_, err = jwt.Parse(cred.Token, func(token *jwt.Token) (interface{}, error) {
return signingKey.PublicKey, nil
})
if err != nil {
log.Fatalf("error: could not verify token signature: %v\n", err)
}
if createTLSCertificate(&endpoint, signingKey.PublicKey, signingKey.PrivateKey) != nil {
log.Fatalf("error: could not make self-signed TLS certificate: %v\n", err)
}
os.WriteFile(".trust", endpoint.tlsCertificatePEM(), 0644)
fmt.Printf("JWKS URL: %s\n\n", endpoint.httpURL(JWKS_URI_PATH))
fmt.Printf("OIDC Discovery Base URL: %s\n\n", endpoint.httpURL())
err = startJwksHttpServer(&endpoint, signingKey, tokenConfig)
if err != nil {
log.Fatalf("error: could not start JWKS HTTP server: %v\n", err)
}
},
}
rootCmd.Flags().StringVarP(&signingKeyType, "key-type", "t", "ecdsa", "Signing key type, ECDSA or RSA.")
rootCmd.Flags().StringVarP(&audience, "audience", "a", "", "Include 'aud' claim in the JWT with the specified value.")
rootCmd.Flags().StringVar(&fireflyClaims.Configuration, "config-name", "", "Name of the Firefly Configuration for which the token is valid.")
rootCmd.Flags().StringSliceVar(&fireflyClaims.AllowedPolicies, "policy-names", []string{}, "Comma separated list of Firefly Policy Names for which the token is valid.")
rootCmd.Flags().StringVar(&endpoint.Host, "host", getPrimaryNetAddr(), "Host to use in claim URIs.")
rootCmd.Flags().StringVarP(&endpoint.BaseURL, "url", "u", "", "Ignore --host, --port, and protocol derived from --tls and use this URL instead for claim URIs.")
rootCmd.Flags().IntVarP(&endpoint.Port, "port", "p", 8000, "TCP port on which JWKS HTTP server will listen.")
rootCmd.Flags().BoolVar(&endpoint.UseTLS, "tls", false, "Generate a self-signed certificate and use HTTPS instead of HTTP for URLs.")
rootCmd.Flags().StringVarP(&validTime, "validity", "v", "24h", "Duration for which the generated token will be valid.")
rootCmd.Execute()
}
func startJwksHttpServer(e *Endpoint, k *SigningKeyPair, cfg TokenConfig) error {
// make JWKS available at JWKS_URI_PATH
http.HandleFunc(JWKS_URI_PATH, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method Not Allowed")
return
}
w.Header().Set("Cache-Control", "No-Store")
w.Header().Set("Content-Type", "application/json")
var alg string
switch k.PublicKey.(type) {
case *ecdsa.PublicKey:
alg = "ES256"
case *rsa.PublicKey:
alg = "RS256"
}
set := jose.JSONWebKeySet{
Keys: []jose.JSONWebKey{
{
Key: k.PublicKey,
KeyID: jwkThumbprint(k.PublicKey),
Use: "sig",
Algorithm: alg,
},
},
}
jwks, _ := json.MarshalIndent(set, "", " ")
fmt.Fprintf(w, "%s", string(jwks))
})
// make JWKS URL known through OIDC Discovery
http.HandleFunc(OIDC_URI_PATH, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method Not Allowed")
return
}
w.Header().Set("Cache-Control", "No-Store")
w.Header().Set("Content-Type", "application/json")
data := OidcDiscovery{
Issuer: e.httpURL(),
TokenEndpoint: e.httpURL(TOKEN_URI_PATH),
JwksURI: e.httpURL(JWKS_URI_PATH),
ClaimsSupported: claimsSupported(),
}
oidc, _ := json.MarshalIndent(data, "", " ")
fmt.Fprintf(w, "%s", string(oidc))
})
http.HandleFunc(TOKEN_URI_PATH, func(w http.ResponseWriter, r *http.Request) {
var customClaims CustomClaims
if r.Method != http.MethodGet && r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method Not Allowed")
return
}
err := r.ParseForm()
if err != nil {
log.Fatalf("error: could not parse form variables: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%v", err)
return
}
if len(r.PostForm) > 0 {
customClaims = CustomClaims{}
for k, v := range r.PostForm {
if len(v) > 1 {
customClaims[k] = v
} else if v[0] != "" { // skip valueless claims
customClaims[k] = v[0]
}
}
}
cred, err := generateToken(k, e.httpURL(), cfg, &customClaims)
if err != nil {
log.Fatalf("error: could not generate token: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%v", err)
return
}
// for GET /token?jwt.io redirect to jwt.io instead of OAuth 2.0 response
if _, ok := r.Form["jwt.io"]; ok && r.Method == http.MethodGet {
params := url.Values{
"token": []string{cred.Token},
"publicKey": []string{strings.ReplaceAll(k.PublicKeyPEM, "\n", "")},
}
w.Header().Set("Location", fmt.Sprintf("https://jwt.io?%s", params.Encode()))
w.WriteHeader(http.StatusFound)
return
}
w.Header().Set("Cache-Control", "No-Store")
w.Header().Set("Content-Type", "application/json")
data := OAuthToken{
AccessToken: cred.Token,
ExpiresIn: int(cfg.Validity.Seconds()),
TokenType: "Bearer",
}
token, _ := json.MarshalIndent(data, "", " ")
fmt.Fprintf(w, "%s", string(token))
})
// make signing public key available to download
http.HandleFunc("/"+PUBLIC_KEY_FILENAME, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method Not Allowed")
return
}
w.Header().Set("Cache-Control", "No-Store")
w.Header().Set("Content-Type", "application/x-pem-file")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, PUBLIC_KEY_FILENAME))
fmt.Fprintf(w, "%s", k.PublicKeyPEM)
})
// quick links at base URL
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method Not Allowed")
return
}
w.Header().Set("Cache-Control", "No-Store")
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, homePageHTML(k.Type))
})
if e.KeyCert != nil {
s := &http.Server{
Addr: fmt.Sprintf(":%d", e.Port),
ErrorLog: log.New(io.Discard, "", log.LstdFlags),
Handler: nil,
TLSConfig: &tls.Config{
Certificates: *e.KeyCert,
},
}
return s.ListenAndServeTLS("", "")
}
return http.ListenAndServe(fmt.Sprintf(":%d", e.Port), nil)
}
func checkPortAvailablity(port int) error {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err == nil {
listener.Close()
}
return err
}
func getPrimaryNetAddr() string {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return "127.0.0.1" // localhost
}
defer conn.Close()
return conn.LocalAddr().(*net.UDPAddr).IP.String()
}
func homePageHTML(keyType string) string {
return strings.TrimSpace(fmt.Sprintf(`
<html>
<head>
<title>jwt-this</title>
<style>
. { font-family: arial }
a { text-decoration: none }
a:hover { text-decoration: underline }
</style>
</head>
<body>
<h1>jwt-this</h1>
<ul>
<li><a href="%s">JSON Web Key Set (JWKS)</a></li>
<li><a href="%s">OpenID Connect (OIDC) Configuration</a></li>
<li><a href="/token">New token via OAuth 2.0 response</a></li>
<li><a href="/token?jwt.io">New token via JWT.io presentation</a></li>
<li><a href="/%s">Download public key [%s]</a></li>
</ul>
<a href="https://github.com/tr1ck3r/jwt-this#readme">README</a> |
<a href="https://github.com/tr1ck3r/jwt-this/releases/latest">Latest Release</a> |
<a href="https://hub.docker.com/r/tr1ck3r/jwt-this">Container Image</a>
</body>
</html>
`, JWKS_URI_PATH, OIDC_URI_PATH, PUBLIC_KEY_FILENAME, strings.Replace(keyType, "_", " ", 1)))
}
func (e *Endpoint) httpURL(path ...string) string {
if _, err := url.ParseRequestURI(e.BaseURL); err == nil {
return fmt.Sprintf("%s%s", e.BaseURL, strings.Join(path, "/"))
}
protocol := "http"
if e.UseTLS {
protocol = "https"
}
return fmt.Sprintf("%s://%s:%d%s", protocol, e.Host, e.Port, strings.Join(path, "/"))
}
func (e *Endpoint) tlsCertificatePEM() []byte {
if e.KeyCert != nil {
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: (*e.KeyCert)[0].Certificate[0],
})
}
return nil
}