forked from louketo/louketo-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
525 lines (443 loc) · 13.1 KB
/
server.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
/*
Copyright 2015 All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path"
"runtime"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/armon/go-proxyproto"
"github.com/coreos/go-oidc/jose"
"github.com/coreos/go-oidc/oidc"
"github.com/elazarl/goproxy"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
httplog "log"
)
type oauthProxy struct {
// the proxy configuration
config *Config
// the gin service
router *gin.Engine
// the opened client
client *oidc.Client
// the openid provider configuration
provider oidc.ProviderConfig
// the proxy client
upstream reverseProxy
// the upstream endpoint url
endpoint *url.URL
// the store interface
store storage
// the prometheus handler
prometheusHandler http.Handler
}
type reverseProxy interface {
ServeHTTP(rw http.ResponseWriter, req *http.Request)
}
func init() {
// step: ensure all time is in UTC
time.LoadLocation("UTC")
// step: set the core
runtime.GOMAXPROCS(runtime.NumCPU())
}
//
// newProxy create's a new proxy from configuration
//
func newProxy(config *Config) (*oauthProxy, error) {
var err error
// step: set the logging level
if config.LogJSONFormat {
log.SetFormatter(&log.JSONFormatter{})
}
if config.Verbose {
log.SetLevel(log.DebugLevel)
}
// step: disable the logging for http server - stop us from getting all those
// annoying EOF from tcp health checks
httplog.SetOutput(ioutil.Discard)
log.Infof("starting %s, author: %s, version: %s, ", prog, author, version)
service := &oauthProxy{
config: config,
prometheusHandler: prometheus.Handler(),
}
// step: parse the upstream endpoint
if service.endpoint, err = url.Parse(config.Upstream); err != nil {
return nil, err
}
// step: initialize the store if any
if config.StoreURL != "" {
if service.store, err = createStorage(config.StoreURL); err != nil {
return nil, err
}
}
// step: initialize the openid client
if !config.SkipTokenVerification {
service.client, service.provider, err = createOpenIDClient(config)
if err != nil {
return nil, err
}
} else {
log.Warnf("TESTING ONLY CONFIG - the verification of the token have been disabled")
}
if config.ClientID == "" && config.ClientSecret == "" {
log.Warnf("Note: client credentials are not set, depending on provider (confidential|public) you might be able to auth")
}
// step: are we running in forwarding more?
switch config.EnableForwarding {
case true:
if err := createForwardingProxy(config, service); err != nil {
return nil, err
}
default:
if err := createReverseProxy(config, service); err != nil {
return nil, err
}
}
return service, nil
}
//
// createReverseProxy creates a reverse proxy
//
func createReverseProxy(config *Config, service *oauthProxy) error {
log.Infof("enabled reverse proxy mode, upstream url: %s", config.Upstream)
// step: display the protected resources
for _, resource := range config.Resources {
log.Infof("protecting resources under uri: %s", resource)
}
for name, value := range config.MatchClaims {
log.Infof("the token must container the claim: %s, required: %s", name, value)
}
// step: initialize the reverse http proxy
if err := service.createUpstreamProxy(service.endpoint); err != nil {
return err
}
// step: create the endpoints
if err := service.createEndpoints(); err != nil {
return err
}
// step: load the templates
if err := service.createTemplates(); err != nil {
return err
}
return nil
}
//
// createForwardingProxy creates a forwarding proxy
//
func createForwardingProxy(config *Config, service *oauthProxy) error {
log.Infof("enabled forward signing proxy mode")
if config.SkipUpstreamTLSVerify {
log.Warnf("TLS verification switched off; in forward signing mode it's recommended you verify! (--skip-upstream-tls-verify=false)")
}
// step: initialize the reverse http proxy
if err := service.createUpstreamProxy(nil); err != nil {
return err
}
gin.SetMode(gin.ReleaseMode)
// step: enable debugging in verbose more
if config.Verbose {
gin.SetMode(gin.DebugMode)
}
engine := gin.New()
// step: default to release mode, only go debug on verbose logging
engine.Use(gin.Recovery())
service.router = engine
// step: are we logging the traffic?
if config.LogRequests {
engine.Use(service.loggingMiddleware())
}
engine.Use(service.forwardProxyMiddleware())
return nil
}
//
// Run starts the proxy service
//
func (r *oauthProxy) Run() (err error) {
tlsConfig := &tls.Config{}
// step: are we doing mutual tls?
if r.config.TLSCaCertificate != "" {
log.Infof("enabling mutual tls, reading in the signing ca: %s", r.config.TLSCaCertificate)
caCert, err := ioutil.ReadFile(r.config.TLSCaCertificate)
if err != nil {
return err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.ClientCAs = caCertPool
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
server := &http.Server{
Addr: r.config.Listen,
Handler: r.router,
}
// step: create the listener
var listener net.Listener
switch strings.HasPrefix(r.config.Listen, "unix://") {
case true:
socket := strings.Trim(r.config.Listen, "unix://")
// step: delete the socket if it exists
if exists := fileExists(socket); exists {
if err := os.Remove(socket); err != nil {
return err
}
}
log.Infof("listening on unix socket: %s", r.config.Listen)
if listener, err = net.Listen("unix", socket); err != nil {
return err
}
default:
listener, err = net.Listen("tcp", r.config.Listen)
if err != nil {
return err
}
}
// step: configure tls
if r.config.TLSCertificate != "" && r.config.TLSPrivateKey != "" {
server.TLSConfig = tlsConfig
if tlsConfig.NextProtos == nil {
tlsConfig.NextProtos = []string{"http/1.1"}
}
if len(tlsConfig.Certificates) == 0 || r.config.TLSCertificate != "" || r.config.TLSPrivateKey != "" {
var err error
tlsConfig.Certificates = make([]tls.Certificate, 1)
if tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(r.config.TLSCertificate, r.config.TLSPrivateKey); err != nil {
return err
}
}
log.Infof("tls enabled, certificate: %s, key: %s", r.config.TLSCertificate, r.config.TLSPrivateKey)
listener = tls.NewListener(listener, tlsConfig)
}
// step: wrap the listen in a proxy protocol
if r.config.EnableProxyProtocol {
log.Infof("enabling the proxy protocol on listener: %s", r.config.Listen)
listener = &proxyproto.Listener{listener}
}
go func() {
log.Infof("keycloak proxy service starting on %s", r.config.Listen)
if err = server.Serve(listener); err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
}).Fatalf("failed to start the service")
}
}()
return nil
}
//
// createUpstreamProxy create a reverse http proxy from the upstream
//
func (r *oauthProxy) createUpstreamProxy(upstream *url.URL) error {
// step: create the default dialer
dialer := (&net.Dialer{
KeepAlive: r.config.UpstreamKeepaliveTimeout,
Timeout: r.config.UpstreamTimeout,
}).Dial
// step: are we using a unix socket?
if upstream != nil && upstream.Scheme == "unix" {
log.Infof("using the unix domain socket: %s%s for upstream", upstream.Host, upstream.Path)
socketPath := fmt.Sprintf("%s%s", upstream.Host, upstream.Path)
dialer = func(network, address string) (net.Conn, error) {
return net.Dial("unix", socketPath)
}
upstream.Path = ""
upstream.Host = "domain-sock"
upstream.Scheme = "http"
}
// step: create the upstream tls configure
tlsConfig := &tls.Config{
InsecureSkipVerify: r.config.SkipUpstreamTLSVerify,
}
// step: are we using a client certificate
// @TODO provide a means of reload on the client certificate when it expires. I'm not sure if it's just a
// case of update the http transport settings - Also we to place this go-routine?
if r.config.TLSClientCertificate != "" {
cert, err := ioutil.ReadFile(r.config.TLSClientCertificate)
if err != nil {
log.Fatal(err)
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(cert)
// step: update the upstream tls to use the client certificate
tlsConfig.ClientCAs = pool
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
// step: create the forwarding proxy
proxy := goproxy.NewProxyHttpServer()
// step: update the tls configuration of the reverse proxy
proxy.Tr = &http.Transport{
Dial: dialer,
TLSClientConfig: tlsConfig,
DisableKeepAlives: !r.config.UpstreamKeepalives,
}
r.upstream = proxy
return nil
}
//
// createEndpoints sets up the gin routing
//
func (r *oauthProxy) createEndpoints() error {
gin.SetMode(gin.ReleaseMode)
if r.config.Verbose {
gin.SetMode(gin.DebugMode)
}
//step: create the egin router
engine := gin.New()
engine.Use(gin.Recovery())
// step: are we logging the traffic?
if r.config.LogRequests {
engine.Use(r.loggingMiddleware())
}
// step: enabling the metrics?
if r.config.EnableMetrics {
engine.Use(r.metricsMiddleware())
}
// step: enabling the security filter?
if r.config.EnableSecurityFilter {
engine.Use(r.securityMiddleware())
}
// step: add the routing
oauth := engine.Group(oauthURL)
{
oauth.Use(r.corsMiddleware(r.config.CrossOrigin))
oauth.GET(authorizationURL, r.oauthAuthorizationHandler)
oauth.GET(callbackURL, r.oauthCallbackHandler)
oauth.GET(healthURL, r.healthHandler)
oauth.GET(tokenURL, r.tokenHandler)
oauth.GET(expiredURL, r.expirationHandler)
oauth.GET(logoutURL, r.logoutHandler)
oauth.POST(loginURL, r.loginHandler)
if r.config.EnableMetrics {
oauth.GET(metricsURL, r.metricsEndpointHandler)
}
}
engine.Use(
r.entrypointMiddleware(),
r.authenticationMiddleware(),
r.admissionMiddleware(),
r.headersMiddleware(r.config.AddClaims),
r.reverveProxyMiddleware())
r.router = engine
return nil
}
//
// createTemplates loads the custom template
//
func (r *oauthProxy) createTemplates() error {
var list []string
if r.config.SignInPage != "" {
log.Debugf("loading the custom sign in page: %s", r.config.SignInPage)
list = append(list, r.config.SignInPage)
}
if r.config.ForbiddenPage != "" {
log.Debugf("loading the custom sign forbidden page: %s", r.config.ForbiddenPage)
list = append(list, r.config.ForbiddenPage)
}
if len(list) > 0 {
log.Infof("loading the custom templates: %s", strings.Join(list, ","))
r.router.LoadHTMLFiles(list...)
}
return nil
}
//
// useStore checks if we are using a store to hold the refresh tokens
//
func (r *oauthProxy) useStore() bool {
return r.store != nil
}
//
// StoreRefreshToken the token to the store
//
func (r *oauthProxy) StoreRefreshToken(token jose.JWT, value string) error {
return r.store.Set(getHashKey(&token), value)
}
//
// Get retrieves a token from the store, the key we are using here is the access token
//
func (r *oauthProxy) GetRefreshToken(token jose.JWT) (string, error) {
// step: the key is the access token
v, err := r.store.Get(getHashKey(&token))
if err != nil {
return v, err
}
if v == "" {
return v, ErrNoSessionStateFound
}
return v, nil
}
//
// DeleteRefreshToken removes a key from the store
//
func (r *oauthProxy) DeleteRefreshToken(token jose.JWT) error {
if err := r.store.Delete(getHashKey(&token)); err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
}).Errorf("failed to delete the token from store")
return err
}
return nil
}
//
// Close is used to close off any resources
//
func (r *oauthProxy) CloseStore() error {
if r.store != nil {
return r.store.Close()
}
return nil
}
//
// accessForbidden redirects the user to the forbidden page
//
func (r *oauthProxy) accessForbidden(cx *gin.Context) {
if r.config.hasCustomForbiddenPage() {
cx.HTML(http.StatusForbidden, path.Base(r.config.ForbiddenPage), r.config.TagData)
cx.Abort()
return
}
cx.AbortWithStatus(http.StatusForbidden)
}
//
// redirectToURL redirects the user and aborts the context
//
func (r *oauthProxy) redirectToURL(url string, cx *gin.Context) {
cx.Redirect(http.StatusTemporaryRedirect, url)
cx.Abort()
}
//
// redirectToAuthorization redirects the user to authorization handler
//
func (r *oauthProxy) redirectToAuthorization(cx *gin.Context) {
if r.config.NoRedirects {
cx.AbortWithStatus(http.StatusUnauthorized)
return
}
// step: add a state referrer to the authorization page
authQuery := fmt.Sprintf("?state=%s", base64.StdEncoding.EncodeToString([]byte(cx.Request.URL.RequestURI())))
// step: if verification is switched off, we can't authorization
if r.config.SkipTokenVerification {
log.Errorf("refusing to redirection to authorization endpoint, skip token verification switched on")
cx.AbortWithStatus(http.StatusForbidden)
return
}
r.redirectToURL(oauthURL+authorizationURL+authQuery, cx)
}