-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
468 lines (380 loc) · 12.6 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
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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
//"go/token"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"strings"
"time"
"github.com/golang/gddo/httputil/header"
"github.com/google/uuid"
"github.com/mactroll/nebula-config/badgermgr"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
"gopkg.in/yaml.v2"
)
type ConfigFile struct {
AuthConfig struct {
DiscoveryURL string `yaml:"discoveryurl`
ClientID string `yaml:"clientid"`
ReidrectURI string `yaml:"redirecturi"`
CAURL string `yaml:"caurl"`
} `yaml:"auth"`
CAConfig struct {
CAKeyFile string `yaml:"cakeyfile`
CACertFile string `yaml:"cacertfile`
JWKSURL string `yaml:"jwksurl"`
} `yaml:"ca"`
DBConfig struct {
DBPath string `yaml:"path"`
} `yaml:"db"`
ClientConfig struct {
StartingIP string `yaml:"startingip"`
} `yaml:"clients"`
}
type IssueCertRequest struct {
Token string
PubKey string
}
type CustomClaims struct {
*jwt.Claims
}
var debugMode bool
// NewConfig returns a new decoded Config struct
func NewConfig(configPath string) (*ConfigFile, error) {
// Create config structure
config := &ConfigFile{}
// Open config file
file, err := os.Open(configPath)
if err != nil {
return nil, err
}
defer file.Close()
// Init new YAML decode
d := yaml.NewDecoder(file)
// Start YAML decoding from file
if err := d.Decode(&config); err != nil {
return nil, err
}
return config, nil
}
// ValidateConfigPath just makes sure, that the path provided is a file,
// that can be read
func ValidateConfigPath(path string) error {
s, err := os.Stat(path)
if err != nil {
return err
}
if s.IsDir() {
return fmt.Errorf("'%s' is a directory, not a normal file", path)
}
return nil
}
// ParseFlags will create and parse the CLI flags
// and return the path to be used elsewhere
func ParseFlags() (string, error) {
// String that contains the configured configuration path
var configPath string
// Set up a CLI flag called "-config" to allow users
// to supply the configuration file
flag.StringVar(&configPath, "config", "./config.yml", "path to config file")
flag.BoolVar(&debugMode, "debug", false, "Enable debug mode")
// Actually parse the flags
flag.Parse()
// Validate the path first
if err := ValidateConfigPath(configPath); err != nil {
return "", err
}
// Return the configuration path
return configPath, nil
}
// Handle the JSON POST
func issueCertCreate(w http.ResponseWriter, r *http.Request, config ConfigFile) {
if r.Header.Get("Content-Type") != "" {
value, _ := header.ParseValueAndParams(r.Header, "Content-Type")
if value != "application/json" {
msg := "Content-Type header is not application/json"
http.Error(w, msg, http.StatusUnsupportedMediaType)
return
}
}
// Use http.MaxBytesReader to enforce a maximum read of 1MB from the
// response body. A request body larger than that will now result in
// Decode() returning a "http: request body too large" error.
r.Body = http.MaxBytesReader(w, r.Body, 1048576)
// Setup the decoder and call the DisallowUnknownFields() method on it.
// This will cause Decode() to return a "json: unknown field ..." error
// if it encounters any extra unexpected fields in the JSON. Strictly
// speaking, it returns an error for "keys which do not match any
// non-ignored, exported fields in the destination".
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var certRequest IssueCertRequest
err := dec.Decode(&certRequest)
if err != nil {
var syntaxError *json.SyntaxError
var unmarshalTypeError *json.UnmarshalTypeError
switch {
// Catch any syntax errors in the JSON and send an error message
// which interpolates the location of the problem to make it
// easier for the client to fix.
case errors.As(err, &syntaxError):
msg := fmt.Sprintf("Request body contains badly-formed JSON (at position %d)", syntaxError.Offset)
http.Error(w, msg, http.StatusBadRequest)
// In some circumstances Decode() may also return an
// io.ErrUnexpectedEOF error for syntax errors in the JSON. There
// is an open issue regarding this at
// https://github.com/golang/go/issues/25956.
case errors.Is(err, io.ErrUnexpectedEOF):
msg := fmt.Sprintf("Request body contains badly-formed JSON")
http.Error(w, msg, http.StatusBadRequest)
// Catch any type errors, like trying to assign a string in the
// JSON request body to a int field in our Person struct. We can
// interpolate the relevant field name and position into the error
// message to make it easier for the client to fix.
case errors.As(err, &unmarshalTypeError):
msg := fmt.Sprintf("Request body contains an invalid value for the %q field (at position %d)", unmarshalTypeError.Field, unmarshalTypeError.Offset)
http.Error(w, msg, http.StatusBadRequest)
// Catch the error caused by extra unexpected fields in the request
// body. We extract the field name from the error message and
// interpolate it in our custom error message. There is an open
// issue at https://github.com/golang/go/issues/29035 regarding
// turning this into a sentinel error.
case strings.HasPrefix(err.Error(), "json: unknown field "):
fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
msg := fmt.Sprintf("Request body contains unknown field %s", fieldName)
http.Error(w, msg, http.StatusBadRequest)
// An io.EOF error is returned by Decode() if the request body is
// empty.
case errors.Is(err, io.EOF):
msg := "Request body must not be empty"
http.Error(w, msg, http.StatusBadRequest)
// Catch the error caused by the request body being too large. Again
// there is an open issue regarding turning this into a sentinel
// error at https://github.com/golang/go/issues/30715.
case err.Error() == "http: request body too large":
msg := "Request body must not be larger than 1MB"
http.Error(w, msg, http.StatusRequestEntityTooLarge)
// Otherwise default to logging the error and sending a 500 Internal
// Server Error response.
default:
log.Println(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return
}
tokenerr := verifyToken(certRequest.Token, config)
if !tokenerr && !debugMode {
log.Println(tokenerr)
return
}
formattedKey := "-----BEGIN NEBULA X25519 PUBLIC KEY-----\n" + certRequest.PubKey + "\n-----END NEBULA X25519 PUBLIC KEY-----\n"
log.Println(certRequest.PubKey)
certificate := signPubKey(formattedKey, config, certRequest.Token)
fmt.Fprintf(w, "%s\n", certificate)
}
// Get JWKS for validating tokens
func fetchJwks(jwksURL string) (*jose.JSONWebKeySet, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", jwksURL, nil)
if err != nil {
return nil, fmt.Errorf("could not create jwks request: %w", err)
}
res, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("could not fetch jwks: %w", err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, fmt.Errorf("received non-200 response code")
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("could not read response body: %w", err)
}
jwks := jose.JSONWebKeySet{}
err = json.Unmarshal(body, &jwks)
if err != nil {
return nil, fmt.Errorf("could not unmarshal jwks into struct: %w", err)
}
return &jwks, nil
}
func verifyToken(bearerToken string, config ConfigFile) bool {
// Parse bearer token from request
token, err := jwt.ParseSigned(bearerToken)
if err != nil {
log.Println("could not parse Bearer token: %w", err)
return false
}
// Get jwks
jsonWebKeySet, err := fetchJwks(config.CAConfig.JWKSURL)
if err != nil {
log.Println("could not load JWKS: %w", err)
return false
}
out := make(map[string]interface{})
if err := token.Claims(jsonWebKeySet, &out); err != nil {
panic(err)
return false
}
// Get claims out of token (validate signature while doing that)
claims := CustomClaims{}
err = token.Claims(jsonWebKeySet, &claims)
if err != nil {
log.Println("could not retrieve claims: %w", err)
return false
}
// Validate claims (issuer, expiresAt, etc.)
err = claims.Validate(jwt.Expected{})
if err != nil {
log.Println("could not validate claims: %w", err)
return false
}
if !claims.Audience.Contains(config.AuthConfig.ClientID) {
log.Println("Wrong audience for token") //fmt.Errorf("Wrong audience for token")
return false
}
if claims.Expiry.Time().Before(time.Now()) {
log.Println("Token has expired") //fmt.Errorf("Token has expired")
return false
}
if claims.IssuedAt.Time().After(time.Now()) {
log.Println("Token hasn't been issued yet")
return false
}
log.Println("ID Token is valid!")
return true
}
// make a temp directory, pass in the pubkey, sign in, get the cert back
func signPubKey(pubKey string, config ConfigFile, token string) string {
tempDir, err := ioutil.TempDir("", "nebula-temp*")
if err != nil {
log.Fatal(err)
return ""
}
defer os.RemoveAll(tempDir)
pubKeyFile, err := ioutil.TempFile(tempDir, "pubkey*")
if err != nil {
log.Fatal(err)
return ""
}
pubKeyFile.Write([]byte(pubKey))
log.Println(pubKeyFile.Name())
ip := badgermgr.GetIPAddress()
log.Printf(ip)
name := uuid.New().String()
cmd := exec.Command("/usr/local/bin/nebula-cert", "sign", "-ca-crt", config.CAConfig.CACertFile, "-ca-key", config.CAConfig.CAKeyFile, "-in-pub", pubKeyFile.Name(), "-name", name, "-ip", ip+"/16", "-out-crt", tempDir+"/certificate")
if debugMode {
log.Println(cmd.Args)
}
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
dat, err := os.ReadFile(tempDir + "/certificate")
if err == nil {
newrec := badgermgr.CertRecord{PubKey: pubKey, IPAddr: ip, Token: token}
err = badgermgr.WriteCertRecord(name, newrec)
if err != nil {
log.Println("Error writing record into badger")
}
return string(dat)
}
return ""
}
// NewRouter generates the router used in the HTTP Server
func NewRouter(config ConfigFile) *http.ServeMux {
// Create router and define routes and return that router
router := http.NewServeMux()
// this just lets us know things are alive
router.HandleFunc("/welcome", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
})
// this writes out the nebula configuration
router.HandleFunc("/.well-known/nebula-configuration", func(w http.ResponseWriter, r *http.Request) {
jsonReturn, err := json.Marshal(config.AuthConfig)
if err == nil {
fmt.Fprintf(w, "%s\n", jsonReturn)
}
})
// handle a request for a signed certificate using an id token
router.HandleFunc("/issuecert", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
fmt.Fprintf(w, "nothing to see here")
case "POST":
issueCertCreate(w, r, config)
}
})
return router
}
func (config ConfigFile) run() {
// Set up a channel to listen to for interrupt signals
var runChan = make(chan os.Signal, 1)
// Define server options
server := &http.Server{
Addr: "127.0.0.1:8000",
Handler: NewRouter(config),
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Handle ctrl+c/ctrl+x interrupt
signal.Notify(runChan, os.Interrupt)
// Alert the user that the server is starting
log.Printf("Server is starting on %s\n", server.Addr)
// Run the server on a new goroutine
go func() {
if err := server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
// Normal interrupt operation, ignore
} else {
log.Fatalf("Server failed to start due to err: %v", err)
}
}
}()
// Block on this channel listeninf for those previously defined syscalls assign
// to variable so we can let the user know why the server is shutting down
interrupt := <-runChan
// Set up a context to allow for graceful server shutdowns in the event
// of an OS interrupt (defers the cancel just in case)
ctx, cancel := context.WithTimeout(
context.Background(),
30,
)
defer cancel()
// If we get one of the pre-prescribed syscalls, gracefully terminate the server
// while alerting the user
log.Printf("Server is shutting down due to %+v\n", interrupt)
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server was unable to gracefully shutdown due to err: %+v", err)
}
}
func main() {
// Generate our config based on the config supplied
// by the user in the flags
cfgPath, err := ParseFlags()
if err != nil {
log.Fatal(err)
}
cfg, err := NewConfig(cfgPath)
if err != nil {
log.Fatal(err)
}
log.Printf("DiscoveryURL: %v", cfg.AuthConfig.DiscoveryURL)
badgermgr.OpenDatabase(cfg.DBConfig.DBPath, cfg.ClientConfig.StartingIP)
if debugMode {
badgermgr.GetAllKeys()
}
// Run the server
cfg.run()
}