2023-04-18 19:38:32 +02:00
package publicProxy
2022-07-19 22:15:54 +02:00
import (
2022-08-10 21:15:35 +02:00
"context"
2023-09-28 20:39:31 +02:00
"crypto/md5"
2022-08-10 21:15:35 +02:00
"fmt"
2023-09-05 18:50:41 +02:00
"github.com/golang-jwt/jwt/v5"
2022-07-20 20:16:01 +02:00
"github.com/openziti/sdk-golang/ziti"
2023-01-13 21:01:34 +01:00
"github.com/openziti/zrok/endpoints"
2023-04-18 19:38:32 +02:00
"github.com/openziti/zrok/endpoints/publicProxy/healthUi"
"github.com/openziti/zrok/endpoints/publicProxy/notFoundUi"
2023-09-05 18:50:41 +02:00
"github.com/openziti/zrok/endpoints/publicProxy/unauthorizedUi"
2023-07-13 20:26:35 +02:00
"github.com/openziti/zrok/environment"
2023-11-21 20:27:17 +01:00
"github.com/openziti/zrok/sdk/golang/sdk"
2023-01-13 21:01:34 +01:00
"github.com/openziti/zrok/util"
2022-07-20 20:16:01 +02:00
"github.com/pkg/errors"
2022-07-26 19:30:19 +02:00
"github.com/sirupsen/logrus"
2023-02-22 16:37:07 +01:00
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
2023-09-05 16:55:55 +02:00
"time"
2022-07-19 22:15:54 +02:00
)
2023-09-26 17:36:11 +02:00
type HttpFrontend struct {
2022-08-18 22:57:38 +02:00
cfg * Config
zCtx ziti . Context
handler http . Handler
}
2023-09-26 17:36:11 +02:00
func NewHTTP ( cfg * Config ) ( * HttpFrontend , error ) {
2023-09-28 20:39:31 +02:00
var key [ ] byte
if cfg . Oauth != nil {
hash := md5 . New ( )
2023-10-05 19:34:27 +02:00
n , err := hash . Write ( [ ] byte ( cfg . Oauth . HashKey ) )
2023-09-28 20:39:31 +02:00
if err != nil {
return nil , err
}
2023-10-05 19:34:27 +02:00
if n != len ( cfg . Oauth . HashKey ) {
2023-09-28 20:39:31 +02:00
return nil , errors . New ( "short hash" )
}
key = hash . Sum ( nil )
}
2023-09-26 17:36:11 +02:00
root , err := environment . LoadRoot ( )
2023-07-13 20:26:35 +02:00
if err != nil {
return nil , errors . Wrap ( err , "error loading environment root" )
}
2023-09-26 17:36:11 +02:00
zCfgPath , err := root . ZitiIdentityNamed ( cfg . Identity )
2022-09-06 21:01:38 +02:00
if err != nil {
2023-07-10 22:41:16 +02:00
return nil , errors . Wrapf ( err , "error getting ziti identity '%v' from environment" , cfg . Identity )
2022-09-06 21:01:38 +02:00
}
2023-05-25 17:50:38 +02:00
zCfg , err := ziti . NewConfigFromFile ( zCfgPath )
2022-07-20 20:16:01 +02:00
if err != nil {
2022-08-18 22:57:38 +02:00
return nil , errors . Wrap ( err , "error loading config" )
2022-07-20 20:16:01 +02:00
}
2023-07-17 22:45:20 +02:00
zCfg . ConfigTypes = [ ] string { sdk . ZrokProxyConfig }
2023-05-25 17:50:38 +02:00
zCtx , err := ziti . NewContext ( zCfg )
if err != nil {
return nil , errors . Wrap ( err , "error loading ziti context" )
}
2023-03-07 18:57:35 +01:00
zDialCtx := zitiDialContext { ctx : zCtx }
2022-07-21 21:26:44 +02:00
zTransport := http . DefaultTransport . ( * http . Transport ) . Clone ( )
zTransport . DialContext = zDialCtx . Dial
2022-07-21 21:46:14 +02:00
2022-09-06 21:23:36 +02:00
proxy , err := newServiceProxy ( cfg , zCtx )
2022-07-20 20:36:14 +02:00
if err != nil {
2022-08-18 22:57:38 +02:00
return nil , err
2022-07-20 20:36:14 +02:00
}
2022-07-21 21:46:14 +02:00
proxy . Transport = zTransport
2023-09-05 16:55:55 +02:00
if err := configureOauthHandlers ( context . Background ( ) , cfg , false ) ; err != nil {
return nil , err
}
2023-09-28 20:39:31 +02:00
handler := authHandler ( util . NewProxyHandler ( proxy ) , cfg , key , zCtx )
2023-09-26 17:36:11 +02:00
return & HttpFrontend {
2022-08-18 22:57:38 +02:00
cfg : cfg ,
zCtx : zCtx ,
handler : handler ,
} , nil
}
2022-07-26 19:30:19 +02:00
2023-10-05 19:34:27 +02:00
func ( f * HttpFrontend ) Run ( ) error {
return http . ListenAndServe ( f . cfg . Address , f . handler )
2022-07-26 19:30:19 +02:00
}
2022-08-10 21:15:35 +02:00
2022-08-18 23:09:38 +02:00
type zitiDialContext struct {
2023-03-07 18:57:35 +01:00
ctx ziti . Context
2022-08-10 21:15:35 +02:00
}
2023-10-05 19:34:27 +02:00
func ( c * zitiDialContext ) Dial ( _ context . Context , _ string , addr string ) ( net . Conn , error ) {
2023-01-04 20:42:58 +01:00
shrToken := strings . Split ( addr , ":" ) [ 0 ] // ignore :port (we get passed 'host:port')
2023-10-05 19:34:27 +02:00
conn , err := c . ctx . Dial ( shrToken )
2022-10-10 22:15:40 +02:00
if err != nil {
return conn , err
}
2023-03-07 18:57:35 +01:00
return conn , nil
2022-08-10 21:15:35 +02:00
}
2022-09-06 21:23:36 +02:00
func newServiceProxy ( cfg * Config , ctx ziti . Context ) ( * httputil . ReverseProxy , error ) {
proxy := hostTargetReverseProxy ( cfg , ctx )
2022-08-10 21:15:35 +02:00
director := proxy . Director
proxy . Director = func ( req * http . Request ) {
director ( req )
req . Header . Set ( "X-Proxy" , "zrok" )
}
proxy . ModifyResponse = func ( resp * http . Response ) error {
return nil
}
proxy . ErrorHandler = func ( w http . ResponseWriter , r * http . Request , err error ) {
logrus . Errorf ( "error proxying: %v" , err )
2022-12-14 20:41:54 +01:00
notFoundUi . WriteNotFound ( w )
2022-08-10 21:15:35 +02:00
}
return proxy , nil
}
2022-09-06 21:23:36 +02:00
func hostTargetReverseProxy ( cfg * Config , ctx ziti . Context ) * httputil . ReverseProxy {
2022-08-10 21:15:35 +02:00
director := func ( req * http . Request ) {
2023-01-04 20:42:58 +01:00
targetShrToken := resolveService ( cfg . HostMatch , req . Host )
if svc , found := endpoints . GetRefreshedService ( targetShrToken , ctx ) ; found {
2023-07-17 22:45:20 +02:00
if cfg , found := svc . Config [ sdk . ZrokProxyConfig ] ; found {
2022-08-19 20:20:55 +02:00
logrus . Debugf ( "auth model: %v" , cfg )
2022-08-10 21:15:35 +02:00
} else {
2022-08-15 23:52:24 +02:00
logrus . Warn ( "no config!" )
2022-08-10 21:15:35 +02:00
}
2023-01-04 20:42:58 +01:00
if target , err := url . Parse ( fmt . Sprintf ( "http://%v" , targetShrToken ) ) ; err == nil {
logrus . Infof ( "[%v] -> %v" , targetShrToken , req . URL )
2022-08-19 20:20:55 +02:00
2022-08-15 23:52:24 +02:00
targetQuery := target . RawQuery
req . URL . Scheme = target . Scheme
req . URL . Host = target . Host
2022-11-23 17:58:45 +01:00
req . URL . Path , req . URL . RawPath = endpoints . JoinURLPath ( target , req . URL )
2022-08-15 23:52:24 +02:00
if targetQuery == "" || req . URL . RawQuery == "" {
req . URL . RawQuery = targetQuery + req . URL . RawQuery
} else {
req . URL . RawQuery = targetQuery + "&" + req . URL . RawQuery
}
if _ , ok := req . Header [ "User-Agent" ] ; ! ok {
// explicitly disable User-Agent so it's not set to default value
req . Header . Set ( "User-Agent" , "" )
}
} else {
logrus . Errorf ( "error proxying: %v" , err )
2022-08-10 21:15:35 +02:00
}
}
}
return & httputil . ReverseProxy { Director : director }
}
2023-09-28 20:39:31 +02:00
func authHandler ( handler http . Handler , pcfg * Config , key [ ] byte , ctx ziti . Context ) http . HandlerFunc {
2022-08-16 17:27:31 +02:00
return func ( w http . ResponseWriter , r * http . Request ) {
2023-09-05 16:55:55 +02:00
shrToken := resolveService ( pcfg . HostMatch , r . Host )
2023-01-04 20:42:58 +01:00
if shrToken != "" {
if svc , found := endpoints . GetRefreshedService ( shrToken , ctx ) ; found {
2023-07-17 22:45:20 +02:00
if cfg , found := svc . Config [ sdk . ZrokProxyConfig ] ; found {
2022-09-06 21:23:36 +02:00
if scheme , found := cfg [ "auth_scheme" ] ; found {
switch scheme {
2023-07-17 22:45:20 +02:00
case string ( sdk . None ) :
2023-01-04 20:42:58 +01:00
logrus . Debugf ( "auth scheme none '%v'" , shrToken )
2024-01-09 21:34:37 +01:00
// ensure cookies from other shares are not sent to this share, in case it's malicious
deleteZrokCookies ( w , r )
2022-09-06 21:23:36 +02:00
handler . ServeHTTP ( w , r )
2022-08-16 17:41:04 +02:00
return
2022-09-06 21:23:36 +02:00
2023-07-17 22:45:20 +02:00
case string ( sdk . Basic ) :
2023-01-04 20:42:58 +01:00
logrus . Debugf ( "auth scheme basic '%v" , shrToken )
2022-09-06 21:23:36 +02:00
inUser , inPass , ok := r . BasicAuth ( )
if ! ok {
2023-09-26 17:36:11 +02:00
basicAuthRequired ( w , shrToken )
2022-09-06 21:23:36 +02:00
return
}
authed := false
if v , found := cfg [ "basic_auth" ] ; found {
if basicAuth , ok := v . ( map [ string ] interface { } ) ; ok {
if v , found := basicAuth [ "users" ] ; found {
if arr , ok := v . ( [ ] interface { } ) ; ok {
for _ , v := range arr {
if um , ok := v . ( map [ string ] interface { } ) ; ok {
username := ""
if v , found := um [ "username" ] ; found {
if un , ok := v . ( string ) ; ok {
username = un
}
2022-08-16 19:16:44 +02:00
}
2022-09-06 21:23:36 +02:00
password := ""
if v , found := um [ "password" ] ; found {
if pw , ok := v . ( string ) ; ok {
password = pw
}
}
if username == inUser && password == inPass {
authed = true
break
2022-08-16 19:16:44 +02:00
}
}
}
}
}
}
2022-08-16 17:41:04 +02:00
}
2022-08-16 19:16:44 +02:00
2022-09-06 21:23:36 +02:00
if ! authed {
2023-09-26 17:36:11 +02:00
basicAuthRequired ( w , shrToken )
2022-09-06 21:23:36 +02:00
return
}
2022-09-07 18:22:22 +02:00
2024-01-09 21:34:37 +01:00
// ensure cookies from other shares are not sent to this share, in case it's malicious
deleteZrokCookies ( w , r )
2022-09-06 21:23:36 +02:00
handler . ServeHTTP ( w , r )
2023-09-05 17:10:25 +02:00
case string ( sdk . Oauth ) :
2023-09-28 20:39:31 +02:00
logrus . Debugf ( "auth scheme oauth '%v'" , shrToken )
2023-09-26 19:42:41 +02:00
2023-09-05 16:55:55 +02:00
if oauthCfg , found := cfg [ "oauth" ] ; found {
if provider , found := oauthCfg . ( map [ string ] interface { } ) [ "provider" ] ; found {
2023-09-05 18:50:41 +02:00
var authCheckInterval time . Duration
if checkInterval , found := oauthCfg . ( map [ string ] interface { } ) [ "authorization_check_interval" ] ; ! found {
2023-12-15 18:15:40 +01:00
logrus . Errorf ( "missing authorization check interval in share config. Defaulting to 3 hours" )
2023-09-05 18:50:41 +02:00
authCheckInterval = 3 * time . Hour
} else {
i , err := time . ParseDuration ( checkInterval . ( string ) )
if err != nil {
logrus . Errorf ( "unable to parse authorization check interval in share config (%v). Defaulting to 3 hours" , checkInterval )
authCheckInterval = 3 * time . Hour
} else {
authCheckInterval = i
}
}
2023-09-13 17:37:38 +02:00
target := fmt . Sprintf ( "%s%s" , r . Host , r . URL . Path )
2023-09-05 16:55:55 +02:00
cookie , err := r . Cookie ( "zrok-access" )
if err != nil {
2023-09-26 19:42:41 +02:00
logrus . Errorf ( "unable to get 'zrok-access' cookie: %v" , err )
2023-10-18 17:47:26 +02:00
oauthLoginRequired ( w , r , pcfg . Oauth , provider . ( string ) , target , authCheckInterval )
2023-09-05 16:55:55 +02:00
return
}
tkn , err := jwt . ParseWithClaims ( cookie . Value , & ZrokClaims { } , func ( t * jwt . Token ) ( interface { } , error ) {
if pcfg . Oauth == nil {
2023-09-26 19:42:41 +02:00
return nil , fmt . Errorf ( "missing oauth configuration for access point; unable to parse jwt" )
2023-09-05 16:55:55 +02:00
}
2023-09-28 20:39:31 +02:00
return key , nil
2023-09-05 16:55:55 +02:00
} )
if err != nil {
2023-09-26 19:42:41 +02:00
logrus . Errorf ( "unable to parse jwt: %v" , err )
2023-10-18 17:47:26 +02:00
oauthLoginRequired ( w , r , pcfg . Oauth , provider . ( string ) , target , authCheckInterval )
2023-09-05 16:55:55 +02:00
return
}
claims := tkn . Claims . ( * ZrokClaims )
if claims . Provider != provider {
2023-09-26 19:42:41 +02:00
logrus . Error ( "provider mismatch; restarting auth flow" )
2023-10-18 17:47:26 +02:00
oauthLoginRequired ( w , r , pcfg . Oauth , provider . ( string ) , target , authCheckInterval )
2023-09-05 16:55:55 +02:00
return
}
if claims . AuthorizationCheckInterval != authCheckInterval {
2023-09-26 19:42:41 +02:00
logrus . Error ( "authorization check interval mismatch; restarting auth flow" )
2023-10-18 17:47:26 +02:00
oauthLoginRequired ( w , r , pcfg . Oauth , provider . ( string ) , target , authCheckInterval )
2023-09-05 16:55:55 +02:00
return
}
2023-12-15 18:13:30 +01:00
if claims . Audience != r . Host {
logrus . Errorf ( "audience claim '%s' does not match requested host '%s'; restarting auth flow" , claims . Audience , r . Host )
oauthLoginRequired ( w , r , pcfg . Oauth , provider . ( string ) , target , authCheckInterval )
return
}
2023-09-05 16:55:55 +02:00
if validDomains , found := oauthCfg . ( map [ string ] interface { } ) [ "email_domains" ] ; found {
if castedDomains , ok := validDomains . ( [ ] interface { } ) ; ! ok {
2023-09-26 19:42:41 +02:00
logrus . Error ( "invalid email domain format" )
2023-09-05 16:55:55 +02:00
return
} else {
if len ( castedDomains ) > 0 {
found := false
for _ , domain := range castedDomains {
if strings . HasSuffix ( claims . Email , domain . ( string ) ) {
found = true
break
}
}
if ! found {
2023-09-26 19:42:41 +02:00
logrus . Warnf ( "invalid email domain" )
2023-09-05 16:55:55 +02:00
unauthorizedUi . WriteUnauthorized ( w )
return
}
}
}
}
handler . ServeHTTP ( w , r )
return
2023-09-26 19:42:41 +02:00
2023-09-05 16:55:55 +02:00
} else {
logrus . Warnf ( "%v -> no provider for '%v'" , r . RemoteAddr , provider )
notFoundUi . WriteNotFound ( w )
}
} else {
logrus . Warnf ( "%v -> no oauth cfg for '%v'" , r . RemoteAddr , shrToken )
notFoundUi . WriteNotFound ( w )
}
2022-09-06 21:23:36 +02:00
default :
logrus . Infof ( "invalid auth scheme '%v'" , scheme )
2023-09-26 17:36:11 +02:00
basicAuthRequired ( w , shrToken )
2022-08-16 17:41:04 +02:00
return
}
2022-09-06 21:23:36 +02:00
} else {
2023-01-04 20:42:58 +01:00
logrus . Warnf ( "%v -> no auth scheme for '%v'" , r . RemoteAddr , shrToken )
2022-12-14 20:41:54 +01:00
notFoundUi . WriteNotFound ( w )
2022-08-16 17:41:04 +02:00
}
2022-08-16 19:16:44 +02:00
} else {
2023-01-04 20:42:58 +01:00
logrus . Warnf ( "%v -> no proxy config for '%v'" , r . RemoteAddr , shrToken )
2022-12-14 20:41:54 +01:00
notFoundUi . WriteNotFound ( w )
2022-08-16 17:41:04 +02:00
}
2022-08-16 19:16:44 +02:00
} else {
2023-01-04 20:42:58 +01:00
logrus . Warnf ( "%v -> service '%v' not found" , r . RemoteAddr , shrToken )
2022-12-14 20:41:54 +01:00
notFoundUi . WriteNotFound ( w )
2022-08-16 17:27:31 +02:00
}
2022-08-16 19:16:44 +02:00
} else {
2022-09-09 16:01:24 +02:00
logrus . Debugf ( "host '%v' did not match host match, returning health check" , r . Host )
2022-12-14 20:41:54 +01:00
healthUi . WriteHealthOk ( w )
2022-08-16 17:27:31 +02:00
}
}
}
2023-09-05 16:55:55 +02:00
type ZrokClaims struct {
Email string ` json:"email" `
AccessToken string ` json:"accessToken" `
Provider string ` json:"provider" `
2023-12-15 18:13:30 +01:00
Audience string ` json:"aud" `
2023-09-05 16:55:55 +02:00
AuthorizationCheckInterval time . Duration ` json:"authorizationCheckInterval" `
jwt . RegisteredClaims
}
2023-12-15 18:13:30 +01:00
func SetZrokCookie ( w http . ResponseWriter , cookieDomain , email , accessToken , provider string , checkInterval time . Duration , key [ ] byte , targetHost string ) {
targetHost = strings . TrimSpace ( targetHost )
if targetHost == "" {
logrus . Error ( "host claim must not be empty" )
http . Error ( w , "host claim must not be empty" , http . StatusBadRequest )
return
}
targetHost = strings . Split ( targetHost , "/" ) [ 0 ]
logrus . Debugf ( "setting zrok-access cookie JWT audience '%s'" , targetHost )
2023-09-05 16:55:55 +02:00
tkn := jwt . NewWithClaims ( jwt . SigningMethodHS256 , ZrokClaims {
Email : email ,
AccessToken : accessToken ,
Provider : provider ,
2023-12-15 18:13:30 +01:00
Audience : targetHost ,
2023-09-05 16:55:55 +02:00
AuthorizationCheckInterval : checkInterval ,
} )
sTkn , err := tkn . SignedString ( key )
if err != nil {
2023-09-26 19:42:41 +02:00
http . Error ( w , fmt . Sprintf ( "after signing cookie token: %v" , err . Error ( ) ) , http . StatusInternalServerError )
2023-09-05 16:55:55 +02:00
return
}
http . SetCookie ( w , & http . Cookie {
Name : "zrok-access" ,
Value : sTkn ,
2023-09-05 18:50:41 +02:00
MaxAge : int ( checkInterval . Seconds ( ) ) ,
2023-12-15 18:13:30 +01:00
Domain : cookieDomain ,
2023-09-05 16:55:55 +02:00
Path : "/" ,
Expires : time . Now ( ) . Add ( checkInterval ) ,
2023-12-15 18:13:30 +01:00
// Secure: true, // pending server tls feature https://github.com/openziti/zrok/issues/24
HttpOnly : true , // enabled because zrok frontend is the only intended consumer of this cookie, not client-side scripts
SameSite : http . SameSiteLaxMode , // explicitly set to the default Lax mode which allows the zrok share to be navigated to from another site and receive the cookie
2023-09-05 16:55:55 +02:00
} )
}
2024-01-09 21:34:37 +01:00
func deleteZrokCookies ( w http . ResponseWriter , r * http . Request ) {
// Get all cookies from the request
cookies := r . Cookies ( )
2024-01-09 22:30:47 +01:00
// Clear the Cookie header
r . Header . Del ( "Cookie" )
// Save cookies not in the list of cookies to delete, the pkce cookie might be okay to pass along to the HTTP
// backend, but zrok-access is not because it can contain the accessToken from any other OAuth enabled shares, so we
// delete it here when the current share is not OAuth-enabled. OAuth-enabled shares check the audience claim in the
// JWT to ensure it matches the requested share and will send the client back to the OAuth provider if it does not
// match.
2024-01-09 21:34:37 +01:00
for _ , cookie := range cookies {
2024-01-09 22:46:22 +01:00
if cookie . Name != "zrok-access" && cookie . Name != "pkce" {
2024-01-09 22:30:47 +01:00
r . AddCookie ( cookie )
2024-01-09 21:34:37 +01:00
}
}
2024-01-09 19:05:37 +01:00
}
2023-09-26 17:36:11 +02:00
func basicAuthRequired ( w http . ResponseWriter , realm string ) {
2022-08-16 17:27:31 +02:00
w . Header ( ) . Set ( "WWW-Authenticate" , ` Basic realm=" ` + realm + ` " ` )
w . WriteHeader ( 401 )
2023-10-05 19:34:27 +02:00
_ , _ = w . Write ( [ ] byte ( "No Authorization\n" ) )
2022-08-16 17:27:31 +02:00
}
2022-08-18 22:57:38 +02:00
2023-10-18 17:47:26 +02:00
func oauthLoginRequired ( w http . ResponseWriter , r * http . Request , cfg * OauthConfig , provider , target string , authCheckInterval time . Duration ) {
http . Redirect ( w , r , fmt . Sprintf ( "%s/%s/login?targethost=%s&checkInterval=%s" , cfg . RedirectUrl , provider , url . QueryEscape ( target ) , authCheckInterval . String ( ) ) , http . StatusFound )
2023-09-26 19:42:41 +02:00
}
2022-09-06 21:23:36 +02:00
func resolveService ( hostMatch string , host string ) string {
2022-09-07 18:22:22 +02:00
if hostMatch == "" || strings . Contains ( host , hostMatch ) {
2022-09-06 21:23:36 +02:00
tokens := strings . Split ( host , "." )
if len ( tokens ) > 0 {
return tokens [ 0 ]
}
2022-08-18 22:57:38 +02:00
}
2022-09-06 21:23:36 +02:00
return ""
2022-08-18 22:57:38 +02:00
}