| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551 | 
							- package httpd
 
- import (
 
- 	"context"
 
- 	"crypto/tls"
 
- 	"crypto/x509"
 
- 	"errors"
 
- 	"fmt"
 
- 	"log"
 
- 	"net"
 
- 	"net/http"
 
- 	"strings"
 
- 	"time"
 
- 	"github.com/go-chi/chi/v5"
 
- 	"github.com/go-chi/chi/v5/middleware"
 
- 	"github.com/go-chi/jwtauth/v5"
 
- 	"github.com/go-chi/render"
 
- 	"github.com/lestrrat-go/jwx/jwa"
 
- 	"github.com/rs/cors"
 
- 	"github.com/rs/xid"
 
- 	"github.com/sftpgo/sdk"
 
- 	"github.com/unrolled/secure"
 
- 	"github.com/drakkan/sftpgo/v2/common"
 
- 	"github.com/drakkan/sftpgo/v2/dataprovider"
 
- 	"github.com/drakkan/sftpgo/v2/logger"
 
- 	"github.com/drakkan/sftpgo/v2/mfa"
 
- 	"github.com/drakkan/sftpgo/v2/smtp"
 
- 	"github.com/drakkan/sftpgo/v2/util"
 
- 	"github.com/drakkan/sftpgo/v2/version"
 
- )
 
- var (
 
- 	compressor      = middleware.NewCompressor(5)
 
- 	xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto")
 
- )
 
- type httpdServer struct {
 
- 	binding           Binding
 
- 	staticFilesPath   string
 
- 	openAPIPath       string
 
- 	enableWebAdmin    bool
 
- 	enableWebClient   bool
 
- 	renderOpenAPI     bool
 
- 	router            *chi.Mux
 
- 	tokenAuth         *jwtauth.JWTAuth
 
- 	signingPassphrase string
 
- 	cors              CorsConfig
 
- }
 
- func newHttpdServer(b Binding, staticFilesPath, signingPassphrase string, cors CorsConfig,
 
- 	openAPIPath string,
 
- ) *httpdServer {
 
- 	if openAPIPath == "" {
 
- 		b.RenderOpenAPI = false
 
- 	}
 
- 	return &httpdServer{
 
- 		binding:           b,
 
- 		staticFilesPath:   staticFilesPath,
 
- 		openAPIPath:       openAPIPath,
 
- 		enableWebAdmin:    b.EnableWebAdmin,
 
- 		enableWebClient:   b.EnableWebClient,
 
- 		renderOpenAPI:     b.RenderOpenAPI,
 
- 		signingPassphrase: signingPassphrase,
 
- 		cors:              cors,
 
- 	}
 
- }
 
- func (s *httpdServer) listenAndServe() error {
 
- 	s.initializeRouter()
 
- 	httpServer := &http.Server{
 
- 		Handler:           s.router,
 
- 		ReadHeaderTimeout: 30 * time.Second,
 
- 		ReadTimeout:       60 * time.Second,
 
- 		WriteTimeout:      60 * time.Second,
 
- 		IdleTimeout:       60 * time.Second,
 
- 		MaxHeaderBytes:    1 << 16, // 64KB
 
- 		ErrorLog:          log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
 
- 	}
 
- 	if certMgr != nil && s.binding.EnableHTTPS {
 
- 		config := &tls.Config{
 
- 			GetCertificate:           certMgr.GetCertificateFunc(),
 
- 			MinVersion:               util.GetTLSVersion(s.binding.MinTLSVersion),
 
- 			NextProtos:               []string{"http/1.1", "h2"},
 
- 			CipherSuites:             util.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
 
- 			PreferServerCipherSuites: true,
 
- 		}
 
- 		logger.Debug(logSender, "", "configured TLS cipher suites for binding %#v: %v", s.binding.GetAddress(),
 
- 			config.CipherSuites)
 
- 		httpServer.TLSConfig = config
 
- 		if s.binding.ClientAuthType == 1 {
 
- 			httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
 
- 			httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
 
- 			httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
 
- 		}
 
- 		return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, true, logSender)
 
- 	}
 
- 	return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, false, logSender)
 
- }
 
- func (s *httpdServer) verifyTLSConnection(state tls.ConnectionState) error {
 
- 	if certMgr != nil {
 
- 		var clientCrt *x509.Certificate
 
- 		var clientCrtName string
 
- 		if len(state.PeerCertificates) > 0 {
 
- 			clientCrt = state.PeerCertificates[0]
 
- 			clientCrtName = clientCrt.Subject.String()
 
- 		}
 
- 		if len(state.VerifiedChains) == 0 {
 
- 			logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
 
- 			return errors.New("TLS connection cannot be verified: unable to get verification chain")
 
- 		}
 
- 		for _, verifiedChain := range state.VerifiedChains {
 
- 			var caCrt *x509.Certificate
 
- 			if len(verifiedChain) > 0 {
 
- 				caCrt = verifiedChain[len(verifiedChain)-1]
 
- 			}
 
- 			if certMgr.IsRevoked(clientCrt, caCrt) {
 
- 				logger.Debug(logSender, "", "tls handshake error, client certificate %#v has been revoked", clientCrtName)
 
- 				return common.ErrCrtRevoked
 
- 			}
 
- 		}
 
- 	}
 
- 	return nil
 
- }
 
- func (s *httpdServer) refreshCookie(next http.Handler) http.Handler {
 
- 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 
- 		s.checkCookieExpiration(w, r)
 
- 		next.ServeHTTP(w, r)
 
- 	})
 
- }
 
- func (s *httpdServer) renderClientLoginPage(w http.ResponseWriter, error string) {
 
- 	data := loginPage{
 
- 		CurrentURL: webClientLoginPath,
 
- 		Version:    version.Get().Version,
 
- 		Error:      error,
 
- 		CSRFToken:  createCSRFToken(),
 
- 		StaticURL:  webStaticFilesPath,
 
- 	}
 
- 	if s.binding.showAdminLoginURL() {
 
- 		data.AltLoginURL = webAdminLoginPath
 
- 	}
 
- 	if smtp.IsEnabled() {
 
- 		data.ForgotPwdURL = webClientForgotPwdPath
 
- 	}
 
- 	if s.binding.OIDC.isEnabled() {
 
- 		data.OpenIDLoginURL = webClientOIDCLoginPath
 
- 	}
 
- 	renderClientTemplate(w, templateClientLogin, data)
 
- }
 
- func (s *httpdServer) handleWebClientLogout(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	c := jwtTokenClaims{}
 
- 	c.removeCookie(w, r, webBaseClientPath)
 
- 	s.logoutOIDCUser(w, r)
 
- 	http.Redirect(w, r, webClientLoginPath, http.StatusFound)
 
- }
 
- func (s *httpdServer) handleWebClientChangePwdPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 	err := r.ParseForm()
 
- 	if err != nil {
 
- 		renderClientChangePasswordPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderClientForbiddenPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	err = doChangeUserPassword(r, r.Form.Get("current_password"), r.Form.Get("new_password1"),
 
- 		r.Form.Get("new_password2"))
 
- 	if err != nil {
 
- 		renderClientChangePasswordPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	s.handleWebClientLogout(w, r)
 
- }
 
- func (s *httpdServer) handleClientWebLogin(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	if !dataprovider.HasAdmin() {
 
- 		http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
 
- 		return
 
- 	}
 
- 	s.renderClientLoginPage(w, getFlashMessage(w, r))
 
- }
 
- func (s *httpdServer) handleWebClientLoginPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	if err := r.ParseForm(); err != nil {
 
- 		s.renderClientLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
 
- 	protocol := common.ProtocolHTTP
 
- 	username := r.Form.Get("username")
 
- 	password := r.Form.Get("password")
 
- 	if username == "" || password == "" {
 
- 		updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
 
- 			dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
 
- 		s.renderClientLoginPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
 
- 			dataprovider.LoginMethodPassword, ipAddr, err)
 
- 		s.renderClientLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	if err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
 
- 		s.renderClientLoginPage(w, fmt.Sprintf("access denied by post connect hook: %v", err))
 
- 		return
 
- 	}
 
- 	user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
 
- 	if err != nil {
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
 
- 		s.renderClientLoginPage(w, dataprovider.ErrInvalidCredentials.Error())
 
- 		return
 
- 	}
 
- 	connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
 
- 	if err := checkHTTPClientUser(&user, r, connectionID); err != nil {
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
 
- 		s.renderClientLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	defer user.CloseFs() //nolint:errcheck
 
- 	err = user.CheckFsRoot(connectionID)
 
- 	if err != nil {
 
- 		logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
 
- 		s.renderClientLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	s.loginUser(w, r, &user, connectionID, ipAddr, false, s.renderClientLoginPage)
 
- }
 
- func (s *httpdServer) handleWebClientPasswordResetPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	err := r.ParseForm()
 
- 	if err != nil {
 
- 		renderClientResetPwdPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderClientForbiddenPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	_, user, err := handleResetPassword(r, r.Form.Get("code"), r.Form.Get("password"), false)
 
- 	if err != nil {
 
- 		if e, ok := err.(*util.ValidationError); ok {
 
- 			renderClientResetPwdPage(w, e.GetErrorString())
 
- 			return
 
- 		}
 
- 		renderClientResetPwdPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
 
- 	if err := checkHTTPClientUser(user, r, connectionID); err != nil {
 
- 		renderClientResetPwdPage(w, fmt.Sprintf("Password reset successfully but unable to login: %v", err.Error()))
 
- 		return
 
- 	}
 
- 	defer user.CloseFs() //nolint:errcheck
 
- 	err = user.CheckFsRoot(connectionID)
 
- 	if err != nil {
 
- 		logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
 
- 		renderClientResetPwdPage(w, fmt.Sprintf("Password reset successfully but unable to login: %v", err.Error()))
 
- 		return
 
- 	}
 
- 	ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
 
- 	s.loginUser(w, r, user, connectionID, ipAddr, false, renderClientResetPwdPage)
 
- }
 
- func (s *httpdServer) handleWebClientTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	claims, err := getTokenClaims(r)
 
- 	if err != nil {
 
- 		renderNotFoundPage(w, r, nil)
 
- 		return
 
- 	}
 
- 	if err := r.ParseForm(); err != nil {
 
- 		renderClientTwoFactorRecoveryPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	username := claims.Username
 
- 	recoveryCode := r.Form.Get("recovery_code")
 
- 	if username == "" || recoveryCode == "" {
 
- 		renderClientTwoFactorRecoveryPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderClientTwoFactorRecoveryPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	user, err := dataprovider.UserExists(username)
 
- 	if err != nil {
 
- 		renderClientTwoFactorRecoveryPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if !user.Filters.TOTPConfig.Enabled || !util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
 
- 		renderClientTwoFactorPage(w, "Two factory authentication is not enabled")
 
- 		return
 
- 	}
 
- 	for idx, code := range user.Filters.RecoveryCodes {
 
- 		if err := code.Secret.Decrypt(); err != nil {
 
- 			renderClientInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
 
- 			return
 
- 		}
 
- 		if code.Secret.GetPayload() == recoveryCode {
 
- 			if code.Used {
 
- 				renderClientTwoFactorRecoveryPage(w, "This recovery code was already used")
 
- 				return
 
- 			}
 
- 			user.Filters.RecoveryCodes[idx].Used = true
 
- 			err = dataprovider.UpdateUser(&user, dataprovider.ActionExecutorSelf, util.GetIPFromRemoteAddress(r.RemoteAddr))
 
- 			if err != nil {
 
- 				logger.Warn(logSender, "", "unable to set the recovery code %#v as used: %v", recoveryCode, err)
 
- 				renderClientInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
 
- 				return
 
- 			}
 
- 			connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
 
- 			s.loginUser(w, r, &user, connectionID, util.GetIPFromRemoteAddress(r.RemoteAddr), true,
 
- 				renderClientTwoFactorRecoveryPage)
 
- 			return
 
- 		}
 
- 	}
 
- 	renderClientTwoFactorRecoveryPage(w, "Invalid recovery code")
 
- }
 
- func (s *httpdServer) handleWebClientTwoFactorPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	claims, err := getTokenClaims(r)
 
- 	if err != nil {
 
- 		renderNotFoundPage(w, r, nil)
 
- 		return
 
- 	}
 
- 	if err := r.ParseForm(); err != nil {
 
- 		renderClientTwoFactorPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	username := claims.Username
 
- 	passcode := r.Form.Get("passcode")
 
- 	if username == "" || passcode == "" {
 
- 		renderClientTwoFactorPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderClientTwoFactorPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	user, err := dataprovider.UserExists(username)
 
- 	if err != nil {
 
- 		renderClientTwoFactorPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if !user.Filters.TOTPConfig.Enabled || !util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
 
- 		renderClientTwoFactorPage(w, "Two factory authentication is not enabled")
 
- 		return
 
- 	}
 
- 	err = user.Filters.TOTPConfig.Secret.Decrypt()
 
- 	if err != nil {
 
- 		renderClientInternalServerErrorPage(w, r, err)
 
- 		return
 
- 	}
 
- 	match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
 
- 		user.Filters.TOTPConfig.Secret.GetPayload())
 
- 	if !match || err != nil {
 
- 		renderClientTwoFactorPage(w, "Invalid authentication code")
 
- 		return
 
- 	}
 
- 	connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
 
- 	s.loginUser(w, r, &user, connectionID, util.GetIPFromRemoteAddress(r.RemoteAddr), true, renderClientTwoFactorPage)
 
- }
 
- func (s *httpdServer) handleWebAdminTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	claims, err := getTokenClaims(r)
 
- 	if err != nil {
 
- 		renderNotFoundPage(w, r, nil)
 
- 		return
 
- 	}
 
- 	if err := r.ParseForm(); err != nil {
 
- 		renderTwoFactorRecoveryPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	username := claims.Username
 
- 	recoveryCode := r.Form.Get("recovery_code")
 
- 	if username == "" || recoveryCode == "" {
 
- 		renderTwoFactorRecoveryPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderTwoFactorRecoveryPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	admin, err := dataprovider.AdminExists(username)
 
- 	if err != nil {
 
- 		renderTwoFactorRecoveryPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if !admin.Filters.TOTPConfig.Enabled {
 
- 		renderTwoFactorRecoveryPage(w, "Two factory authentication is not enabled")
 
- 		return
 
- 	}
 
- 	for idx, code := range admin.Filters.RecoveryCodes {
 
- 		if err := code.Secret.Decrypt(); err != nil {
 
- 			renderInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
 
- 			return
 
- 		}
 
- 		if code.Secret.GetPayload() == recoveryCode {
 
- 			if code.Used {
 
- 				renderTwoFactorRecoveryPage(w, "This recovery code was already used")
 
- 				return
 
- 			}
 
- 			admin.Filters.RecoveryCodes[idx].Used = true
 
- 			err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, util.GetIPFromRemoteAddress(r.RemoteAddr))
 
- 			if err != nil {
 
- 				logger.Warn(logSender, "", "unable to set the recovery code %#v as used: %v", recoveryCode, err)
 
- 				renderInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
 
- 				return
 
- 			}
 
- 			s.loginAdmin(w, r, &admin, true, renderTwoFactorRecoveryPage)
 
- 			return
 
- 		}
 
- 	}
 
- 	renderTwoFactorRecoveryPage(w, "Invalid recovery code")
 
- }
 
- func (s *httpdServer) handleWebAdminTwoFactorPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	claims, err := getTokenClaims(r)
 
- 	if err != nil {
 
- 		renderNotFoundPage(w, r, nil)
 
- 		return
 
- 	}
 
- 	if err := r.ParseForm(); err != nil {
 
- 		renderTwoFactorPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	username := claims.Username
 
- 	passcode := r.Form.Get("passcode")
 
- 	if username == "" || passcode == "" {
 
- 		renderTwoFactorPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderTwoFactorPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	admin, err := dataprovider.AdminExists(username)
 
- 	if err != nil {
 
- 		renderTwoFactorPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if !admin.Filters.TOTPConfig.Enabled {
 
- 		renderTwoFactorPage(w, "Two factory authentication is not enabled")
 
- 		return
 
- 	}
 
- 	err = admin.Filters.TOTPConfig.Secret.Decrypt()
 
- 	if err != nil {
 
- 		renderInternalServerErrorPage(w, r, err)
 
- 		return
 
- 	}
 
- 	match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
 
- 		admin.Filters.TOTPConfig.Secret.GetPayload())
 
- 	if !match || err != nil {
 
- 		renderTwoFactorPage(w, "Invalid authentication code")
 
- 		return
 
- 	}
 
- 	s.loginAdmin(w, r, &admin, true, renderTwoFactorPage)
 
- }
 
- func (s *httpdServer) handleWebAdminLoginPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	if err := r.ParseForm(); err != nil {
 
- 		s.renderAdminLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	username := r.Form.Get("username")
 
- 	password := r.Form.Get("password")
 
- 	if username == "" || password == "" {
 
- 		s.renderAdminLoginPage(w, "Invalid credentials")
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		s.renderAdminLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	admin, err := dataprovider.CheckAdminAndPass(username, password, util.GetIPFromRemoteAddress(r.RemoteAddr))
 
- 	if err != nil {
 
- 		s.renderAdminLoginPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	s.loginAdmin(w, r, &admin, false, s.renderAdminLoginPage)
 
- }
 
- func (s *httpdServer) renderAdminLoginPage(w http.ResponseWriter, error string) {
 
- 	data := loginPage{
 
- 		CurrentURL: webAdminLoginPath,
 
- 		Version:    version.Get().Version,
 
- 		Error:      error,
 
- 		CSRFToken:  createCSRFToken(),
 
- 		StaticURL:  webStaticFilesPath,
 
- 	}
 
- 	if s.binding.showClientLoginURL() {
 
- 		data.AltLoginURL = webClientLoginPath
 
- 	}
 
- 	if smtp.IsEnabled() {
 
- 		data.ForgotPwdURL = webAdminForgotPwdPath
 
- 	}
 
- 	if s.binding.OIDC.hasRoles() {
 
- 		data.OpenIDLoginURL = webAdminOIDCLoginPath
 
- 	}
 
- 	renderAdminTemplate(w, templateLogin, data)
 
- }
 
- func (s *httpdServer) handleWebAdminLogin(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	if !dataprovider.HasAdmin() {
 
- 		http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
 
- 		return
 
- 	}
 
- 	s.renderAdminLoginPage(w, getFlashMessage(w, r))
 
- }
 
- func (s *httpdServer) handleWebAdminLogout(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 	c := jwtTokenClaims{}
 
- 	c.removeCookie(w, r, webBaseAdminPath)
 
- 	s.logoutOIDCUser(w, r)
 
- 	http.Redirect(w, r, webAdminLoginPath, http.StatusFound)
 
- }
 
- func (s *httpdServer) handleWebAdminChangePwdPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 	err := r.ParseForm()
 
- 	if err != nil {
 
- 		renderChangePasswordPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderForbiddenPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	err = doChangeAdminPassword(r, r.Form.Get("current_password"), r.Form.Get("new_password1"),
 
- 		r.Form.Get("new_password2"))
 
- 	if err != nil {
 
- 		renderChangePasswordPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	s.handleWebAdminLogout(w, r)
 
- }
 
- func (s *httpdServer) handleWebAdminPasswordResetPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	err := r.ParseForm()
 
- 	if err != nil {
 
- 		renderResetPwdPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderForbiddenPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	admin, _, err := handleResetPassword(r, r.Form.Get("code"), r.Form.Get("password"), true)
 
- 	if err != nil {
 
- 		if e, ok := err.(*util.ValidationError); ok {
 
- 			renderResetPwdPage(w, e.GetErrorString())
 
- 			return
 
- 		}
 
- 		renderResetPwdPage(w, err.Error())
 
- 		return
 
- 	}
 
- 	s.loginAdmin(w, r, admin, false, renderResetPwdPage)
 
- }
 
- func (s *httpdServer) handleWebAdminSetupPost(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	if dataprovider.HasAdmin() {
 
- 		renderBadRequestPage(w, r, errors.New("an admin user already exists"))
 
- 		return
 
- 	}
 
- 	err := r.ParseForm()
 
- 	if err != nil {
 
- 		renderAdminSetupPage(w, r, "", err.Error())
 
- 		return
 
- 	}
 
- 	if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
 
- 		renderForbiddenPage(w, r, err.Error())
 
- 		return
 
- 	}
 
- 	username := r.Form.Get("username")
 
- 	password := r.Form.Get("password")
 
- 	confirmPassword := r.Form.Get("confirm_password")
 
- 	installCode := r.Form.Get("install_code")
 
- 	if installationCode != "" && installCode != installationCode {
 
- 		renderAdminSetupPage(w, r, username, fmt.Sprintf("%v mismatch", installationCodeHint))
 
- 		return
 
- 	}
 
- 	if username == "" {
 
- 		renderAdminSetupPage(w, r, username, "Please set a username")
 
- 		return
 
- 	}
 
- 	if password == "" {
 
- 		renderAdminSetupPage(w, r, username, "Please set a password")
 
- 		return
 
- 	}
 
- 	if password != confirmPassword {
 
- 		renderAdminSetupPage(w, r, username, "Passwords mismatch")
 
- 		return
 
- 	}
 
- 	admin := dataprovider.Admin{
 
- 		Username:    username,
 
- 		Password:    password,
 
- 		Status:      1,
 
- 		Permissions: []string{dataprovider.PermAdminAny},
 
- 	}
 
- 	err = dataprovider.AddAdmin(&admin, username, util.GetIPFromRemoteAddress(r.RemoteAddr))
 
- 	if err != nil {
 
- 		renderAdminSetupPage(w, r, username, err.Error())
 
- 		return
 
- 	}
 
- 	s.loginAdmin(w, r, &admin, false, nil)
 
- }
 
- func (s *httpdServer) loginUser(
 
- 	w http.ResponseWriter, r *http.Request, user *dataprovider.User, connectionID, ipAddr string,
 
- 	isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, error string),
 
- ) {
 
- 	c := jwtTokenClaims{
 
- 		Username:                   user.Username,
 
- 		Permissions:                user.Filters.WebClient,
 
- 		Signature:                  user.GetSignature(),
 
- 		MustSetTwoFactorAuth:       user.MustSetSecondFactor(),
 
- 		RequiredTwoFactorProtocols: user.Filters.TwoFactorAuthProtocols,
 
- 	}
 
- 	audience := tokenAudienceWebClient
 
- 	if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) &&
 
- 		user.CanManageMFA() && !isSecondFactorAuth {
 
- 		audience = tokenAudienceWebClientPartial
 
- 	}
 
- 	err := c.createAndSetCookie(w, r, s.tokenAuth, audience)
 
- 	if err != nil {
 
- 		logger.Warn(logSender, connectionID, "unable to set user login cookie %v", err)
 
- 		updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
 
- 		errorFunc(w, err.Error())
 
- 		return
 
- 	}
 
- 	if isSecondFactorAuth {
 
- 		invalidateToken(r)
 
- 	}
 
- 	if audience == tokenAudienceWebClientPartial {
 
- 		http.Redirect(w, r, webClientTwoFactorPath, http.StatusFound)
 
- 		return
 
- 	}
 
- 	updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, err)
 
- 	dataprovider.UpdateLastLogin(user)
 
- 	http.Redirect(w, r, webClientFilesPath, http.StatusFound)
 
- }
 
- func (s *httpdServer) loginAdmin(
 
- 	w http.ResponseWriter, r *http.Request, admin *dataprovider.Admin,
 
- 	isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, error string),
 
- ) {
 
- 	c := jwtTokenClaims{
 
- 		Username:    admin.Username,
 
- 		Permissions: admin.Permissions,
 
- 		Signature:   admin.GetSignature(),
 
- 	}
 
- 	audience := tokenAudienceWebAdmin
 
- 	if admin.Filters.TOTPConfig.Enabled && admin.CanManageMFA() && !isSecondFactorAuth {
 
- 		audience = tokenAudienceWebAdminPartial
 
- 	}
 
- 	err := c.createAndSetCookie(w, r, s.tokenAuth, audience)
 
- 	if err != nil {
 
- 		logger.Warn(logSender, "", "unable to set admin login cookie %v", err)
 
- 		if errorFunc == nil {
 
- 			renderAdminSetupPage(w, r, admin.Username, err.Error())
 
- 			return
 
- 		}
 
- 		errorFunc(w, err.Error())
 
- 		return
 
- 	}
 
- 	if isSecondFactorAuth {
 
- 		invalidateToken(r)
 
- 	}
 
- 	if audience == tokenAudienceWebAdminPartial {
 
- 		http.Redirect(w, r, webAdminTwoFactorPath, http.StatusFound)
 
- 		return
 
- 	}
 
- 	dataprovider.UpdateAdminLastLogin(admin)
 
- 	http.Redirect(w, r, webUsersPath, http.StatusFound)
 
- }
 
- func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	invalidateToken(r)
 
- 	sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
 
- }
 
- func (s *httpdServer) getUserToken(w http.ResponseWriter, r *http.Request) {
 
- 	r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 	ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
 
- 	username, password, ok := r.BasicAuth()
 
- 	protocol := common.ProtocolHTTP
 
- 	if !ok {
 
- 		updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
 
- 			dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
 
- 		w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 		sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
 
- 		return
 
- 	}
 
- 	if username == "" || password == "" {
 
- 		updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
 
- 			dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
 
- 		w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 		sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
 
- 		return
 
- 	}
 
- 	if err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
 
- 		sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
 
- 		return
 
- 	}
 
- 	user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
 
- 	if err != nil {
 
- 		w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
 
- 		sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
 
- 			http.StatusUnauthorized)
 
- 		return
 
- 	}
 
- 	connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
 
- 	if err := checkHTTPClientUser(&user, r, connectionID); err != nil {
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
 
- 		sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
 
- 		return
 
- 	}
 
- 	if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
 
- 		passcode := r.Header.Get(otpHeaderCode)
 
- 		if passcode == "" {
 
- 			logger.Debug(logSender, "", "TOTP enabled for user %#v and not passcode provided, authentication refused", user.Username)
 
- 			w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 			updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
 
- 			sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
 
- 				http.StatusUnauthorized)
 
- 			return
 
- 		}
 
- 		err = user.Filters.TOTPConfig.Secret.Decrypt()
 
- 		if err != nil {
 
- 			updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
 
- 			sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err), http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
 
- 			return
 
- 		}
 
- 		match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
 
- 			user.Filters.TOTPConfig.Secret.GetPayload())
 
- 		if !match || err != nil {
 
- 			logger.Debug(logSender, "invalid passcode for user %#v, match? %v, err: %v", user.Username, match, err)
 
- 			w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 			updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
 
- 			sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
 
- 				http.StatusUnauthorized)
 
- 			return
 
- 		}
 
- 	}
 
- 	defer user.CloseFs() //nolint:errcheck
 
- 	err = user.CheckFsRoot(connectionID)
 
- 	if err != nil {
 
- 		logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
 
- 		sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
 
- 		return
 
- 	}
 
- 	s.generateAndSendUserToken(w, r, ipAddr, user)
 
- }
 
- func (s *httpdServer) generateAndSendUserToken(w http.ResponseWriter, r *http.Request, ipAddr string, user dataprovider.User) {
 
- 	c := jwtTokenClaims{
 
- 		Username:                   user.Username,
 
- 		Permissions:                user.Filters.WebClient,
 
- 		Signature:                  user.GetSignature(),
 
- 		MustSetTwoFactorAuth:       user.MustSetSecondFactor(),
 
- 		RequiredTwoFactorProtocols: user.Filters.TwoFactorAuthProtocols,
 
- 	}
 
- 	resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPIUser)
 
- 	if err != nil {
 
- 		updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
 
- 		sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
 
- 		return
 
- 	}
 
- 	updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
 
- 	dataprovider.UpdateLastLogin(&user)
 
- 	render.JSON(w, r, resp)
 
- }
 
- func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
 
- 	username, password, ok := r.BasicAuth()
 
- 	if !ok {
 
- 		w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 		sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
 
- 		return
 
- 	}
 
- 	admin, err := dataprovider.CheckAdminAndPass(username, password, util.GetIPFromRemoteAddress(r.RemoteAddr))
 
- 	if err != nil {
 
- 		w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 		sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
 
- 		return
 
- 	}
 
- 	if admin.Filters.TOTPConfig.Enabled {
 
- 		passcode := r.Header.Get(otpHeaderCode)
 
- 		if passcode == "" {
 
- 			logger.Debug(logSender, "", "TOTP enabled for admin %#v and not passcode provided, authentication refused", admin.Username)
 
- 			w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 			sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
 
- 			return
 
- 		}
 
- 		err = admin.Filters.TOTPConfig.Secret.Decrypt()
 
- 		if err != nil {
 
- 			sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err),
 
- 				http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
 
- 			return
 
- 		}
 
- 		match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
 
- 			admin.Filters.TOTPConfig.Secret.GetPayload())
 
- 		if !match || err != nil {
 
- 			logger.Debug(logSender, "invalid passcode for admin %#v, match? %v, err: %v", admin.Username, match, err)
 
- 			w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
 
- 			sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
 
- 				http.StatusUnauthorized)
 
- 			return
 
- 		}
 
- 	}
 
- 	s.generateAndSendToken(w, r, admin)
 
- }
 
- func (s *httpdServer) generateAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin) {
 
- 	c := jwtTokenClaims{
 
- 		Username:    admin.Username,
 
- 		Permissions: admin.Permissions,
 
- 		Signature:   admin.GetSignature(),
 
- 	}
 
- 	resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI)
 
- 	if err != nil {
 
- 		sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
 
- 		return
 
- 	}
 
- 	dataprovider.UpdateAdminLastLogin(&admin)
 
- 	render.JSON(w, r, resp)
 
- }
 
- func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
 
- 	if _, ok := r.Context().Value(oidcTokenKey).(string); ok {
 
- 		return
 
- 	}
 
- 	token, claims, err := jwtauth.FromContext(r.Context())
 
- 	if err != nil {
 
- 		return
 
- 	}
 
- 	tokenClaims := jwtTokenClaims{}
 
- 	tokenClaims.Decode(claims)
 
- 	if tokenClaims.Username == "" || tokenClaims.Signature == "" {
 
- 		return
 
- 	}
 
- 	if time.Until(token.Expiration()) > tokenRefreshThreshold {
 
- 		return
 
- 	}
 
- 	if util.IsStringInSlice(tokenAudienceWebClient, token.Audience()) {
 
- 		s.refreshClientToken(w, r, tokenClaims)
 
- 	} else {
 
- 		s.refreshAdminToken(w, r, tokenClaims)
 
- 	}
 
- }
 
- func (s *httpdServer) refreshClientToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
 
- 	user, err := dataprovider.UserExists(tokenClaims.Username)
 
- 	if err != nil {
 
- 		return
 
- 	}
 
- 	if user.GetSignature() != tokenClaims.Signature {
 
- 		logger.Debug(logSender, "", "signature mismatch for user %#v, unable to refresh cookie", user.Username)
 
- 		return
 
- 	}
 
- 	if err := checkHTTPClientUser(&user, r, xid.New().String()); err != nil {
 
- 		logger.Debug(logSender, "", "unable to refresh cookie for user %#v: %v", user.Username, err)
 
- 		return
 
- 	}
 
- 	tokenClaims.Permissions = user.Filters.WebClient
 
- 	logger.Debug(logSender, "", "cookie refreshed for user %#v", user.Username)
 
- 	tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebClient) //nolint:errcheck
 
- }
 
- func (s *httpdServer) refreshAdminToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
 
- 	admin, err := dataprovider.AdminExists(tokenClaims.Username)
 
- 	if err != nil {
 
- 		return
 
- 	}
 
- 	if admin.Status != 1 {
 
- 		logger.Debug(logSender, "", "admin %#v is disabled, unable to refresh cookie", admin.Username)
 
- 		return
 
- 	}
 
- 	if admin.GetSignature() != tokenClaims.Signature {
 
- 		logger.Debug(logSender, "", "signature mismatch for admin %#v, unable to refresh cookie", admin.Username)
 
- 		return
 
- 	}
 
- 	if !admin.CanLoginFromIP(util.GetIPFromRemoteAddress(r.RemoteAddr)) {
 
- 		logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie", admin.Username, r.RemoteAddr)
 
- 		return
 
- 	}
 
- 	tokenClaims.Permissions = admin.Permissions
 
- 	logger.Debug(logSender, "", "cookie refreshed for admin %#v", admin.Username)
 
- 	tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebAdmin) //nolint:errcheck
 
- }
 
- func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
 
- 	token, _, err := jwtauth.FromContext(r.Context())
 
- 	if token == nil || err != nil {
 
- 		_, err = r.Cookie(jwtCookieKey)
 
- 		if err != nil {
 
- 			return r
 
- 		}
 
- 		token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
 
- 		ctx := jwtauth.NewContext(r.Context(), token, err)
 
- 		return r.WithContext(ctx)
 
- 	}
 
- 	return r
 
- }
 
- func (s *httpdServer) checkConnection(next http.Handler) http.Handler {
 
- 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 
- 		ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
 
- 		ip := net.ParseIP(ipAddr)
 
- 		areHeadersAllowed := false
 
- 		if ip != nil {
 
- 			for _, allow := range s.binding.allowHeadersFrom {
 
- 				if allow(ip) {
 
- 					parsedIP := util.GetRealIP(r)
 
- 					if parsedIP != "" {
 
- 						ipAddr = parsedIP
 
- 						r.RemoteAddr = ipAddr
 
- 					}
 
- 					if forwardedProto := r.Header.Get(xForwardedProto); forwardedProto != "" {
 
- 						ctx := context.WithValue(r.Context(), forwardedProtoKey, forwardedProto)
 
- 						r = r.WithContext(ctx)
 
- 					}
 
- 					areHeadersAllowed = true
 
- 					break
 
- 				}
 
- 			}
 
- 		}
 
- 		if !areHeadersAllowed {
 
- 			for idx := range s.binding.Security.proxyHeaders {
 
- 				r.Header.Del(s.binding.Security.proxyHeaders[idx])
 
- 			}
 
- 		}
 
- 		common.Connections.AddClientConnection(ipAddr)
 
- 		defer common.Connections.RemoveClientConnection(ipAddr)
 
- 		if !common.Connections.IsNewConnectionAllowed(ipAddr) {
 
- 			logger.Log(logger.LevelDebug, common.ProtocolHTTP, "", fmt.Sprintf("connection not allowed from ip %#v", ipAddr))
 
- 			s.sendForbiddenResponse(w, r, "connection not allowed from your ip")
 
- 			return
 
- 		}
 
- 		if common.IsBanned(ipAddr) {
 
- 			s.sendForbiddenResponse(w, r, "your IP address is banned")
 
- 			return
 
- 		}
 
- 		if delay, err := common.LimitRate(common.ProtocolHTTP, ipAddr); err != nil {
 
- 			delay += 499999999 * time.Nanosecond
 
- 			w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
 
- 			w.Header().Set("X-Retry-In", delay.String())
 
- 			s.sendTooManyRequestResponse(w, r, err)
 
- 			return
 
- 		}
 
- 		next.ServeHTTP(w, r)
 
- 	})
 
- }
 
- func (s *httpdServer) sendTooManyRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
 
- 	if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
 
- 		r = s.updateContextFromCookie(r)
 
- 		if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
 
- 			renderClientMessagePage(w, r, http.StatusText(http.StatusTooManyRequests), "Rate limit exceeded",
 
- 				http.StatusTooManyRequests, err, "")
 
- 			return
 
- 		}
 
- 		renderMessagePage(w, r, http.StatusText(http.StatusTooManyRequests), "Rate limit exceeded", http.StatusTooManyRequests,
 
- 			err, "")
 
- 		return
 
- 	}
 
- 	sendAPIResponse(w, r, err, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
 
- }
 
- func (s *httpdServer) sendForbiddenResponse(w http.ResponseWriter, r *http.Request, message string) {
 
- 	if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
 
- 		r = s.updateContextFromCookie(r)
 
- 		if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
 
- 			renderClientForbiddenPage(w, r, message)
 
- 			return
 
- 		}
 
- 		renderForbiddenPage(w, r, message)
 
- 		return
 
- 	}
 
- 	sendAPIResponse(w, r, errors.New(message), message, http.StatusForbidden)
 
- }
 
- func (s *httpdServer) badHostHandler(w http.ResponseWriter, r *http.Request) {
 
- 	host := r.Host
 
- 	for _, header := range s.binding.Security.HostsProxyHeaders {
 
- 		if h := r.Header.Get(header); h != "" {
 
- 			host = h
 
- 			break
 
- 		}
 
- 	}
 
- 	s.sendForbiddenResponse(w, r, fmt.Sprintf("The host %#v is not allowed", host))
 
- }
 
- func (s *httpdServer) redirectToWebPath(w http.ResponseWriter, r *http.Request, webPath string) {
 
- 	if dataprovider.HasAdmin() {
 
- 		http.Redirect(w, r, webPath, http.StatusFound)
 
- 		return
 
- 	}
 
- 	if s.enableWebAdmin {
 
- 		http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
 
- 	}
 
- }
 
- func (s *httpdServer) isStaticFileURL(r *http.Request) bool {
 
- 	var urlPath string
 
- 	rctx := chi.RouteContext(r.Context())
 
- 	if rctx != nil && rctx.RoutePath != "" {
 
- 		urlPath = rctx.RoutePath
 
- 	} else {
 
- 		urlPath = r.URL.Path
 
- 	}
 
- 	return !strings.HasPrefix(urlPath, webOpenAPIPath) && !strings.HasPrefix(urlPath, webStaticFilesPath)
 
- }
 
- func (s *httpdServer) initializeRouter() {
 
- 	s.tokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(s.signingPassphrase), nil)
 
- 	s.router = chi.NewRouter()
 
- 	s.router.Use(middleware.RequestID)
 
- 	s.router.Use(s.checkConnection)
 
- 	s.router.Use(logger.NewStructuredLogger(logger.GetLogger()))
 
- 	s.router.Use(middleware.Recoverer)
 
- 	if s.binding.Security.Enabled {
 
- 		secureMiddleware := secure.New(secure.Options{
 
- 			AllowedHosts:            s.binding.Security.AllowedHosts,
 
- 			AllowedHostsAreRegex:    s.binding.Security.AllowedHostsAreRegex,
 
- 			HostsProxyHeaders:       s.binding.Security.HostsProxyHeaders,
 
- 			SSLProxyHeaders:         s.binding.Security.getHTTPSProxyHeaders(),
 
- 			STSSeconds:              s.binding.Security.STSSeconds,
 
- 			STSIncludeSubdomains:    s.binding.Security.STSIncludeSubdomains,
 
- 			STSPreload:              s.binding.Security.STSPreload,
 
- 			ContentTypeNosniff:      s.binding.Security.ContentTypeNosniff,
 
- 			ContentSecurityPolicy:   s.binding.Security.ContentSecurityPolicy,
 
- 			PermissionsPolicy:       s.binding.Security.PermissionsPolicy,
 
- 			CrossOriginOpenerPolicy: s.binding.Security.CrossOriginOpenerPolicy,
 
- 			ExpectCTHeader:          s.binding.Security.ExpectCTHeader,
 
- 		})
 
- 		secureMiddleware.SetBadHostHandler(http.HandlerFunc(s.badHostHandler))
 
- 		s.router.Use(secureMiddleware.Handler)
 
- 	}
 
- 	if s.cors.Enabled {
 
- 		c := cors.New(cors.Options{
 
- 			AllowedOrigins:   s.cors.AllowedOrigins,
 
- 			AllowedMethods:   s.cors.AllowedMethods,
 
- 			AllowedHeaders:   s.cors.AllowedHeaders,
 
- 			ExposedHeaders:   s.cors.ExposedHeaders,
 
- 			MaxAge:           s.cors.MaxAge,
 
- 			AllowCredentials: s.cors.AllowCredentials,
 
- 		})
 
- 		s.router.Use(c.Handler)
 
- 	}
 
- 	s.router.Use(middleware.GetHead)
 
- 	// StripSlashes causes infinite redirects at the root path if used with http.FileServer
 
- 	s.router.Use(middleware.Maybe(middleware.StripSlashes, s.isStaticFileURL))
 
- 	s.router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 
- 		r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 		if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
 
- 			r = s.updateContextFromCookie(r)
 
- 			if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
 
- 				renderClientNotFoundPage(w, r, nil)
 
- 				return
 
- 			}
 
- 			renderNotFoundPage(w, r, nil)
 
- 			return
 
- 		}
 
- 		sendAPIResponse(w, r, nil, http.StatusText(http.StatusNotFound), http.StatusNotFound)
 
- 	}))
 
- 	s.router.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
 
- 		render.PlainText(w, r, "ok")
 
- 	})
 
- 	// share API exposed to external users
 
- 	s.router.Get(sharesPath+"/{id}", downloadFromShare)
 
- 	s.router.Post(sharesPath+"/{id}", uploadFilesToShare)
 
- 	s.router.Post(sharesPath+"/{id}/{name}", uploadFileToShare)
 
- 	s.router.With(compressor.Handler).Get(sharesPath+"/{id}/dirs", readBrowsableShareContents)
 
- 	s.router.Get(sharesPath+"/{id}/files", downloadBrowsableSharedFile)
 
- 	s.router.Get(tokenPath, s.getToken)
 
- 	s.router.Post(adminPath+"/{username}/forgot-password", forgotAdminPassword)
 
- 	s.router.Post(adminPath+"/{username}/reset-password", resetAdminPassword)
 
- 	s.router.Post(userPath+"/{username}/forgot-password", forgotUserPassword)
 
- 	s.router.Post(userPath+"/{username}/reset-password", resetUserPassword)
 
- 	s.router.Group(func(router chi.Router) {
 
- 		router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeAdmin))
 
- 		router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
 
- 		router.Use(jwtAuthenticatorAPI)
 
- 		router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
 
- 			r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 			render.JSON(w, r, version.Get())
 
- 		})
 
- 		router.With(forbidAPIKeyAuthentication).Get(logoutPath, s.logout)
 
- 		router.With(forbidAPIKeyAuthentication).Get(adminProfilePath, getAdminProfile)
 
- 		router.With(forbidAPIKeyAuthentication).Put(adminProfilePath, updateAdminProfile)
 
- 		router.With(forbidAPIKeyAuthentication).Put(adminPwdPath, changeAdminPassword)
 
- 		// compatibility layer to remove in v2.2
 
- 		router.With(forbidAPIKeyAuthentication).Put(adminPwdCompatPath, changeAdminPassword)
 
- 		// admin TOTP APIs
 
- 		router.With(forbidAPIKeyAuthentication).Get(adminTOTPConfigsPath, getTOTPConfigs)
 
- 		router.With(forbidAPIKeyAuthentication).Post(adminTOTPGeneratePath, generateTOTPSecret)
 
- 		router.With(forbidAPIKeyAuthentication).Post(adminTOTPValidatePath, validateTOTPPasscode)
 
- 		router.With(forbidAPIKeyAuthentication).Post(adminTOTPSavePath, saveTOTPConfig)
 
- 		router.With(forbidAPIKeyAuthentication).Get(admin2FARecoveryCodesPath, getRecoveryCodes)
 
- 		router.With(forbidAPIKeyAuthentication).Post(admin2FARecoveryCodesPath, generateRecoveryCodes)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewServerStatus)).
 
- 			Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
 
- 				r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 				render.JSON(w, r, getServicesStatus())
 
- 			})
 
- 		router.With(checkPerm(dataprovider.PermAdminViewConnections)).
 
- 			Get(activeConnectionsPath, func(w http.ResponseWriter, r *http.Request) {
 
- 				r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 				render.JSON(w, r, common.Connections.GetStats())
 
- 			})
 
- 		router.With(checkPerm(dataprovider.PermAdminCloseConnections)).
 
- 			Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanPath, getUsersQuotaScans)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/users/scans", getUsersQuotaScans)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanPath, startUserQuotaScanCompat)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/users/{username}/scan", startUserQuotaScan)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanVFolderPath, getFoldersQuotaScans)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/folders/scans", getFoldersQuotaScans)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanVFolderPath, startFolderQuotaScanCompat)
 
- 		router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/folders/{name}/scan", startFolderQuotaScan)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
 
- 		router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
 
- 		router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}/2fa/disable", disableUser2FA)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath, getFolders)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath+"/{name}", getFolderByName)
 
- 		router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(folderPath, addFolder)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(folderPath+"/{name}", updateFolder)
 
- 		router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(folderPath+"/{name}", deleteFolder)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(dumpDataPath, dumpData)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(loadDataPath, loadData)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(loadDataPath, loadDataFromRequest)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateUsedQuotaPath, updateUserQuotaUsageCompat)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/usage",
 
- 			updateUserQuotaUsage)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/transfer-usage",
 
- 			updateUserTransferQuotaUsage)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateFolderUsedQuotaPath, updateFolderQuotaUsageCompat)
 
- 		router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage",
 
- 			updateFolderQuotaUsage)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderBanTime, getBanTime)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderScore, getScore)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageDefender)).Post(defenderUnban, unban)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
 
- 		router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
 
- 		router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Get(retentionChecksPath, getRetentionChecks)
 
- 		router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Post(retentionBasePath+"/{username}/check",
 
- 			startRetentionCheck)
 
- 		router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Get(metadataChecksPath, getMetadataChecks)
 
- 		router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Post(metadataBasePath+"/{username}/check",
 
- 			startMetadataCheck)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
 
- 			Get(fsEventsPath, searchFsEvents)
 
- 		router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
 
- 			Get(providerEventsPath, searchProviderEvents)
 
- 		router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
 
- 			Get(apiKeysPath, getAPIKeys)
 
- 		router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
 
- 			Post(apiKeysPath, addAPIKey)
 
- 		router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
 
- 			Get(apiKeysPath+"/{id}", getAPIKeyByID)
 
- 		router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
 
- 			Put(apiKeysPath+"/{id}", updateAPIKey)
 
- 		router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
 
- 			Delete(apiKeysPath+"/{id}", deleteAPIKey)
 
- 	})
 
- 	s.router.Get(userTokenPath, s.getUserToken)
 
- 	s.router.Group(func(router chi.Router) {
 
- 		router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
 
- 		router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
 
- 		router.Use(jwtAuthenticatorAPIUser)
 
- 		router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
 
- 		router.With(forbidAPIKeyAuthentication, checkSecondFactorRequirement,
 
- 			checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).Put(userPwdPath, changeUserPassword)
 
- 		router.With(forbidAPIKeyAuthentication, checkSecondFactorRequirement,
 
- 			checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).Get(userPublicKeysPath, getUserPublicKeys)
 
- 		router.With(forbidAPIKeyAuthentication, checkSecondFactorRequirement,
 
- 			checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).Put(userPublicKeysPath, setUserPublicKeys)
 
- 		router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
 
- 		router.With(forbidAPIKeyAuthentication, checkSecondFactorRequirement).Put(userProfilePath, updateUserProfile)
 
- 		// user TOTP APIs
 
- 		router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
 
- 			Get(userTOTPConfigsPath, getTOTPConfigs)
 
- 		router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
 
- 			Post(userTOTPGeneratePath, generateTOTPSecret)
 
- 		router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
 
- 			Post(userTOTPValidatePath, validateTOTPPasscode)
 
- 		router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
 
- 			Post(userTOTPSavePath, saveTOTPConfig)
 
- 		router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
 
- 			Get(user2FARecoveryCodesPath, getRecoveryCodes)
 
- 		router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
 
- 			Post(user2FARecoveryCodesPath, generateRecoveryCodes)
 
- 		// compatibility layer to remove in v2.3
 
- 		router.With(checkSecondFactorRequirement, compressor.Handler).Get(userFolderPath, readUserFolder)
 
- 		router.With(checkSecondFactorRequirement).Get(userFilePath, getUserFile)
 
- 		router.With(checkSecondFactorRequirement, compressor.Handler).Get(userDirsPath, readUserFolder)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Post(userDirsPath, createUserDir)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Patch(userDirsPath, renameUserDir)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Delete(userDirsPath, deleteUserDir)
 
- 		router.With(checkSecondFactorRequirement).Get(userFilesPath, getUserFile)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Post(userFilesPath, uploadUserFiles)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Patch(userFilesPath, renameUserFile)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Delete(userFilesPath, deleteUserFile)
 
- 		router.With(checkSecondFactorRequirement).Post(userStreamZipPath, getUserFilesAsZipStream)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 			Get(userSharesPath, getShares)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 			Post(userSharesPath, addShare)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 			Get(userSharesPath+"/{id}", getShareByID)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 			Put(userSharesPath+"/{id}", updateShare)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 			Delete(userSharesPath+"/{id}", deleteShare)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Post(userUploadFilePath, uploadUserFile)
 
- 		router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
 
- 			Patch(userFilesDirsMetadataPath, setFileDirMetadata)
 
- 	})
 
- 	if s.renderOpenAPI {
 
- 		s.router.Group(func(router chi.Router) {
 
- 			router.Use(compressor.Handler)
 
- 			fileServer(router, webOpenAPIPath, http.Dir(s.openAPIPath))
 
- 		})
 
- 	}
 
- 	if s.enableWebAdmin || s.enableWebClient {
 
- 		s.router.Group(func(router chi.Router) {
 
- 			router.Use(compressor.Handler)
 
- 			fileServer(router, webStaticFilesPath, http.Dir(s.staticFilesPath))
 
- 		})
 
- 		if s.binding.OIDC.isEnabled() {
 
- 			s.router.Get(webOIDCRedirectPath, s.handleOIDCRedirect)
 
- 		}
 
- 		if s.enableWebClient {
 
- 			s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
 
- 				r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 				s.redirectToWebPath(w, r, webClientLoginPath)
 
- 			})
 
- 			s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
 
- 				r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 				s.redirectToWebPath(w, r, webClientLoginPath)
 
- 			})
 
- 		} else {
 
- 			s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
 
- 				r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 				s.redirectToWebPath(w, r, webAdminLoginPath)
 
- 			})
 
- 			s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
 
- 				r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 				s.redirectToWebPath(w, r, webAdminLoginPath)
 
- 			})
 
- 		}
 
- 	}
 
- 	s.setupWebClientRoutes()
 
- 	s.setupWebAdminRoutes()
 
- }
 
- func (s *httpdServer) setupWebClientRoutes() {
 
- 	if s.enableWebClient {
 
- 		s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
 
- 			r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
 
- 			http.Redirect(w, r, webClientLoginPath, http.StatusFound)
 
- 		})
 
- 		s.router.Get(webClientLoginPath, s.handleClientWebLogin)
 
- 		if s.binding.OIDC.isEnabled() {
 
- 			s.router.Get(webClientOIDCLoginPath, s.handleWebClientOIDCLogin)
 
- 		}
 
- 		s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
 
- 		s.router.Get(webClientForgotPwdPath, handleWebClientForgotPwd)
 
- 		s.router.Post(webClientForgotPwdPath, handleWebClientForgotPwdPost)
 
- 		s.router.Get(webClientResetPwdPath, handleWebClientPasswordReset)
 
- 		s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
 
- 			Get(webClientTwoFactorPath, handleWebClientTwoFactor)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
 
- 			Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
 
- 			Get(webClientTwoFactorRecoveryPath, handleWebClientTwoFactorRecovery)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
 
- 			Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
 
- 		// share API exposed to external users
 
- 		s.router.Get(webClientPubSharesPath+"/{id}", downloadFromShare)
 
- 		s.router.Get(webClientPubSharesPath+"/{id}/browse", handleShareGetFiles)
 
- 		s.router.Get(webClientPubSharesPath+"/{id}/upload", handleClientUploadToShare)
 
- 		s.router.With(compressor.Handler).Get(webClientPubSharesPath+"/{id}/dirs", handleShareGetDirContents)
 
- 		s.router.Post(webClientPubSharesPath+"/{id}", uploadFilesToShare)
 
- 		s.router.Post(webClientPubSharesPath+"/{id}/{name}", uploadFileToShare)
 
- 		s.router.Group(func(router chi.Router) {
 
- 			if s.binding.OIDC.isEnabled() {
 
- 				router.Use(s.oidcTokenAuthenticator(tokenAudienceWebClient))
 
- 			}
 
- 			router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
 
- 			router.Use(jwtAuthenticatorWebClient)
 
- 			router.Get(webClientLogoutPath, s.handleWebClientLogout)
 
- 			router.With(checkSecondFactorRequirement, s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
 
- 			router.With(checkSecondFactorRequirement, s.refreshCookie).Get(webClientViewPDFPath, handleClientViewPDF)
 
- 			router.With(checkSecondFactorRequirement, s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
 
- 				Post(webClientFilePath, uploadUserFile)
 
- 			router.With(checkSecondFactorRequirement, s.refreshCookie).Get(webClientEditFilePath, handleClientEditFile)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
 
- 				Patch(webClientFilesPath, renameUserFile)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
 
- 				Delete(webClientFilesPath, deleteUserFile)
 
- 			router.With(checkSecondFactorRequirement, compressor.Handler, s.refreshCookie).
 
- 				Get(webClientDirsPath, s.handleClientGetDirContents)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
 
- 				Post(webClientDirsPath, createUserDir)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
 
- 				Patch(webClientDirsPath, renameUserDir)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
 
- 				Delete(webClientDirsPath, deleteUserDir)
 
- 			router.With(checkSecondFactorRequirement, s.refreshCookie).
 
- 				Get(webClientDownloadZipPath, handleWebClientDownloadZip)
 
- 			router.With(checkSecondFactorRequirement, s.refreshCookie, requireBuiltinLogin).
 
- 				Get(webClientProfilePath, handleClientGetProfile)
 
- 			router.With(checkSecondFactorRequirement, requireBuiltinLogin).
 
- 				Post(webClientProfilePath, handleWebClientProfilePost)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
 
- 				Get(webChangeClientPwdPath, handleWebClientChangePwd)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
 
- 				Post(webChangeClientPwdPath, s.handleWebClientChangePwdPost)
 
- 			router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
 
- 				Get(webClientMFAPath, handleWebClientMFA)
 
- 			router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
 
- 				Post(webClientTOTPGeneratePath, generateTOTPSecret)
 
- 			router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
 
- 				Post(webClientTOTPValidatePath, validateTOTPPasscode)
 
- 			router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
 
- 				Post(webClientTOTPSavePath, saveTOTPConfig)
 
- 			router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
 
- 				Get(webClientRecoveryCodesPath, getRecoveryCodes)
 
- 			router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
 
- 				Post(webClientRecoveryCodesPath, generateRecoveryCodes)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
 
- 				Get(webClientSharesPath, handleClientGetShares)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
 
- 				Get(webClientSharePath, handleClientAddShareGet)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 				Post(webClientSharePath, handleClientAddSharePost)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
 
- 				Get(webClientSharePath+"/{id}", handleClientUpdateShareGet)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
 
- 				Post(webClientSharePath+"/{id}", handleClientUpdateSharePost)
 
- 			router.With(checkSecondFactorRequirement, checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
 
- 				Delete(webClientSharePath+"/{id}", deleteShare)
 
- 		})
 
- 	}
 
- }
 
- func (s *httpdServer) setupWebAdminRoutes() {
 
- 	if s.enableWebAdmin {
 
- 		s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
 
- 			r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
 
- 			s.redirectToWebPath(w, r, webAdminLoginPath)
 
- 		})
 
- 		s.router.Get(webAdminLoginPath, s.handleWebAdminLogin)
 
- 		if s.binding.OIDC.hasRoles() {
 
- 			s.router.Get(webAdminOIDCLoginPath, s.handleWebAdminOIDCLogin)
 
- 		}
 
- 		s.router.Post(webAdminLoginPath, s.handleWebAdminLoginPost)
 
- 		s.router.Get(webAdminSetupPath, handleWebAdminSetupGet)
 
- 		s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
 
- 		s.router.Get(webAdminForgotPwdPath, handleWebAdminForgotPwd)
 
- 		s.router.Post(webAdminForgotPwdPath, handleWebAdminForgotPwdPost)
 
- 		s.router.Get(webAdminResetPwdPath, handleWebAdminPasswordReset)
 
- 		s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
 
- 			Get(webAdminTwoFactorPath, handleWebAdminTwoFactor)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
 
- 			Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
 
- 			Get(webAdminTwoFactorRecoveryPath, handleWebAdminTwoFactorRecovery)
 
- 		s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
 
- 			jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
 
- 			Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
 
- 		s.router.Group(func(router chi.Router) {
 
- 			if s.binding.OIDC.isEnabled() {
 
- 				router.Use(s.oidcTokenAuthenticator(tokenAudienceWebAdmin))
 
- 			}
 
- 			router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
 
- 			router.Use(jwtAuthenticatorWebAdmin)
 
- 			router.Get(webLogoutPath, s.handleWebAdminLogout)
 
- 			router.With(s.refreshCookie, requireBuiltinLogin).Get(webAdminProfilePath, handleWebAdminProfile)
 
- 			router.With(requireBuiltinLogin).Post(webAdminProfilePath, handleWebAdminProfilePost)
 
- 			router.With(s.refreshCookie, requireBuiltinLogin).Get(webChangeAdminPwdPath, handleWebAdminChangePwd)
 
- 			router.With(requireBuiltinLogin).Post(webChangeAdminPwdPath, s.handleWebAdminChangePwdPost)
 
- 			router.With(s.refreshCookie, requireBuiltinLogin).Get(webAdminMFAPath, handleWebAdminMFA)
 
- 			router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
 
- 			router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
 
- 			router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminTOTPSavePath, saveTOTPConfig)
 
- 			router.With(verifyCSRFHeader, requireBuiltinLogin, s.refreshCookie).Get(webAdminRecoveryCodesPath, getRecoveryCodes)
 
- 			router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
 
- 			router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
 
- 				Get(webUsersPath, handleGetWebUsers)
 
- 			router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
 
- 				Get(webUserPath, handleWebAddUserGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
 
- 				Get(webUserPath+"/{username}", handleWebUpdateUserGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, handleWebAddUserPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}", handleWebUpdateUserPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
 
- 				Get(webConnectionsPath, handleWebGetConnections)
 
- 			router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
 
- 				Get(webFoldersPath, handleWebGetFolders)
 
- 			router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
 
- 				Get(webFolderPath, handleWebAddFolderGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webFolderPath, handleWebAddFolderPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
 
- 				Get(webStatusPath, handleWebGetStatus)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
 
- 				Get(webAdminsPath, handleGetWebAdmins)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
 
- 				Get(webAdminPath, handleWebAddAdminGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
 
- 				Get(webAdminPath+"/{username}", handleWebUpdateAdminGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, handleWebAddAdminPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}",
 
- 				handleWebUpdateAdminPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageAdmins), verifyCSRFHeader).
 
- 				Delete(webAdminPath+"/{username}", deleteAdmin)
 
- 			router.With(checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
 
- 				Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
 
- 			router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
 
- 				Get(webFolderPath+"/{name}", handleWebUpdateFolderGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webFolderPath+"/{name}",
 
- 				handleWebUpdateFolderPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
 
- 				Delete(webFolderPath+"/{name}", deleteFolder)
 
- 			router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
 
- 				Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
 
- 			router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
 
- 				Delete(webUserPath+"/{username}", deleteUser)
 
- 			router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
 
- 				Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, handleWebMaintenance)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, handleWebRestore)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
 
- 				Get(webTemplateUser, handleWebTemplateUserGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, handleWebTemplateUserPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
 
- 				Get(webTemplateFolder, handleWebTemplateFolderGet)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateFolder, handleWebTemplateFolderPost)
 
- 			router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, handleWebDefenderPage)
 
- 			router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
 
- 			router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(webDefenderHostsPath+"/{id}",
 
- 				deleteDefenderHostByID)
 
- 		})
 
- 	}
 
- }
 
 
  |