summaryrefslogtreecommitdiff
path: root/main.go
blob: 44501c0802a9a5709af511991e06d212342f3e26 (plain)
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
package main

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"gopkg.in/square/go-jose.v2"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
)

const (
	NONCE_SIZE        int    = 16
	TOKEN_COOKIE_NAME string = "sso_token"
	RFP_COOKIE_NAME   string = "sso_rfp"
)

// acr_values can be mfa or selective_mfa (mfa only for external users)
// mfa amr values:
// pas - password
// otp - OTP code
// u2f - U2F code
// mfa - multi-factor
// hrd - hardware OTP device used
// sft - software OTP device used

type ProxyConfig struct {
	IDProviderURL      string
	ClientID           string
	UpstreamURL        string
	ListenOn           string
	TrustedCACert      string
	IsOptional         bool
	RequestMFA         bool
	AllowedMFAMethods  []string // An OR set
	RequiredMFAMethods []string // An AND set
	reverseProxy       *httputil.ReverseProxy
}

type IdPConfig struct {
	AuthorizationEndpoint string   `json:"authorization_endpoint"`
	Issuer                string   `json:"issuer"`
	JwksUri               string   `json:"jwks_uri"`
	SupportedGrantTypes   []string `json:"grant_types_supported"`
	IdTokenSigningAlgs    []string `json:"id_token_signing_alg_values_supported"`
	ResponseModes         []string `json:"response_modes_supported"`
	ResponseTypes         []string `json:"response_types_supported"`
	Scopes                []string `json:"scopes_supported"`
	SubjectTypes          []string `json:"subject_types_supported"`
}

func FetchIdPConfig(h CautiousHTTPClient, idp_url string) (*IdPConfig, error) {
	u, err := url.Parse(idp_url)
	if err != nil {
		return nil, err
	}
	u.Path = "/.well-known/openid-configuration"

	var idpc IdPConfig
	err = h.GetJSON(u.String(), &idpc)
	if err != nil {
		return nil, err
	}

	return &idpc, nil
}

// TODO: Optimization to fetch only if expired (per http headers)
func FetchJWKS(h CautiousHTTPClient, jwks_url string) (map[string]jose.JSONWebKey, error) {
	var jwks jose.JSONWebKeySet
	err := h.GetJSON(jwks_url, &jwks)
	if err != nil {
		return nil, err
	}

	keys := make(map[string]jose.JSONWebKey, len(jwks.Keys))

	for _, k := range jwks.Keys {
		keys[k.KeyID] = k
	}

	return keys, nil
}

func URLMustParse(u string) *url.URL {
	o, err := url.Parse(u)
	if err != nil {
		panic(err)
	}
	return o
}

func GenerateNonce() (string, error) {
	nonce := make([]byte, NONCE_SIZE)
	n, err := rand.Read(nonce)
	if n != NONCE_SIZE || err != nil {
		return "", err
	}
	return hex.EncodeToString(nonce), nil
}

func CompareUpper(lhs, rhs string) bool {
	return strings.ToUpper(lhs) == strings.ToUpper(rhs)
}

// TODO
// Cookie rules
// Secure
// HttpOnly
// Path to /
// Expires to iat in JWT
func SetCookie() {
}

// TODO
// Fetch (connect timeout 1s, read timeout 30s, read size 1M)
func DownloadCertificate() {
}

// TODO
// Fetch (connect timeout 1s, read timeout 30s, read size 1M)
func DownloadCRL() {
}

// TODO
// Cert validation
// Validate cert not in CRL
// Validate cert chains to trusted CA cert (ship with proxy)
// Validate CRL signed by trusted CA
// Cert "Subject CN " must match exactly PKI setting (ex: foo-pki.foo.com)
// Current time bust be within "Validity Not Before" and "Validity Not After" in cert +- 5 minutes
// Cert Key length >= 2048
// Certificate usage must include "digitalSignature"
func ValidateCertificate() {
}

// TODO
func MakeClientID(r *http.Request) string {
	if strings.Contains(r.Host, ":") {
		return r.Host
	}
	return ""
}

// TODO
func RedirectToIDP(w http.ResponseWriter, r *http.Request) {
	nonce, _ := GenerateNonce()
	_ = nonce
	nonceh := "" // SHA256 nonce

	// Set nonce cookie

	req := url.Values{}
	req.Add("client_id", "") // fqdn + : + port
	req.Add("nonce", nonceh)
	req.Add("redirect_uri", "") // Requested URL
	req.Add("scope", "openid")
	req.Add("response_type", "id_token")
}

// TODO: Remove id_token from URL, set cookie and redirect user to requested URL
func SetTokenCookieAndRedirect(w http.ResponseWriter, r *http.Request, token string) {
}

// TODO
// Occasionally refresh IDP config (per HTTP caching headers)
//
// Fetch ${IDP_HOST}/.well-known/openid-configuration
// - validate certificate chains to a trusted root
// - validate scopes_supported contains "openid"
// - validate response_types_supported contains "id_token"
// - validate grant_types_supported contains "implicit"
// - validate id_token_signing_alg_values_supported contains a supported signing type (see below)
// - Cache authorization_endpoint for redirecting users
//
// Fetch jwks_uri endpoint
// - Build key map indexed by kid for all keys that are suppored by our rules
//   - kty == RSA
//   - alg header must be one of [PS256, PS385, PS512]
//   - pem decode x5c and validate the certificate chain as below
//   - validate first item of x5c matches n and e
func RefreshIDPConfig() {
}

// TODO
// If x5u exists in header
// Fetch cert from x5u URL
// Get CRL from cert, fetch (connect timeout 1s, read timeout 30s, read size 1M)
//
// exp claim has passed +- 5 minutes
// iat claim is greater than 24 hours +- 5 minutes
// aud claim is exact match for client_id
// iss claim is exact match for idp (ex: foo.example.com)
// if other aud claims validate that they are known
// nonce in JWT must be SHA256 of rfp cookie value
// Validate cert
// alg jwt header must be one of [PS256, PS385, PS512]
// typ jwt header must be JWS
// validate jwt signature
// validate amr claim contains requested acr values (selective_mfa will be just mfa)
// validate acr claim is the same as requested acr_values
func ValidateJWT(jwt, rfp string) bool {
	return true
}

// TODO
func GetJWTSubject(jwt string) string {
	return ""
}

func RequestHasForwardedUser(w http.ResponseWriter, r *http.Request) bool {
	if _, ok := r.Header["X-Forwarded-User"]; ok {
		log.Printf("ERROR: Request contains X-Forwarded-For header")
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return true
	} else {
		return false
	}
}

func RequestIsOverSecureChannel(w http.ResponseWriter, r *http.Request) bool {
	https, ok := r.Header["X-Forwarded-Proto"]
	if !ok || len(https) != 1 {
		log.Printf("ERROR: Request does not contain X-Forwarded-Proto header")
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return false
	}

	if !CompareUpper(https[0], "HTTPS") {
		log.Printf("ERROR: Request is not over HTTPS")
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return false
	}

	return true
}

// TODO
// - Validate Hostname header == known hostname
func AuthProxyController(w http.ResponseWriter, r *http.Request) {
	proxy := r.Context().Value("ProxyConfig").(*ProxyConfig).reverseProxy

	// Order matters in these checks!
	if RequestHasForwardedUser(w, r) {
		return
	}

	if !RequestIsOverSecureChannel(w, r) {
		return
	}

	if CompareUpper(r.Method, "OPTIONS") {
		proxy.ServeHTTP(w, r)
		return
	}

	rfpc, err := r.Cookie(RFP_COOKIE_NAME)
	if err != nil {
		log.Printf("ERROR: No rfp cookie")
		RedirectToIDP(w, r)
		return
	}

	token := r.URL.Query().Get("id_token")
	if token != "" && ValidateJWT(rfpc.Value, token) {
		SetTokenCookieAndRedirect(w, r, token)
		return
	}

	tokenc, err := r.Cookie(TOKEN_COOKIE_NAME)
	if err != nil {
		log.Printf("ERROR: No token cookie")
		RedirectToIDP(w, r)
		return
	}

	if !ValidateJWT(tokenc.Value, rfpc.Value) {
		log.Printf("ERROR: Token is invalid")
		RedirectToIDP(w, r)
		return
	}

	r.Header["X-Forwarded-User"] = []string{GetJWTSubject(tokenc.Value)}

	proxy.ServeHTTP(w, r)
}

// Remove token and rfp cookies and redirect user to root of domain
func LogoutController(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name:   TOKEN_COOKIE_NAME,
		Value:  "",
		MaxAge: 0,
	})

	http.SetCookie(w, &http.Cookie{
		Name:   TOKEN_COOKIE_NAME,
		Value:  "",
		MaxAge: 0,
	})

	http.Redirect(w, r, "/", http.StatusFound)
}

// TODO
func LoginController(w http.ResponseWriter, r *http.Request) {
}

// TODO
// Optional login allows for applications that can operate in anonymous mode or
// authenticated mode. When in anonmyous mode the request is proxied through
// without an X-Forwarded-User header. Upstream servers should either expose or
// map a URL for /.oidc/login to allow users to login. On successful login the
// user will be redirected back to the main page for the site (/)
func parseConfig() *ProxyConfig {
	return &ProxyConfig{
		IDProviderURL: "",
		ClientID:      "",
		UpstreamURL:   "http://localhost:9991/",
		ListenOn:      ":9992",
		TrustedCACert: "",
		IsOptional:    false,
	}
}

func main() {
	h := NewCautiousHTTPClient()

	idpc, err := FetchIdPConfig(h, "http://mcrute-virt:9993")
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}

	jwks, err := FetchJWKS(h, idpc.JwksUri)
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	fmt.Printf("%+v\n", jwks)
	return

	cfg := parseConfig()
	cfg.reverseProxy = httputil.NewSingleHostReverseProxy(URLMustParse(cfg.UpstreamURL))

	if cfg.IsOptional {
		http.HandleFunc("/.oidc/login", func(w http.ResponseWriter, r *http.Request) {
			LoginController(w,
				r.WithContext(context.WithValue(r.Context(), "ProxyConfig", cfg)))
		})
	}

	http.HandleFunc("/.oidc/logout", func(w http.ResponseWriter, r *http.Request) {
		LogoutController(w,
			r.WithContext(context.WithValue(r.Context(), "ProxyConfig", cfg)))
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		AuthProxyController(w,
			r.WithContext(context.WithValue(r.Context(), "ProxyConfig", cfg)))
	})

	log.Fatal(http.ListenAndServe(cfg.ListenOn, nil))
}