all: refactor handler logic

- all: prefer `FormValues` to `ParseForm` with subsequent `Form.Get`s
- all: refactor authentication stack to be checked by middleware, and accessible via request context.
- all: replace http.ServeMux with gorilla/mux’s router
- all: replace custom CSRF checks with gorilla/csrf middleware
- authenticate: extract callback path as constant.
- internal/config: implement stringer interface for policy
- internal/cryptutil: add helper func `NewBase64Key`
- internal/cryptutil: rename `GenerateKey` to `NewKey`
- internal/cryptutil: rename `GenerateRandomString` to `NewRandomStringN`
- internal/middleware: removed alice in favor of gorilla/mux
- internal/sessions: remove unused `ValidateRedirectURI` and `ValidateClientSecret`
- internal/sessions: replace custom CSRF with gorilla/csrf fork that supports custom handler protection
- internal/urlutil: add `SignedRedirectURL` to create hmac'd URLs
- internal/urlutil: add `ValidateURL` helper to parse URL options
- internal/urlutil: add `GetAbsoluteURL` which takes a request and returns its absolute URL.
- proxy: remove holdover state verification checks; we no longer are setting sessions in any proxy routes so we don’t need them.
- proxy: replace un-named http.ServeMux with named domain routes.

Signed-off-by: Bobby DeSimone <bobbydesimone@gmail.com>
This commit is contained in:
Bobby DeSimone 2019-09-12 13:54:30 -07:00
parent a793249386
commit dc12947241
No known key found for this signature in database
GPG key ID: AEE4CF12FE86D07E
37 changed files with 1132 additions and 1384 deletions

View file

@ -1,15 +1,15 @@
package proxy // import "github.com/pomerium/pomerium/proxy"
import (
"encoding/base64"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/pomerium/csrf"
"github.com/pomerium/pomerium/internal/config"
"github.com/pomerium/pomerium/internal/cryptutil"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/middleware"
@ -18,34 +18,55 @@ import (
"github.com/pomerium/pomerium/internal/urlutil"
)
// StateParameter holds the redirect id along with the session id.
type StateParameter struct {
SessionID string `json:"session_id"`
RedirectURI string `json:"redirect_uri"`
}
// Handler returns the proxy service's ServeMux
func (p *Proxy) Handler() http.Handler {
// validation middleware chain
validate := middleware.NewChain()
validate = validate.Append(middleware.ValidateHost(func(host string) bool {
r := httputil.NewRouter().StrictSlash(true)
r.Use(middleware.ValidateHost(func(host string) bool {
_, ok := p.routeConfigs[host]
return ok
}))
mux := http.NewServeMux()
mux.HandleFunc("/robots.txt", p.RobotsTxt)
mux.HandleFunc("/.pomerium", p.UserDashboard)
mux.HandleFunc("/.pomerium/impersonate", p.Impersonate) // POST
mux.HandleFunc("/.pomerium/sign_out", p.SignOut)
// handlers with validation
mux.Handle("/.pomerium/callback", validate.ThenFunc(p.AuthenticateCallback))
mux.Handle("/.pomerium/refresh", validate.ThenFunc(p.ForceRefresh))
mux.Handle("/", validate.ThenFunc(p.Proxy))
return mux
r.Use(csrf.Protect(
p.cookieSecret,
csrf.Path("/"),
csrf.Domain(p.cookieDomain),
csrf.CookieName(fmt.Sprintf("%s_csrf", p.cookieName)),
csrf.ErrorHandler(http.HandlerFunc(httputil.CSRFFailureHandler)),
))
r.HandleFunc("/robots.txt", p.RobotsTxt)
// requires authN not authZ
r.Use(sessions.RetrieveSession(p.sessionStore))
r.Use(p.VerifySession)
r.HandleFunc("/.pomerium/", p.UserDashboard).Methods(http.MethodGet)
r.HandleFunc("/.pomerium/impersonate", p.Impersonate).Methods(http.MethodPost)
r.HandleFunc("/.pomerium/sign_out", p.SignOut).Methods(http.MethodGet, http.MethodPost)
r.HandleFunc("/.pomerium/refresh", p.ForceRefresh).Methods(http.MethodPost)
r.PathPrefix("/").HandlerFunc(p.Proxy)
return r
}
// VerifySession is the middleware used to enforce a valid authentication
// session state is attached to the users's request context.
func (p *Proxy) VerifySession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
state, err := sessions.FromContext(r.Context())
if err != nil {
log.Debug().Str("cause", err.Error()).Msg("proxy: re-authenticating due to session state error")
p.authenticate(w, r)
return
}
if err := state.Valid(); err != nil {
log.Debug().Str("cause", err.Error()).Msg("proxy: re-authenticating due to invalid session")
p.authenticate(w, r)
return
}
next.ServeHTTP(w, r)
})
}
// RobotsTxt sets the User-Agent header in the response to be "Disallow"
func (p *Proxy) RobotsTxt(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "User-agent: *\nDisallow: /")
}
@ -55,110 +76,18 @@ func (p *Proxy) RobotsTxt(w http.ResponseWriter, _ *http.Request) {
// the local session state.
func (p *Proxy) SignOut(w http.ResponseWriter, r *http.Request) {
redirectURL := &url.URL{Scheme: "https", Host: r.Host, Path: "/"}
switch r.Method {
case http.MethodPost:
if err := r.ParseForm(); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
uri, err := urlutil.ParseAndValidateURL(r.Form.Get("redirect_uri"))
if err == nil && uri.String() != "" {
redirectURL = uri
}
default:
uri, err := urlutil.ParseAndValidateURL(r.URL.Query().Get("redirect_uri"))
if err == nil && uri.String() != "" {
redirectURL = uri
}
if uri, err := urlutil.ParseAndValidateURL(r.FormValue("redirect_uri")); err == nil && uri.String() != "" {
redirectURL = uri
}
http.Redirect(w, r, p.GetSignOutURL(p.authenticateURL, redirectURL).String(), http.StatusFound)
uri := urlutil.SignedRedirectURL(p.SharedKey, p.authenticateSignoutURL, redirectURL)
http.Redirect(w, r, uri.String(), http.StatusFound)
}
// OAuthStart begins the authenticate flow, encrypting the redirect url
// Authenticate begins the authenticate flow, encrypting the redirect url
// in a request to the provider's sign in endpoint.
func (p *Proxy) OAuthStart(w http.ResponseWriter, r *http.Request) {
state := &StateParameter{
SessionID: fmt.Sprintf("%x", cryptutil.GenerateKey()),
RedirectURI: r.URL.String(),
}
// Encrypt CSRF + redirect_uri and store in csrf session. Validated on callback.
csrfState, err := p.cipher.Marshal(state)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
p.csrfStore.SetCSRF(w, r, csrfState)
paramState, err := p.cipher.Marshal(state)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
// Sanity check. The encrypted payload of local and remote state should
// never match as each encryption round uses a cryptographic nonce.
// if paramState == csrfState {
// httputil.ErrorResponse(w, r, httputil.Error("encrypted state should not match", http.StatusBadRequest, nil))
// return
// }
signinURL := p.GetSignInURL(p.authenticateURL, p.GetRedirectURL(r.Host), paramState)
// Redirect the user to the authenticate service along with the encrypted
// state which contains a redirect uri back to the proxy and a nonce
http.Redirect(w, r, signinURL.String(), http.StatusFound)
}
// AuthenticateCallback checks the state parameter to make sure it matches the
// local csrf state then redirects the user back to the original intended route.
func (p *Proxy) AuthenticateCallback(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
// Encrypted CSRF passed from authenticate service
remoteStateEncrypted := r.Form.Get("state")
var remoteStatePlain StateParameter
if err := p.cipher.Unmarshal(remoteStateEncrypted, &remoteStatePlain); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
c, err := p.csrfStore.GetCSRF(r)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
p.csrfStore.ClearCSRF(w, r)
localStateEncrypted := c.Value
var localStatePlain StateParameter
err = p.cipher.Unmarshal(localStateEncrypted, &localStatePlain)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
// assert no nonce reuse
if remoteStateEncrypted == localStateEncrypted {
p.sessionStore.ClearSession(w, r)
httputil.ErrorResponse(w, r,
httputil.Error("local and remote state", http.StatusBadRequest,
fmt.Errorf("possible nonce-reuse / replay attack")))
return
}
// Decrypted remote and local state struct (inc. nonce) must match
if remoteStatePlain.SessionID != localStatePlain.SessionID {
p.sessionStore.ClearSession(w, r)
httputil.ErrorResponse(w, r, httputil.Error("CSRF mismatch", http.StatusBadRequest, nil))
return
}
// This is the redirect back to the original requested application
http.Redirect(w, r, remoteStatePlain.RedirectURI, http.StatusFound)
func (p *Proxy) authenticate(w http.ResponseWriter, r *http.Request) {
uri := urlutil.SignedRedirectURL(p.SharedKey, p.authenticateSigninURL, urlutil.GetAbsoluteURL(r))
http.Redirect(w, r, uri.String(), http.StatusFound)
}
// shouldSkipAuthentication contains conditions for skipping authentication.
@ -189,17 +118,6 @@ func isCORSPreflight(r *http.Request) bool {
r.Header.Get("Origin") != ""
}
func (p *Proxy) loadExistingSession(r *http.Request) (*sessions.State, error) {
s, err := p.sessionStore.LoadSession(r)
if err != nil {
return nil, fmt.Errorf("proxy: invalid session: %w", err)
}
if err := s.Valid(); err != nil {
return nil, fmt.Errorf("proxy: invalid state: %w", err)
}
return s, nil
}
// Proxy authenticates a request, either proxying the request if it is authenticated,
// or starting the authenticate service for validation if not.
func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
@ -214,11 +132,10 @@ func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
route.ServeHTTP(w, r)
return
}
s, err := p.loadExistingSession(r)
if err != nil {
log.Debug().Str("cause", err.Error()).Msg("proxy: bad authN session, redirecting")
p.OAuthStart(w, r)
s, err := sessions.FromContext(r.Context())
if err != nil || s == nil {
log.Debug().Err(err).Msg("proxy: couldn't get session from context")
p.authenticate(w, r)
return
}
authorized, err := p.AuthorizeClient.Authorize(r.Context(), r.Host, s)
@ -226,7 +143,7 @@ func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
httputil.ErrorResponse(w, r, err)
return
} else if !authorized {
httputil.ErrorResponse(w, r, httputil.Error(fmt.Sprintf("%s is not authorized for this route", s.Email), http.StatusForbidden, nil))
httputil.ErrorResponse(w, r, httputil.Error(fmt.Sprintf("%s is not authorized for this route", s.RequestEmail()), http.StatusForbidden, nil))
return
}
r.Header.Set(HeaderUserID, s.User)
@ -240,62 +157,41 @@ func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
// It also contains certain administrative actions like user impersonation.
// Nota bene: This endpoint does authentication, not authorization.
func (p *Proxy) UserDashboard(w http.ResponseWriter, r *http.Request) {
session, err := p.loadExistingSession(r)
session, err := sessions.FromContext(r.Context())
if err != nil {
log.Debug().Str("cause", err.Error()).Msg("proxy: bad authN session, redirecting")
p.OAuthStart(w, r)
httputil.ErrorResponse(w, r, err)
return
}
redirectURL := &url.URL{Scheme: "https", Host: r.Host, Path: "/.pomerium/sign_out"}
isAdmin, err := p.AuthorizeClient.IsAdmin(r.Context(), session)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
// CSRF value used to mitigate replay attacks.
csrf := &StateParameter{SessionID: fmt.Sprintf("%x", cryptutil.GenerateKey())}
csrfCookie, err := p.cipher.Marshal(csrf)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
p.csrfStore.SetCSRF(w, r, csrfCookie)
t := struct {
Email string
User string
Groups []string
RefreshDeadline string
SignoutURL string
IsAdmin bool
ImpersonateEmail string
ImpersonateGroup string
CSRF string
}{
Email: session.Email,
User: session.User,
Groups: session.Groups,
RefreshDeadline: time.Until(session.RefreshDeadline).Round(time.Second).String(),
SignoutURL: p.GetSignOutURL(p.authenticateURL, redirectURL).String(),
IsAdmin: isAdmin,
ImpersonateEmail: session.ImpersonateEmail,
ImpersonateGroup: strings.Join(session.ImpersonateGroups, ","),
CSRF: csrf.SessionID,
}
templates.New().ExecuteTemplate(w, "dashboard.html", t)
//todo(bdd): make sign out redirect a configuration option so that
// admins can set to whatever their corporate homepage is
redirectURL := &url.URL{Scheme: "https", Host: r.Host, Path: "/"}
signoutURL := urlutil.SignedRedirectURL(p.SharedKey, p.authenticateSignoutURL, redirectURL)
templates.New().ExecuteTemplate(w, "dashboard.html", map[string]interface{}{
"Email": session.Email,
"User": session.User,
"Groups": session.Groups,
"RefreshDeadline": time.Until(session.RefreshDeadline).Round(time.Second).String(),
"SignoutURL": signoutURL.String(),
"IsAdmin": isAdmin,
"ImpersonateEmail": session.ImpersonateEmail,
"ImpersonateGroup": strings.Join(session.ImpersonateGroups, ","),
"csrfField": csrf.TemplateField(r),
})
}
// ForceRefresh redeems and extends an existing authenticated oidc session with
// the underlying identity provider. All session details including groups,
// timeouts, will be renewed.
func (p *Proxy) ForceRefresh(w http.ResponseWriter, r *http.Request) {
session, err := p.loadExistingSession(r)
session, err := sessions.FromContext(r.Context())
if err != nil {
log.Debug().Str("cause", err.Error()).Msg("proxy: bad authN session, redirecting")
p.OAuthStart(w, r)
httputil.ErrorResponse(w, r, err)
return
}
iss, err := session.IssuedAt()
@ -324,49 +220,25 @@ func (p *Proxy) ForceRefresh(w http.ResponseWriter, r *http.Request) {
// to the user's current user sessions state if the user is currently an
// administrative user. Requests are redirected back to the user dashboard.
func (p *Proxy) Impersonate(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if err := r.ParseForm(); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
session, err := p.loadExistingSession(r)
if err != nil {
log.Debug().Str("cause", err.Error()).Msg("proxy: bad authN session, redirecting")
p.OAuthStart(w, r)
return
}
isAdmin, err := p.AuthorizeClient.IsAdmin(r.Context(), session)
if err != nil || !isAdmin {
httputil.ErrorResponse(w, r, httputil.Error(fmt.Sprintf("%s is not an administrator", session.Email), http.StatusForbidden, err))
return
}
// CSRF check -- did this request originate from our form?
c, err := p.csrfStore.GetCSRF(r)
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
p.csrfStore.ClearCSRF(w, r)
encryptedCSRF := c.Value
var decryptedCSRF StateParameter
if err = p.cipher.Unmarshal(encryptedCSRF, decryptedCSRF); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
if decryptedCSRF.SessionID != r.FormValue("csrf") {
httputil.ErrorResponse(w, r, httputil.Error("CSRF mismatch", http.StatusBadRequest, nil))
return
}
// OK to impersonation
session.ImpersonateEmail = r.FormValue("email")
session.ImpersonateGroups = strings.Split(r.FormValue("group"), ",")
if err := p.sessionStore.SaveSession(w, r, session); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
session, err := sessions.FromContext(r.Context())
if err != nil {
httputil.ErrorResponse(w, r, err)
return
}
isAdmin, err := p.AuthorizeClient.IsAdmin(r.Context(), session)
if err != nil || !isAdmin {
httputil.ErrorResponse(w, r, httputil.Error(fmt.Sprintf("%s is not an administrator", session.RequestEmail()), http.StatusForbidden, err))
return
}
// OK to impersonation
session.ImpersonateEmail = r.FormValue("email")
session.ImpersonateGroups = strings.Split(r.FormValue("group"), ",")
if err := p.sessionStore.SaveSession(w, r, session); err != nil {
httputil.ErrorResponse(w, r, err)
return
}
http.Redirect(w, r, "/.pomerium", http.StatusFound)
}
@ -391,48 +263,3 @@ func (p *Proxy) policy(r *http.Request) (*config.Policy, bool) {
}
return nil, false
}
// GetRedirectURL returns the redirect url for a single reverse proxy host. HTTPS is set explicitly.
func (p *Proxy) GetRedirectURL(host string) *url.URL {
u := p.redirectURL
u.Scheme = "https"
u.Host = host
return u
}
// signRedirectURL takes a redirect url string and timestamp and returns the base64
// encoded HMAC result.
func (p *Proxy) signRedirectURL(rawRedirect string, timestamp time.Time) string {
data := []byte(fmt.Sprint(rawRedirect, timestamp.Unix()))
h := cryptutil.Hash(p.SharedKey, data)
return base64.URLEncoding.EncodeToString(h)
}
// GetSignInURL with typical oauth parameters
func (p *Proxy) GetSignInURL(authenticateURL, redirectURL *url.URL, state string) *url.URL {
a := authenticateURL.ResolveReference(&url.URL{Path: "/sign_in"})
now := time.Now()
rawRedirect := redirectURL.String()
params, _ := url.ParseQuery(a.RawQuery) // handled by ServeMux
params.Set("redirect_uri", rawRedirect)
params.Set("shared_secret", p.SharedKey)
params.Set("response_type", "code")
params.Add("state", state)
params.Set("ts", fmt.Sprint(now.Unix()))
params.Set("sig", p.signRedirectURL(rawRedirect, now))
a.RawQuery = params.Encode()
return a
}
// GetSignOutURL creates and returns the sign out URL, given a redirectURL
func (p *Proxy) GetSignOutURL(authenticateURL, redirectURL *url.URL) *url.URL {
a := authenticateURL.ResolveReference(&url.URL{Path: "/sign_out"})
now := time.Now()
rawRedirect := redirectURL.String()
params, _ := url.ParseQuery(a.RawQuery) // handled by ServeMux
params.Add("redirect_uri", rawRedirect)
params.Set("ts", fmt.Sprint(now.Unix()))
params.Set("sig", p.signRedirectURL(rawRedirect, now))
a.RawQuery = params.Encode()
return a
}