server.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "errors"
  20. "fmt"
  21. "log"
  22. "net"
  23. "net/http"
  24. "net/url"
  25. "path/filepath"
  26. "strings"
  27. "time"
  28. "github.com/go-chi/chi/v5"
  29. "github.com/go-chi/chi/v5/middleware"
  30. "github.com/go-chi/jwtauth/v5"
  31. "github.com/go-chi/render"
  32. "github.com/lestrrat-go/jwx/v2/jwa"
  33. "github.com/rs/cors"
  34. "github.com/rs/xid"
  35. "github.com/sftpgo/sdk"
  36. "github.com/unrolled/secure"
  37. "github.com/drakkan/sftpgo/v2/internal/acme"
  38. "github.com/drakkan/sftpgo/v2/internal/common"
  39. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  40. "github.com/drakkan/sftpgo/v2/internal/logger"
  41. "github.com/drakkan/sftpgo/v2/internal/mfa"
  42. "github.com/drakkan/sftpgo/v2/internal/smtp"
  43. "github.com/drakkan/sftpgo/v2/internal/util"
  44. "github.com/drakkan/sftpgo/v2/internal/version"
  45. )
  46. const (
  47. jsonAPISuffix = "/json"
  48. )
  49. var (
  50. compressor = middleware.NewCompressor(5)
  51. xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto")
  52. )
  53. type httpdServer struct {
  54. binding Binding
  55. staticFilesPath string
  56. openAPIPath string
  57. enableWebAdmin bool
  58. enableWebClient bool
  59. enableRESTAPI bool
  60. renderOpenAPI bool
  61. isShared int
  62. router *chi.Mux
  63. tokenAuth *jwtauth.JWTAuth
  64. signingPassphrase string
  65. cors CorsConfig
  66. }
  67. func newHttpdServer(b Binding, staticFilesPath, signingPassphrase string, cors CorsConfig,
  68. openAPIPath string,
  69. ) *httpdServer {
  70. if openAPIPath == "" {
  71. b.RenderOpenAPI = false
  72. }
  73. return &httpdServer{
  74. binding: b,
  75. staticFilesPath: staticFilesPath,
  76. openAPIPath: openAPIPath,
  77. enableWebAdmin: b.EnableWebAdmin,
  78. enableWebClient: b.EnableWebClient,
  79. enableRESTAPI: b.EnableRESTAPI,
  80. renderOpenAPI: b.RenderOpenAPI,
  81. signingPassphrase: signingPassphrase,
  82. cors: cors,
  83. }
  84. }
  85. func (s *httpdServer) setShared(value int) {
  86. s.isShared = value
  87. }
  88. func (s *httpdServer) listenAndServe() error {
  89. s.initializeRouter()
  90. httpServer := &http.Server{
  91. Handler: s.router,
  92. ReadHeaderTimeout: 30 * time.Second,
  93. ReadTimeout: 60 * time.Second,
  94. WriteTimeout: 60 * time.Second,
  95. IdleTimeout: 60 * time.Second,
  96. MaxHeaderBytes: 1 << 16, // 64KB
  97. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  98. }
  99. if certMgr != nil && s.binding.EnableHTTPS {
  100. certID := common.DefaultTLSKeyPaidID
  101. if getConfigPath(s.binding.CertificateFile, "") != "" && getConfigPath(s.binding.CertificateKeyFile, "") != "" {
  102. certID = s.binding.GetAddress()
  103. }
  104. config := &tls.Config{
  105. GetCertificate: certMgr.GetCertificateFunc(certID),
  106. MinVersion: util.GetTLSVersion(s.binding.MinTLSVersion),
  107. NextProtos: util.GetALPNProtocols(s.binding.Protocols),
  108. CipherSuites: util.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
  109. }
  110. httpServer.TLSConfig = config
  111. logger.Debug(logSender, "", "configured TLS cipher suites for binding %q: %v, certID: %v",
  112. s.binding.GetAddress(), httpServer.TLSConfig.CipherSuites, certID)
  113. if s.binding.isMutualTLSEnabled() {
  114. httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
  115. httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
  116. httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
  117. }
  118. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, true, logSender)
  119. }
  120. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, false, logSender)
  121. }
  122. func (s *httpdServer) verifyTLSConnection(state tls.ConnectionState) error {
  123. if certMgr != nil {
  124. var clientCrt *x509.Certificate
  125. var clientCrtName string
  126. if len(state.PeerCertificates) > 0 {
  127. clientCrt = state.PeerCertificates[0]
  128. clientCrtName = clientCrt.Subject.String()
  129. }
  130. if len(state.VerifiedChains) == 0 {
  131. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  132. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  133. }
  134. for _, verifiedChain := range state.VerifiedChains {
  135. var caCrt *x509.Certificate
  136. if len(verifiedChain) > 0 {
  137. caCrt = verifiedChain[len(verifiedChain)-1]
  138. }
  139. if certMgr.IsRevoked(clientCrt, caCrt) {
  140. logger.Debug(logSender, "", "tls handshake error, client certificate %q has been revoked", clientCrtName)
  141. return common.ErrCrtRevoked
  142. }
  143. }
  144. }
  145. return nil
  146. }
  147. func (s *httpdServer) refreshCookie(next http.Handler) http.Handler {
  148. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  149. s.checkCookieExpiration(w, r)
  150. next.ServeHTTP(w, r)
  151. })
  152. }
  153. func (s *httpdServer) renderClientLoginPage(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string) {
  154. data := loginPage{
  155. commonBasePage: getCommonBasePage(r),
  156. Title: util.I18nLoginTitle,
  157. CurrentURL: webClientLoginPath,
  158. Error: err,
  159. CSRFToken: createCSRFToken(ip),
  160. Branding: s.binding.Branding.WebClient,
  161. FormDisabled: s.binding.isWebClientLoginFormDisabled(),
  162. CheckRedirect: true,
  163. }
  164. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  165. data.CurrentURL += "?next=" + url.QueryEscape(next)
  166. }
  167. if s.binding.showAdminLoginURL() {
  168. data.AltLoginURL = webAdminLoginPath
  169. data.AltLoginName = s.binding.Branding.WebAdmin.ShortName
  170. }
  171. if smtp.IsEnabled() && !data.FormDisabled {
  172. data.ForgotPwdURL = webClientForgotPwdPath
  173. }
  174. if s.binding.OIDC.isEnabled() && !s.binding.isWebClientOIDCLoginDisabled() {
  175. data.OpenIDLoginURL = webClientOIDCLoginPath
  176. }
  177. renderClientTemplate(w, templateCommonLogin, data)
  178. }
  179. func (s *httpdServer) handleWebClientLogout(w http.ResponseWriter, r *http.Request) {
  180. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  181. c := jwtTokenClaims{}
  182. c.removeCookie(w, r, webBaseClientPath)
  183. s.logoutOIDCUser(w, r)
  184. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  185. }
  186. func (s *httpdServer) handleWebClientChangePwdPost(w http.ResponseWriter, r *http.Request) {
  187. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  188. if err := r.ParseForm(); err != nil {
  189. s.renderClientChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  190. return
  191. }
  192. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  193. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  194. return
  195. }
  196. err := doChangeUserPassword(r, strings.TrimSpace(r.Form.Get("current_password")),
  197. strings.TrimSpace(r.Form.Get("new_password1")), strings.TrimSpace(r.Form.Get("new_password2")))
  198. if err != nil {
  199. s.renderClientChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric))
  200. return
  201. }
  202. s.handleWebClientLogout(w, r)
  203. }
  204. func (s *httpdServer) handleClientWebLogin(w http.ResponseWriter, r *http.Request) {
  205. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  206. if !dataprovider.HasAdmin() {
  207. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  208. return
  209. }
  210. msg := getFlashMessage(w, r)
  211. s.renderClientLoginPage(w, r, msg.getI18nError(), util.GetIPFromRemoteAddress(r.RemoteAddr))
  212. }
  213. func (s *httpdServer) handleWebClientLoginPost(w http.ResponseWriter, r *http.Request) {
  214. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  215. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  216. if err := r.ParseForm(); err != nil {
  217. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  218. return
  219. }
  220. protocol := common.ProtocolHTTP
  221. username := strings.TrimSpace(r.Form.Get("username"))
  222. password := strings.TrimSpace(r.Form.Get("password"))
  223. if username == "" || password == "" {
  224. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  225. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  226. s.renderClientLoginPage(w, r,
  227. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  228. return
  229. }
  230. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  231. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  232. dataprovider.LoginMethodPassword, ipAddr, err)
  233. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  234. return
  235. }
  236. if err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
  237. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  238. dataprovider.LoginMethodPassword, ipAddr, err)
  239. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nError403Message), ipAddr)
  240. return
  241. }
  242. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
  243. if err != nil {
  244. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  245. s.renderClientLoginPage(w, r,
  246. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  247. return
  248. }
  249. connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
  250. if err := checkHTTPClientUser(&user, r, connectionID, true); err != nil {
  251. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  252. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nError403Message), ipAddr)
  253. return
  254. }
  255. defer user.CloseFs() //nolint:errcheck
  256. err = user.CheckFsRoot(connectionID)
  257. if err != nil {
  258. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  259. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  260. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nErrorFsGeneric), ipAddr)
  261. return
  262. }
  263. s.loginUser(w, r, &user, connectionID, ipAddr, false, s.renderClientLoginPage)
  264. }
  265. func (s *httpdServer) handleWebClientPasswordResetPost(w http.ResponseWriter, r *http.Request) {
  266. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  267. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  268. err := r.ParseForm()
  269. if err != nil {
  270. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  271. return
  272. }
  273. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  274. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  275. return
  276. }
  277. newPassword := strings.TrimSpace(r.Form.Get("password"))
  278. confirmPassword := strings.TrimSpace(r.Form.Get("confirm_password"))
  279. _, user, err := handleResetPassword(r, strings.TrimSpace(r.Form.Get("code")),
  280. newPassword, confirmPassword, false)
  281. if err != nil {
  282. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric), ipAddr)
  283. return
  284. }
  285. connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
  286. if err := checkHTTPClientUser(user, r, connectionID, true); err != nil {
  287. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorLoginAfterReset), ipAddr)
  288. return
  289. }
  290. defer user.CloseFs() //nolint:errcheck
  291. err = user.CheckFsRoot(connectionID)
  292. if err != nil {
  293. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  294. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorLoginAfterReset), ipAddr)
  295. return
  296. }
  297. s.loginUser(w, r, user, connectionID, ipAddr, false, s.renderClientResetPwdPage)
  298. }
  299. func (s *httpdServer) handleWebClientTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
  300. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  301. claims, err := getTokenClaims(r)
  302. if err != nil {
  303. s.renderNotFoundPage(w, r, nil)
  304. return
  305. }
  306. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  307. if err := r.ParseForm(); err != nil {
  308. s.renderClientTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  309. return
  310. }
  311. username := claims.Username
  312. recoveryCode := strings.TrimSpace(r.Form.Get("recovery_code"))
  313. if username == "" || recoveryCode == "" {
  314. s.renderClientTwoFactorRecoveryPage(w, r,
  315. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  316. return
  317. }
  318. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  319. s.renderClientTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  320. return
  321. }
  322. user, userMerged, err := dataprovider.GetUserVariants(username, "")
  323. if err != nil {
  324. if errors.Is(err, util.ErrNotFound) {
  325. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  326. }
  327. s.renderClientTwoFactorRecoveryPage(w, r,
  328. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  329. return
  330. }
  331. if !userMerged.Filters.TOTPConfig.Enabled || !util.Contains(userMerged.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) {
  332. s.renderClientTwoFactorPage(w, r, util.NewI18nError(
  333. util.NewValidationError("two factory authentication is not enabled"), util.I18n2FADisabled), ipAddr)
  334. return
  335. }
  336. for idx, code := range user.Filters.RecoveryCodes {
  337. if err := code.Secret.Decrypt(); err != nil {
  338. s.renderClientInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
  339. return
  340. }
  341. if code.Secret.GetPayload() == recoveryCode {
  342. if code.Used {
  343. s.renderClientTwoFactorRecoveryPage(w, r,
  344. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  345. return
  346. }
  347. user.Filters.RecoveryCodes[idx].Used = true
  348. err = dataprovider.UpdateUser(&user, dataprovider.ActionExecutorSelf, ipAddr, user.Role)
  349. if err != nil {
  350. logger.Warn(logSender, "", "unable to set the recovery code %q as used: %v", recoveryCode, err)
  351. s.renderClientInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
  352. return
  353. }
  354. connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
  355. s.loginUser(w, r, &userMerged, connectionID, ipAddr, true,
  356. s.renderClientTwoFactorRecoveryPage)
  357. return
  358. }
  359. }
  360. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  361. s.renderClientTwoFactorRecoveryPage(w, r,
  362. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  363. }
  364. func (s *httpdServer) handleWebClientTwoFactorPost(w http.ResponseWriter, r *http.Request) {
  365. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  366. claims, err := getTokenClaims(r)
  367. if err != nil {
  368. s.renderNotFoundPage(w, r, nil)
  369. return
  370. }
  371. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  372. if err := r.ParseForm(); err != nil {
  373. s.renderClientTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  374. return
  375. }
  376. username := claims.Username
  377. passcode := strings.TrimSpace(r.Form.Get("passcode"))
  378. if username == "" || passcode == "" {
  379. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  380. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  381. s.renderClientTwoFactorPage(w, r,
  382. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  383. return
  384. }
  385. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  386. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  387. dataprovider.LoginMethodPassword, ipAddr, err)
  388. s.renderClientTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  389. return
  390. }
  391. user, err := dataprovider.GetUserWithGroupSettings(username, "")
  392. if err != nil {
  393. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  394. dataprovider.LoginMethodPassword, ipAddr, err)
  395. s.renderClientTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCredentials), ipAddr)
  396. return
  397. }
  398. if !user.Filters.TOTPConfig.Enabled || !util.Contains(user.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) {
  399. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  400. s.renderClientTwoFactorPage(w, r, util.NewI18nError(common.ErrInternalFailure, util.I18n2FADisabled), ipAddr)
  401. return
  402. }
  403. err = user.Filters.TOTPConfig.Secret.Decrypt()
  404. if err != nil {
  405. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  406. s.renderClientInternalServerErrorPage(w, r, err)
  407. return
  408. }
  409. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  410. user.Filters.TOTPConfig.Secret.GetPayload())
  411. if !match || err != nil {
  412. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  413. s.renderClientTwoFactorPage(w, r,
  414. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  415. return
  416. }
  417. connectionID := fmt.Sprintf("%s_%s", getProtocolFromRequest(r), xid.New().String())
  418. s.loginUser(w, r, &user, connectionID, ipAddr, true, s.renderClientTwoFactorPage)
  419. }
  420. func (s *httpdServer) handleWebAdminTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
  421. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  422. claims, err := getTokenClaims(r)
  423. if err != nil {
  424. s.renderNotFoundPage(w, r, nil)
  425. return
  426. }
  427. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  428. if err := r.ParseForm(); err != nil {
  429. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  430. return
  431. }
  432. username := claims.Username
  433. recoveryCode := strings.TrimSpace(r.Form.Get("recovery_code"))
  434. if username == "" || recoveryCode == "" {
  435. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  436. ipAddr)
  437. return
  438. }
  439. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  440. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  441. return
  442. }
  443. admin, err := dataprovider.AdminExists(username)
  444. if err != nil {
  445. if errors.Is(err, util.ErrNotFound) {
  446. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  447. }
  448. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  449. ipAddr)
  450. return
  451. }
  452. if !admin.Filters.TOTPConfig.Enabled {
  453. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(util.NewValidationError("two factory authentication is not enabled"), util.I18n2FADisabled), ipAddr)
  454. return
  455. }
  456. for idx, code := range admin.Filters.RecoveryCodes {
  457. if err := code.Secret.Decrypt(); err != nil {
  458. s.renderInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
  459. return
  460. }
  461. if code.Secret.GetPayload() == recoveryCode {
  462. if code.Used {
  463. s.renderTwoFactorRecoveryPage(w, r,
  464. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  465. return
  466. }
  467. admin.Filters.RecoveryCodes[idx].Used = true
  468. err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, ipAddr, admin.Role)
  469. if err != nil {
  470. logger.Warn(logSender, "", "unable to set the recovery code %q as used: %v", recoveryCode, err)
  471. s.renderInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
  472. return
  473. }
  474. s.loginAdmin(w, r, &admin, true, s.renderTwoFactorRecoveryPage, ipAddr)
  475. return
  476. }
  477. }
  478. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  479. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  480. ipAddr)
  481. }
  482. func (s *httpdServer) handleWebAdminTwoFactorPost(w http.ResponseWriter, r *http.Request) {
  483. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  484. claims, err := getTokenClaims(r)
  485. if err != nil {
  486. s.renderNotFoundPage(w, r, nil)
  487. return
  488. }
  489. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  490. if err := r.ParseForm(); err != nil {
  491. s.renderTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  492. return
  493. }
  494. username := claims.Username
  495. passcode := strings.TrimSpace(r.Form.Get("passcode"))
  496. if username == "" || passcode == "" {
  497. s.renderTwoFactorPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  498. ipAddr)
  499. return
  500. }
  501. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  502. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  503. s.renderTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  504. return
  505. }
  506. admin, err := dataprovider.AdminExists(username)
  507. if err != nil {
  508. if errors.Is(err, util.ErrNotFound) {
  509. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  510. }
  511. s.renderTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCredentials), ipAddr)
  512. return
  513. }
  514. if !admin.Filters.TOTPConfig.Enabled {
  515. s.renderTwoFactorPage(w, r, util.NewI18nError(common.ErrInternalFailure, util.I18n2FADisabled), ipAddr)
  516. return
  517. }
  518. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  519. if err != nil {
  520. s.renderInternalServerErrorPage(w, r, err)
  521. return
  522. }
  523. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  524. admin.Filters.TOTPConfig.Secret.GetPayload())
  525. if !match || err != nil {
  526. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  527. s.renderTwoFactorPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  528. ipAddr)
  529. return
  530. }
  531. s.loginAdmin(w, r, &admin, true, s.renderTwoFactorPage, ipAddr)
  532. }
  533. func (s *httpdServer) handleWebAdminLoginPost(w http.ResponseWriter, r *http.Request) {
  534. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  535. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  536. if err := r.ParseForm(); err != nil {
  537. s.renderAdminLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  538. return
  539. }
  540. username := strings.TrimSpace(r.Form.Get("username"))
  541. password := strings.TrimSpace(r.Form.Get("password"))
  542. if username == "" || password == "" {
  543. s.renderAdminLoginPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  544. ipAddr)
  545. return
  546. }
  547. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  548. s.renderAdminLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  549. return
  550. }
  551. admin, err := dataprovider.CheckAdminAndPass(username, password, ipAddr)
  552. if err != nil {
  553. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  554. s.renderAdminLoginPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  555. ipAddr)
  556. return
  557. }
  558. s.loginAdmin(w, r, &admin, false, s.renderAdminLoginPage, ipAddr)
  559. }
  560. func (s *httpdServer) renderAdminLoginPage(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string) {
  561. data := loginPage{
  562. commonBasePage: getCommonBasePage(r),
  563. Title: util.I18nLoginTitle,
  564. CurrentURL: webAdminLoginPath,
  565. Error: err,
  566. CSRFToken: createCSRFToken(ip),
  567. Branding: s.binding.Branding.WebAdmin,
  568. FormDisabled: s.binding.isWebAdminLoginFormDisabled(),
  569. CheckRedirect: false,
  570. }
  571. if s.binding.showClientLoginURL() {
  572. data.AltLoginURL = webClientLoginPath
  573. data.AltLoginName = s.binding.Branding.WebClient.ShortName
  574. }
  575. if smtp.IsEnabled() && !data.FormDisabled {
  576. data.ForgotPwdURL = webAdminForgotPwdPath
  577. }
  578. if s.binding.OIDC.hasRoles() && !s.binding.isWebAdminOIDCLoginDisabled() {
  579. data.OpenIDLoginURL = webAdminOIDCLoginPath
  580. }
  581. renderAdminTemplate(w, templateCommonLogin, data)
  582. }
  583. func (s *httpdServer) handleWebAdminLogin(w http.ResponseWriter, r *http.Request) {
  584. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  585. if !dataprovider.HasAdmin() {
  586. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  587. return
  588. }
  589. msg := getFlashMessage(w, r)
  590. s.renderAdminLoginPage(w, r, msg.getI18nError(), util.GetIPFromRemoteAddress(r.RemoteAddr))
  591. }
  592. func (s *httpdServer) handleWebAdminLogout(w http.ResponseWriter, r *http.Request) {
  593. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  594. c := jwtTokenClaims{}
  595. c.removeCookie(w, r, webBaseAdminPath)
  596. s.logoutOIDCUser(w, r)
  597. http.Redirect(w, r, webAdminLoginPath, http.StatusFound)
  598. }
  599. func (s *httpdServer) handleWebAdminChangePwdPost(w http.ResponseWriter, r *http.Request) {
  600. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  601. err := r.ParseForm()
  602. if err != nil {
  603. s.renderChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  604. return
  605. }
  606. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  607. s.renderForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  608. return
  609. }
  610. err = doChangeAdminPassword(r, strings.TrimSpace(r.Form.Get("current_password")),
  611. strings.TrimSpace(r.Form.Get("new_password1")), strings.TrimSpace(r.Form.Get("new_password2")))
  612. if err != nil {
  613. s.renderChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric))
  614. return
  615. }
  616. s.handleWebAdminLogout(w, r)
  617. }
  618. func (s *httpdServer) handleWebAdminPasswordResetPost(w http.ResponseWriter, r *http.Request) {
  619. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  620. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  621. err := r.ParseForm()
  622. if err != nil {
  623. s.renderResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  624. return
  625. }
  626. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  627. s.renderForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  628. return
  629. }
  630. newPassword := strings.TrimSpace(r.Form.Get("password"))
  631. confirmPassword := strings.TrimSpace(r.Form.Get("confirm_password"))
  632. admin, _, err := handleResetPassword(r, strings.TrimSpace(r.Form.Get("code")),
  633. newPassword, confirmPassword, true)
  634. if err != nil {
  635. s.renderResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric), ipAddr)
  636. return
  637. }
  638. s.loginAdmin(w, r, admin, false, s.renderResetPwdPage, ipAddr)
  639. }
  640. func (s *httpdServer) handleWebAdminSetupPost(w http.ResponseWriter, r *http.Request) {
  641. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  642. if dataprovider.HasAdmin() {
  643. s.renderBadRequestPage(w, r, errors.New("an admin user already exists"))
  644. return
  645. }
  646. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  647. err := r.ParseForm()
  648. if err != nil {
  649. s.renderAdminSetupPage(w, r, "", ipAddr, util.NewI18nError(err, util.I18nErrorInvalidForm))
  650. return
  651. }
  652. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  653. s.renderForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  654. return
  655. }
  656. username := strings.TrimSpace(r.Form.Get("username"))
  657. password := strings.TrimSpace(r.Form.Get("password"))
  658. confirmPassword := strings.TrimSpace(r.Form.Get("confirm_password"))
  659. installCode := strings.TrimSpace(r.Form.Get("install_code"))
  660. if installationCode != "" && installCode != resolveInstallationCode() {
  661. s.renderAdminSetupPage(w, r, username, ipAddr,
  662. util.NewI18nError(
  663. util.NewValidationError(fmt.Sprintf("%v mismatch", installationCodeHint)),
  664. util.I18nErrorSetupInstallCode),
  665. )
  666. return
  667. }
  668. if username == "" {
  669. s.renderAdminSetupPage(w, r, username, ipAddr,
  670. util.NewI18nError(util.NewValidationError("please set a username"), util.I18nError500Message))
  671. return
  672. }
  673. if password == "" {
  674. s.renderAdminSetupPage(w, r, username, ipAddr,
  675. util.NewI18nError(util.NewValidationError("please set a password"), util.I18nError500Message))
  676. return
  677. }
  678. if password != confirmPassword {
  679. s.renderAdminSetupPage(w, r, username, ipAddr,
  680. util.NewI18nError(errors.New("the two password fields do not match"), util.I18nErrorChangePwdNoMatch))
  681. return
  682. }
  683. admin := dataprovider.Admin{
  684. Username: username,
  685. Password: password,
  686. Status: 1,
  687. Permissions: []string{dataprovider.PermAdminAny},
  688. }
  689. err = dataprovider.AddAdmin(&admin, username, ipAddr, "")
  690. if err != nil {
  691. s.renderAdminSetupPage(w, r, username, ipAddr, util.NewI18nError(err, util.I18nError500Message))
  692. return
  693. }
  694. s.loginAdmin(w, r, &admin, false, nil, ipAddr)
  695. }
  696. func (s *httpdServer) loginUser(
  697. w http.ResponseWriter, r *http.Request, user *dataprovider.User, connectionID, ipAddr string,
  698. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string),
  699. ) {
  700. c := jwtTokenClaims{
  701. Username: user.Username,
  702. Permissions: user.Filters.WebClient,
  703. Signature: user.GetSignature(),
  704. Role: user.Role,
  705. MustSetTwoFactorAuth: user.MustSetSecondFactor(),
  706. MustChangePassword: user.MustChangePassword(),
  707. RequiredTwoFactorProtocols: user.Filters.TwoFactorAuthProtocols,
  708. }
  709. audience := tokenAudienceWebClient
  710. if user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) &&
  711. user.CanManageMFA() && !isSecondFactorAuth {
  712. audience = tokenAudienceWebClientPartial
  713. }
  714. err := c.createAndSetCookie(w, r, s.tokenAuth, audience, ipAddr)
  715. if err != nil {
  716. logger.Warn(logSender, connectionID, "unable to set user login cookie %v", err)
  717. updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  718. errorFunc(w, r, util.NewI18nError(err, util.I18nError500Message), ipAddr)
  719. return
  720. }
  721. if isSecondFactorAuth {
  722. invalidateToken(r)
  723. }
  724. if audience == tokenAudienceWebClientPartial {
  725. redirectPath := webClientTwoFactorPath
  726. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  727. redirectPath += "?next=" + url.QueryEscape(next)
  728. }
  729. http.Redirect(w, r, redirectPath, http.StatusFound)
  730. return
  731. }
  732. updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, err)
  733. dataprovider.UpdateLastLogin(user)
  734. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  735. http.Redirect(w, r, next, http.StatusFound)
  736. return
  737. }
  738. http.Redirect(w, r, webClientFilesPath, http.StatusFound)
  739. }
  740. func (s *httpdServer) loginAdmin(
  741. w http.ResponseWriter, r *http.Request, admin *dataprovider.Admin,
  742. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string),
  743. ipAddr string,
  744. ) {
  745. c := jwtTokenClaims{
  746. Username: admin.Username,
  747. Permissions: admin.Permissions,
  748. Role: admin.Role,
  749. Signature: admin.GetSignature(),
  750. HideUserPageSections: admin.Filters.Preferences.HideUserPageSections,
  751. MustSetTwoFactorAuth: admin.Filters.RequireTwoFactor && !admin.Filters.TOTPConfig.Enabled,
  752. MustChangePassword: admin.Filters.RequirePasswordChange,
  753. }
  754. audience := tokenAudienceWebAdmin
  755. if admin.Filters.TOTPConfig.Enabled && admin.CanManageMFA() && !isSecondFactorAuth {
  756. audience = tokenAudienceWebAdminPartial
  757. }
  758. err := c.createAndSetCookie(w, r, s.tokenAuth, audience, ipAddr)
  759. if err != nil {
  760. logger.Warn(logSender, "", "unable to set admin login cookie %v", err)
  761. if errorFunc == nil {
  762. s.renderAdminSetupPage(w, r, admin.Username, ipAddr, util.NewI18nError(err, util.I18nError500Message))
  763. return
  764. }
  765. errorFunc(w, r, util.NewI18nError(err, util.I18nError500Message), ipAddr)
  766. return
  767. }
  768. if isSecondFactorAuth {
  769. invalidateToken(r)
  770. }
  771. if audience == tokenAudienceWebAdminPartial {
  772. http.Redirect(w, r, webAdminTwoFactorPath, http.StatusFound)
  773. return
  774. }
  775. dataprovider.UpdateAdminLastLogin(admin)
  776. common.DelayLogin(nil)
  777. redirectURL := webUsersPath
  778. if errorFunc == nil {
  779. redirectURL = webAdminMFAPath
  780. }
  781. http.Redirect(w, r, redirectURL, http.StatusFound)
  782. }
  783. func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
  784. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  785. invalidateToken(r)
  786. sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
  787. }
  788. func (s *httpdServer) getUserToken(w http.ResponseWriter, r *http.Request) {
  789. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  790. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  791. username, password, ok := r.BasicAuth()
  792. protocol := common.ProtocolHTTP
  793. if !ok {
  794. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  795. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  796. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  797. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  798. return
  799. }
  800. if username == "" || password == "" {
  801. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  802. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  803. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  804. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  805. return
  806. }
  807. if err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
  808. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  809. dataprovider.LoginMethodPassword, ipAddr, err)
  810. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  811. return
  812. }
  813. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
  814. if err != nil {
  815. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  816. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  817. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  818. http.StatusUnauthorized)
  819. return
  820. }
  821. connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
  822. if err := checkHTTPClientUser(&user, r, connectionID, true); err != nil {
  823. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  824. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  825. return
  826. }
  827. if user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) {
  828. passcode := r.Header.Get(otpHeaderCode)
  829. if passcode == "" {
  830. logger.Debug(logSender, "", "TOTP enabled for user %q and not passcode provided, authentication refused", user.Username)
  831. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  832. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  833. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  834. http.StatusUnauthorized)
  835. return
  836. }
  837. err = user.Filters.TOTPConfig.Secret.Decrypt()
  838. if err != nil {
  839. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  840. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err), http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  841. return
  842. }
  843. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  844. user.Filters.TOTPConfig.Secret.GetPayload())
  845. if !match || err != nil {
  846. logger.Debug(logSender, "invalid passcode for user %q, match? %v, err: %v", user.Username, match, err)
  847. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  848. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  849. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  850. http.StatusUnauthorized)
  851. return
  852. }
  853. }
  854. defer user.CloseFs() //nolint:errcheck
  855. err = user.CheckFsRoot(connectionID)
  856. if err != nil {
  857. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  858. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  859. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  860. return
  861. }
  862. s.generateAndSendUserToken(w, r, ipAddr, user)
  863. }
  864. func (s *httpdServer) generateAndSendUserToken(w http.ResponseWriter, r *http.Request, ipAddr string, user dataprovider.User) {
  865. c := jwtTokenClaims{
  866. Username: user.Username,
  867. Permissions: user.Filters.WebClient,
  868. Signature: user.GetSignature(),
  869. Role: user.Role,
  870. MustSetTwoFactorAuth: user.MustSetSecondFactor(),
  871. MustChangePassword: user.MustChangePassword(),
  872. RequiredTwoFactorProtocols: user.Filters.TwoFactorAuthProtocols,
  873. }
  874. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPIUser, ipAddr)
  875. if err != nil {
  876. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  877. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  878. return
  879. }
  880. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  881. dataprovider.UpdateLastLogin(&user)
  882. render.JSON(w, r, resp)
  883. }
  884. func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
  885. username, password, ok := r.BasicAuth()
  886. if !ok {
  887. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  888. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  889. return
  890. }
  891. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  892. admin, err := dataprovider.CheckAdminAndPass(username, password, ipAddr)
  893. if err != nil {
  894. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  895. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  896. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  897. http.StatusUnauthorized)
  898. return
  899. }
  900. if admin.Filters.TOTPConfig.Enabled {
  901. passcode := r.Header.Get(otpHeaderCode)
  902. if passcode == "" {
  903. logger.Debug(logSender, "", "TOTP enabled for admin %q and not passcode provided, authentication refused", admin.Username)
  904. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  905. err = handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials)
  906. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  907. return
  908. }
  909. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  910. if err != nil {
  911. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err),
  912. http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  913. return
  914. }
  915. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  916. admin.Filters.TOTPConfig.Secret.GetPayload())
  917. if !match || err != nil {
  918. logger.Debug(logSender, "invalid passcode for admin %q, match? %v, err: %v", admin.Username, match, err)
  919. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  920. err = handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials)
  921. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized),
  922. http.StatusUnauthorized)
  923. return
  924. }
  925. }
  926. s.generateAndSendToken(w, r, admin, ipAddr)
  927. }
  928. func (s *httpdServer) generateAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin, ip string) {
  929. c := jwtTokenClaims{
  930. Username: admin.Username,
  931. Permissions: admin.Permissions,
  932. Role: admin.Role,
  933. Signature: admin.GetSignature(),
  934. MustSetTwoFactorAuth: admin.Filters.RequireTwoFactor && !admin.Filters.TOTPConfig.Enabled,
  935. MustChangePassword: admin.Filters.RequirePasswordChange,
  936. }
  937. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI, ip)
  938. if err != nil {
  939. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  940. return
  941. }
  942. dataprovider.UpdateAdminLastLogin(&admin)
  943. common.DelayLogin(nil)
  944. render.JSON(w, r, resp)
  945. }
  946. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  947. if _, ok := r.Context().Value(oidcTokenKey).(string); ok {
  948. return
  949. }
  950. token, claims, err := jwtauth.FromContext(r.Context())
  951. if err != nil {
  952. return
  953. }
  954. tokenClaims := jwtTokenClaims{}
  955. tokenClaims.Decode(claims)
  956. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  957. return
  958. }
  959. if time.Until(token.Expiration()) > tokenRefreshThreshold {
  960. return
  961. }
  962. if util.Contains(token.Audience(), tokenAudienceWebClient) {
  963. s.refreshClientToken(w, r, tokenClaims)
  964. } else {
  965. s.refreshAdminToken(w, r, tokenClaims)
  966. }
  967. }
  968. func (s *httpdServer) refreshClientToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  969. user, err := dataprovider.GetUserWithGroupSettings(tokenClaims.Username, "")
  970. if err != nil {
  971. return
  972. }
  973. if user.GetSignature() != tokenClaims.Signature {
  974. logger.Debug(logSender, "", "signature mismatch for user %q, unable to refresh cookie", user.Username)
  975. return
  976. }
  977. if err := user.CheckLoginConditions(); err != nil {
  978. logger.Debug(logSender, "", "unable to refresh cookie for user %q: %v", user.Username, err)
  979. return
  980. }
  981. if err := checkHTTPClientUser(&user, r, xid.New().String(), true); err != nil {
  982. logger.Debug(logSender, "", "unable to refresh cookie for user %q: %v", user.Username, err)
  983. return
  984. }
  985. tokenClaims.Permissions = user.Filters.WebClient
  986. tokenClaims.Role = user.Role
  987. logger.Debug(logSender, "", "cookie refreshed for user %q", user.Username)
  988. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebClient, util.GetIPFromRemoteAddress(r.RemoteAddr)) //nolint:errcheck
  989. }
  990. func (s *httpdServer) refreshAdminToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  991. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  992. if err != nil {
  993. return
  994. }
  995. if admin.GetSignature() != tokenClaims.Signature {
  996. logger.Debug(logSender, "", "signature mismatch for admin %q, unable to refresh cookie", admin.Username)
  997. return
  998. }
  999. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1000. if err := admin.CanLogin(ipAddr); err != nil {
  1001. logger.Debug(logSender, "", "unable to refresh cookie for admin %q, err: %v", admin.Username, err)
  1002. return
  1003. }
  1004. tokenClaims.Permissions = admin.Permissions
  1005. tokenClaims.Role = admin.Role
  1006. tokenClaims.HideUserPageSections = admin.Filters.Preferences.HideUserPageSections
  1007. logger.Debug(logSender, "", "cookie refreshed for admin %q", admin.Username)
  1008. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebAdmin, ipAddr) //nolint:errcheck
  1009. }
  1010. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  1011. token, _, err := jwtauth.FromContext(r.Context())
  1012. if token == nil || err != nil {
  1013. _, err = r.Cookie(jwtCookieKey)
  1014. if err != nil {
  1015. return r
  1016. }
  1017. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  1018. ctx := jwtauth.NewContext(r.Context(), token, err)
  1019. return r.WithContext(ctx)
  1020. }
  1021. return r
  1022. }
  1023. func (s *httpdServer) parseHeaders(next http.Handler) http.Handler {
  1024. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1025. w.Header().Set("Server", version.GetServerVersion("/", false))
  1026. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1027. var ip net.IP
  1028. isUnixSocket := filepath.IsAbs(s.binding.Address)
  1029. if !isUnixSocket {
  1030. ip = net.ParseIP(ipAddr)
  1031. }
  1032. areHeadersAllowed := false
  1033. if isUnixSocket || ip != nil {
  1034. for _, allow := range s.binding.allowHeadersFrom {
  1035. if allow(ip) {
  1036. parsedIP := util.GetRealIP(r, s.binding.ClientIPProxyHeader, s.binding.ClientIPHeaderDepth)
  1037. if parsedIP != "" {
  1038. ipAddr = parsedIP
  1039. r.RemoteAddr = ipAddr
  1040. }
  1041. if forwardedProto := r.Header.Get(xForwardedProto); forwardedProto != "" {
  1042. ctx := context.WithValue(r.Context(), forwardedProtoKey, forwardedProto)
  1043. r = r.WithContext(ctx)
  1044. }
  1045. areHeadersAllowed = true
  1046. break
  1047. }
  1048. }
  1049. }
  1050. if !areHeadersAllowed {
  1051. for idx := range s.binding.Security.proxyHeaders {
  1052. r.Header.Del(s.binding.Security.proxyHeaders[idx])
  1053. }
  1054. }
  1055. next.ServeHTTP(w, r)
  1056. })
  1057. }
  1058. func (s *httpdServer) checkConnection(next http.Handler) http.Handler {
  1059. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1060. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1061. common.Connections.AddClientConnection(ipAddr)
  1062. defer common.Connections.RemoveClientConnection(ipAddr)
  1063. if err := common.Connections.IsNewConnectionAllowed(ipAddr, common.ProtocolHTTP); err != nil {
  1064. logger.Log(logger.LevelDebug, common.ProtocolHTTP, "", "connection not allowed from ip %q: %v", ipAddr, err)
  1065. s.sendForbiddenResponse(w, r, util.NewI18nError(err, util.I18nErrorConnectionForbidden))
  1066. return
  1067. }
  1068. if common.IsBanned(ipAddr, common.ProtocolHTTP) {
  1069. s.sendForbiddenResponse(w, r, util.NewI18nError(
  1070. util.NewGenericError("your IP address is blocked"),
  1071. util.I18nErrorIPForbidden),
  1072. )
  1073. return
  1074. }
  1075. if delay, err := common.LimitRate(common.ProtocolHTTP, ipAddr); err != nil {
  1076. delay += 499999999 * time.Nanosecond
  1077. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  1078. w.Header().Set("X-Retry-In", delay.String())
  1079. s.sendTooManyRequestResponse(w, r, err)
  1080. return
  1081. }
  1082. next.ServeHTTP(w, r)
  1083. })
  1084. }
  1085. func (s *httpdServer) sendTooManyRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
  1086. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1087. r = s.updateContextFromCookie(r)
  1088. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1089. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1090. util.NewI18nError(errors.New(http.StatusText(http.StatusTooManyRequests)), util.I18nError429Message), "")
  1091. return
  1092. }
  1093. s.renderMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1094. util.NewI18nError(errors.New(http.StatusText(http.StatusTooManyRequests)), util.I18nError429Message), "")
  1095. return
  1096. }
  1097. sendAPIResponse(w, r, err, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
  1098. }
  1099. func (s *httpdServer) sendForbiddenResponse(w http.ResponseWriter, r *http.Request, err error) {
  1100. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1101. r = s.updateContextFromCookie(r)
  1102. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1103. s.renderClientForbiddenPage(w, r, err)
  1104. return
  1105. }
  1106. s.renderForbiddenPage(w, r, err)
  1107. return
  1108. }
  1109. sendAPIResponse(w, r, err, "", http.StatusForbidden)
  1110. }
  1111. func (s *httpdServer) badHostHandler(w http.ResponseWriter, r *http.Request) {
  1112. host := r.Host
  1113. for _, header := range s.binding.Security.HostsProxyHeaders {
  1114. if h := r.Header.Get(header); h != "" {
  1115. host = h
  1116. break
  1117. }
  1118. }
  1119. s.sendForbiddenResponse(w, r, util.NewI18nError(
  1120. util.NewGenericError(fmt.Sprintf("The host %q is not allowed", host)),
  1121. util.I18nErrorConnectionForbidden,
  1122. ))
  1123. }
  1124. func (s *httpdServer) notFoundHandler(w http.ResponseWriter, r *http.Request) {
  1125. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1126. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1127. r = s.updateContextFromCookie(r)
  1128. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1129. s.renderClientNotFoundPage(w, r, nil)
  1130. return
  1131. }
  1132. s.renderNotFoundPage(w, r, nil)
  1133. return
  1134. }
  1135. sendAPIResponse(w, r, nil, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  1136. }
  1137. func (s *httpdServer) redirectToWebPath(w http.ResponseWriter, r *http.Request, webPath string) {
  1138. if dataprovider.HasAdmin() {
  1139. http.Redirect(w, r, webPath, http.StatusFound)
  1140. return
  1141. }
  1142. if s.enableWebAdmin {
  1143. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  1144. }
  1145. }
  1146. // The StripSlashes causes infinite redirects at the root path if used with http.FileServer.
  1147. // We also don't strip paths with more than one trailing slash, see #1434
  1148. func (s *httpdServer) mustStripSlash(r *http.Request) bool {
  1149. urlPath := getURLPath(r)
  1150. return !strings.HasSuffix(urlPath, "//") && !strings.HasPrefix(urlPath, webOpenAPIPath) &&
  1151. !strings.HasPrefix(urlPath, webStaticFilesPath) && !strings.HasPrefix(urlPath, acmeChallengeURI)
  1152. }
  1153. func (s *httpdServer) mustCheckPath(r *http.Request) bool {
  1154. urlPath := getURLPath(r)
  1155. return !strings.HasPrefix(urlPath, webStaticFilesPath) && !strings.HasPrefix(urlPath, acmeChallengeURI)
  1156. }
  1157. func (s *httpdServer) initializeRouter() {
  1158. var hasHTTPSRedirect bool
  1159. s.tokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(s.signingPassphrase), nil)
  1160. s.router = chi.NewRouter()
  1161. s.router.Use(middleware.RequestID)
  1162. s.router.Use(s.parseHeaders)
  1163. s.router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  1164. s.router.Use(middleware.Recoverer)
  1165. if s.binding.Security.Enabled {
  1166. secureMiddleware := secure.New(secure.Options{
  1167. AllowedHosts: s.binding.Security.AllowedHosts,
  1168. AllowedHostsAreRegex: s.binding.Security.AllowedHostsAreRegex,
  1169. HostsProxyHeaders: s.binding.Security.HostsProxyHeaders,
  1170. SSLProxyHeaders: s.binding.Security.getHTTPSProxyHeaders(),
  1171. STSSeconds: s.binding.Security.STSSeconds,
  1172. STSIncludeSubdomains: s.binding.Security.STSIncludeSubdomains,
  1173. STSPreload: s.binding.Security.STSPreload,
  1174. ContentTypeNosniff: s.binding.Security.ContentTypeNosniff,
  1175. ContentSecurityPolicy: s.binding.Security.ContentSecurityPolicy,
  1176. PermissionsPolicy: s.binding.Security.PermissionsPolicy,
  1177. CrossOriginOpenerPolicy: s.binding.Security.CrossOriginOpenerPolicy,
  1178. })
  1179. secureMiddleware.SetBadHostHandler(http.HandlerFunc(s.badHostHandler))
  1180. if s.binding.Security.CacheControl == "private" {
  1181. s.router.Use(cacheControlMiddleware)
  1182. }
  1183. s.router.Use(secureMiddleware.Handler)
  1184. if s.binding.Security.HTTPSRedirect {
  1185. s.router.Use(s.binding.Security.redirectHandler)
  1186. hasHTTPSRedirect = true
  1187. }
  1188. }
  1189. if s.cors.Enabled {
  1190. c := cors.New(cors.Options{
  1191. AllowedOrigins: util.RemoveDuplicates(s.cors.AllowedOrigins, true),
  1192. AllowedMethods: util.RemoveDuplicates(s.cors.AllowedMethods, true),
  1193. AllowedHeaders: util.RemoveDuplicates(s.cors.AllowedHeaders, true),
  1194. ExposedHeaders: util.RemoveDuplicates(s.cors.ExposedHeaders, true),
  1195. MaxAge: s.cors.MaxAge,
  1196. AllowCredentials: s.cors.AllowCredentials,
  1197. OptionsPassthrough: s.cors.OptionsPassthrough,
  1198. OptionsSuccessStatus: s.cors.OptionsSuccessStatus,
  1199. AllowPrivateNetwork: s.cors.AllowPrivateNetwork,
  1200. })
  1201. s.router.Use(c.Handler)
  1202. }
  1203. s.router.Use(middleware.Maybe(s.checkConnection, s.mustCheckPath))
  1204. s.router.Use(middleware.GetHead)
  1205. s.router.Use(middleware.Maybe(middleware.StripSlashes, s.mustStripSlash))
  1206. s.router.NotFound(s.notFoundHandler)
  1207. s.router.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  1208. render.PlainText(w, r, "ok")
  1209. })
  1210. if hasHTTPSRedirect {
  1211. if p := acme.GetHTTP01WebRoot(); p != "" {
  1212. serveStaticDir(s.router, acmeChallengeURI, p, true)
  1213. }
  1214. }
  1215. if s.enableRESTAPI {
  1216. // share API available to external users
  1217. s.router.Get(sharesPath+"/{id}", s.downloadFromShare) //nolint:goconst
  1218. s.router.Post(sharesPath+"/{id}", s.uploadFilesToShare)
  1219. s.router.Post(sharesPath+"/{id}/{name}", s.uploadFileToShare)
  1220. s.router.With(compressor.Handler).Get(sharesPath+"/{id}/dirs", s.readBrowsableShareContents)
  1221. s.router.Get(sharesPath+"/{id}/files", s.downloadBrowsableSharedFile)
  1222. s.router.Get(tokenPath, s.getToken)
  1223. s.router.Post(adminPath+"/{username}/forgot-password", forgotAdminPassword)
  1224. s.router.Post(adminPath+"/{username}/reset-password", resetAdminPassword)
  1225. s.router.Post(userPath+"/{username}/forgot-password", forgotUserPassword)
  1226. s.router.Post(userPath+"/{username}/reset-password", resetUserPassword)
  1227. s.router.Group(func(router chi.Router) {
  1228. router.Use(checkNodeToken(s.tokenAuth))
  1229. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeAdmin))
  1230. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1231. router.Use(jwtAuthenticatorAPI)
  1232. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  1233. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1234. render.JSON(w, r, version.Get())
  1235. })
  1236. router.With(forbidAPIKeyAuthentication).Get(logoutPath, s.logout)
  1237. router.With(forbidAPIKeyAuthentication).Get(adminProfilePath, getAdminProfile)
  1238. router.With(forbidAPIKeyAuthentication, s.checkAuthRequirements).Put(adminProfilePath, updateAdminProfile)
  1239. router.With(forbidAPIKeyAuthentication).Put(adminPwdPath, changeAdminPassword)
  1240. // admin TOTP APIs
  1241. router.With(forbidAPIKeyAuthentication).Get(adminTOTPConfigsPath, getTOTPConfigs)
  1242. router.With(forbidAPIKeyAuthentication).Post(adminTOTPGeneratePath, generateTOTPSecret)
  1243. router.With(forbidAPIKeyAuthentication).Post(adminTOTPValidatePath, validateTOTPPasscode)
  1244. router.With(forbidAPIKeyAuthentication).Post(adminTOTPSavePath, saveTOTPConfig)
  1245. router.With(forbidAPIKeyAuthentication).Get(admin2FARecoveryCodesPath, getRecoveryCodes)
  1246. router.With(forbidAPIKeyAuthentication).Post(admin2FARecoveryCodesPath, generateRecoveryCodes)
  1247. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1248. Get(apiKeysPath, getAPIKeys)
  1249. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1250. Post(apiKeysPath, addAPIKey)
  1251. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1252. Get(apiKeysPath+"/{id}", getAPIKeyByID)
  1253. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1254. Put(apiKeysPath+"/{id}", updateAPIKey)
  1255. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1256. Delete(apiKeysPath+"/{id}", deleteAPIKey)
  1257. router.Group(func(router chi.Router) {
  1258. router.Use(s.checkAuthRequirements)
  1259. router.With(s.checkPerm(dataprovider.PermAdminViewServerStatus)).
  1260. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  1261. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1262. render.JSON(w, r, getServicesStatus())
  1263. })
  1264. router.With(s.checkPerm(dataprovider.PermAdminViewConnections)).Get(activeConnectionsPath, getActiveConnections)
  1265. router.With(s.checkPerm(dataprovider.PermAdminCloseConnections)).
  1266. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  1267. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/users/scans", getUsersQuotaScans)
  1268. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/users/{username}/scan", startUserQuotaScan)
  1269. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/folders/scans", getFoldersQuotaScans)
  1270. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/folders/{name}/scan", startFolderQuotaScan)
  1271. router.With(s.checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  1272. router.With(s.checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  1273. router.With(s.checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername) //nolint:goconst
  1274. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  1275. router.With(s.checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  1276. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA)).Put(userPath+"/{username}/2fa/disable", disableUser2FA) //nolint:goconst
  1277. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Get(folderPath, getFolders)
  1278. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Get(folderPath+"/{name}", getFolderByName) //nolint:goconst
  1279. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(folderPath, addFolder)
  1280. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Put(folderPath+"/{name}", updateFolder)
  1281. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Delete(folderPath+"/{name}", deleteFolder)
  1282. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Get(groupPath, getGroups)
  1283. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Get(groupPath+"/{name}", getGroupByName)
  1284. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(groupPath, addGroup)
  1285. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Put(groupPath+"/{name}", updateGroup)
  1286. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Delete(groupPath+"/{name}", deleteGroup)
  1287. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(dumpDataPath, dumpData)
  1288. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(loadDataPath, loadData)
  1289. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(loadDataPath, loadDataFromRequest)
  1290. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/usage",
  1291. updateUserQuotaUsage)
  1292. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/transfer-usage",
  1293. updateUserTransferQuotaUsage)
  1294. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage",
  1295. updateFolderQuotaUsage)
  1296. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
  1297. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
  1298. router.With(s.checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
  1299. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(adminPath, getAdmins)
  1300. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(adminPath, addAdmin)
  1301. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(adminPath+"/{username}", getAdminByUsername)
  1302. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(adminPath+"/{username}", updateAdmin)
  1303. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(adminPath+"/{username}", deleteAdmin)
  1304. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1305. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(retentionChecksPath, getRetentionChecks)
  1306. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(retentionBasePath+"/{username}/check",
  1307. startRetentionCheck)
  1308. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1309. Get(fsEventsPath, searchFsEvents)
  1310. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1311. Get(providerEventsPath, searchProviderEvents)
  1312. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1313. Get(logEventsPath, searchLogEvents)
  1314. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventActionsPath, getEventActions)
  1315. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventActionsPath+"/{name}", getEventActionByName)
  1316. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(eventActionsPath, addEventAction)
  1317. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(eventActionsPath+"/{name}", updateEventAction)
  1318. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(eventActionsPath+"/{name}", deleteEventAction)
  1319. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventRulesPath, getEventRules)
  1320. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventRulesPath+"/{name}", getEventRuleByName)
  1321. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(eventRulesPath, addEventRule)
  1322. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(eventRulesPath+"/{name}", updateEventRule)
  1323. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(eventRulesPath+"/{name}", deleteEventRule)
  1324. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(eventRulesPath+"/run/{name}", runOnDemandRule)
  1325. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(rolesPath, getRoles)
  1326. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(rolesPath, addRole)
  1327. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(rolesPath+"/{name}", getRoleByName)
  1328. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(rolesPath+"/{name}", updateRole)
  1329. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(rolesPath+"/{name}", deleteRole)
  1330. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler).Get(ipListsPath+"/{type}", getIPListEntries) //nolint:goconst
  1331. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(ipListsPath+"/{type}", addIPListEntry)
  1332. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(ipListsPath+"/{type}/{ipornet}", getIPListEntry) //nolint:goconst
  1333. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(ipListsPath+"/{type}/{ipornet}", updateIPListEntry)
  1334. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(ipListsPath+"/{type}/{ipornet}", deleteIPListEntry)
  1335. })
  1336. })
  1337. s.router.Get(userTokenPath, s.getUserToken)
  1338. s.router.Group(func(router chi.Router) {
  1339. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
  1340. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1341. router.Use(jwtAuthenticatorAPIUser)
  1342. router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
  1343. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1344. Put(userPwdPath, changeUserPassword)
  1345. router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
  1346. router.With(forbidAPIKeyAuthentication, s.checkAuthRequirements).Put(userProfilePath, updateUserProfile)
  1347. // user TOTP APIs
  1348. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1349. Get(userTOTPConfigsPath, getTOTPConfigs)
  1350. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1351. Post(userTOTPGeneratePath, generateTOTPSecret)
  1352. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1353. Post(userTOTPValidatePath, validateTOTPPasscode)
  1354. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1355. Post(userTOTPSavePath, saveTOTPConfig)
  1356. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1357. Get(user2FARecoveryCodesPath, getRecoveryCodes)
  1358. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1359. Post(user2FARecoveryCodesPath, generateRecoveryCodes)
  1360. router.With(s.checkAuthRequirements, compressor.Handler).Get(userDirsPath, readUserFolder)
  1361. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1362. Post(userDirsPath, createUserDir)
  1363. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1364. Patch(userDirsPath, renameUserFsEntry)
  1365. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1366. Delete(userDirsPath, deleteUserDir)
  1367. router.With(s.checkAuthRequirements).Get(userFilesPath, getUserFile)
  1368. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1369. Post(userFilesPath, uploadUserFiles)
  1370. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1371. Patch(userFilesPath, renameUserFsEntry)
  1372. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1373. Delete(userFilesPath, deleteUserFile)
  1374. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1375. Post(userFileActionsPath+"/move", renameUserFsEntry)
  1376. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1377. Post(userFileActionsPath+"/copy", copyUserFsEntry)
  1378. router.With(s.checkAuthRequirements).Post(userStreamZipPath, getUserFilesAsZipStream)
  1379. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1380. Get(userSharesPath, getShares)
  1381. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1382. Post(userSharesPath, addShare)
  1383. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1384. Get(userSharesPath+"/{id}", getShareByID)
  1385. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1386. Put(userSharesPath+"/{id}", updateShare)
  1387. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1388. Delete(userSharesPath+"/{id}", deleteShare)
  1389. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1390. Post(userUploadFilePath, uploadUserFile)
  1391. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1392. Patch(userFilesDirsMetadataPath, setFileDirMetadata)
  1393. })
  1394. if s.renderOpenAPI {
  1395. s.router.Group(func(router chi.Router) {
  1396. router.Use(cleanCacheControlMiddleware)
  1397. router.Use(compressor.Handler)
  1398. serveStaticDir(router, webOpenAPIPath, s.openAPIPath, false)
  1399. })
  1400. }
  1401. }
  1402. if s.enableWebAdmin || s.enableWebClient {
  1403. s.router.Group(func(router chi.Router) {
  1404. router.Use(cleanCacheControlMiddleware)
  1405. router.Use(compressor.Handler)
  1406. serveStaticDir(router, webStaticFilesPath, s.staticFilesPath, true)
  1407. })
  1408. if s.binding.OIDC.isEnabled() {
  1409. s.router.Get(webOIDCRedirectPath, s.handleOIDCRedirect)
  1410. }
  1411. if s.enableWebClient {
  1412. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1413. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1414. s.redirectToWebPath(w, r, webClientLoginPath)
  1415. })
  1416. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1417. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1418. s.redirectToWebPath(w, r, webClientLoginPath)
  1419. })
  1420. } else {
  1421. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1422. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1423. s.redirectToWebPath(w, r, webAdminLoginPath)
  1424. })
  1425. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1426. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1427. s.redirectToWebPath(w, r, webAdminLoginPath)
  1428. })
  1429. }
  1430. }
  1431. s.setupWebClientRoutes()
  1432. s.setupWebAdminRoutes()
  1433. }
  1434. func (s *httpdServer) setupWebClientRoutes() {
  1435. if s.enableWebClient {
  1436. s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
  1437. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1438. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  1439. })
  1440. s.router.Get(webClientLoginPath, s.handleClientWebLogin)
  1441. if s.binding.OIDC.isEnabled() && !s.binding.isWebClientOIDCLoginDisabled() {
  1442. s.router.Get(webClientOIDCLoginPath, s.handleWebClientOIDCLogin)
  1443. }
  1444. if !s.binding.isWebClientLoginFormDisabled() {
  1445. s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
  1446. s.router.Get(webClientForgotPwdPath, s.handleWebClientForgotPwd)
  1447. s.router.Post(webClientForgotPwdPath, s.handleWebClientForgotPwdPost)
  1448. s.router.Get(webClientResetPwdPath, s.handleWebClientPasswordReset)
  1449. s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
  1450. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1451. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1452. Get(webClientTwoFactorPath, s.handleWebClientTwoFactor)
  1453. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1454. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1455. Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
  1456. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1457. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1458. Get(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecovery)
  1459. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1460. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1461. Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
  1462. }
  1463. // share routes available to external users
  1464. s.router.Get(webClientPubSharesPath+"/{id}/login", s.handleClientShareLoginGet)
  1465. s.router.Post(webClientPubSharesPath+"/{id}/login", s.handleClientShareLoginPost)
  1466. s.router.Get(webClientPubSharesPath+"/{id}", s.downloadFromShare)
  1467. s.router.Post(webClientPubSharesPath+"/{id}/partial", s.handleClientSharePartialDownload)
  1468. s.router.Get(webClientPubSharesPath+"/{id}/browse", s.handleShareGetFiles)
  1469. s.router.Post(webClientPubSharesPath+"/{id}/browse/exist", s.handleClientShareCheckExist)
  1470. s.router.Get(webClientPubSharesPath+"/{id}/download", s.handleClientSharedFile)
  1471. s.router.Get(webClientPubSharesPath+"/{id}/upload", s.handleClientUploadToShare)
  1472. s.router.With(compressor.Handler).Get(webClientPubSharesPath+"/{id}/dirs", s.handleShareGetDirContents)
  1473. s.router.Post(webClientPubSharesPath+"/{id}", s.uploadFilesToShare)
  1474. s.router.Post(webClientPubSharesPath+"/{id}/{name}", s.uploadFileToShare)
  1475. s.router.Get(webClientPubSharesPath+"/{id}/viewpdf", s.handleShareViewPDF)
  1476. s.router.Get(webClientPubSharesPath+"/{id}/getpdf", s.handleShareGetPDF)
  1477. s.router.Group(func(router chi.Router) {
  1478. if s.binding.OIDC.isEnabled() {
  1479. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebClient))
  1480. }
  1481. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1482. router.Use(jwtAuthenticatorWebClient)
  1483. router.Get(webClientLogoutPath, s.handleWebClientLogout)
  1484. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
  1485. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientViewPDFPath, s.handleClientViewPDF)
  1486. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientGetPDFPath, s.handleClientGetPDF)
  1487. router.With(s.checkAuthRequirements, s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
  1488. router.With(s.checkAuthRequirements, s.refreshCookie, verifyCSRFHeader).Get(webClientTasksPath+"/{id}",
  1489. getWebTask)
  1490. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1491. Post(webClientFilePath, uploadUserFile)
  1492. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1493. Post(webClientExistPath, s.handleClientCheckExist)
  1494. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientEditFilePath, s.handleClientEditFile)
  1495. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1496. Delete(webClientFilesPath, deleteUserFile)
  1497. router.With(s.checkAuthRequirements, compressor.Handler, s.refreshCookie).
  1498. Get(webClientDirsPath, s.handleClientGetDirContents)
  1499. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1500. Post(webClientDirsPath, createUserDir)
  1501. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1502. Delete(webClientDirsPath, taskDeleteDir)
  1503. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1504. Post(webClientFileActionsPath+"/move", taskRenameFsEntry)
  1505. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1506. Post(webClientFileActionsPath+"/copy", taskCopyFsEntry)
  1507. router.With(s.checkAuthRequirements, s.refreshCookie).
  1508. Post(webClientDownloadZipPath, s.handleWebClientDownloadZip)
  1509. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientPingPath, handlePingRequest)
  1510. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientProfilePath,
  1511. s.handleClientGetProfile)
  1512. router.With(s.checkAuthRequirements).Post(webClientProfilePath, s.handleWebClientProfilePost)
  1513. router.With(s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1514. Get(webChangeClientPwdPath, s.handleWebClientChangePwd)
  1515. router.With(s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1516. Post(webChangeClientPwdPath, s.handleWebClientChangePwdPost)
  1517. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1518. Get(webClientMFAPath, s.handleWebClientMFA)
  1519. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1520. Get(webClientMFAPath+"/qrcode", getQRCode)
  1521. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1522. Post(webClientTOTPGeneratePath, generateTOTPSecret)
  1523. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1524. Post(webClientTOTPValidatePath, validateTOTPPasscode)
  1525. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1526. Post(webClientTOTPSavePath, saveTOTPConfig)
  1527. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
  1528. Get(webClientRecoveryCodesPath, getRecoveryCodes)
  1529. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1530. Post(webClientRecoveryCodesPath, generateRecoveryCodes)
  1531. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), compressor.Handler, s.refreshCookie).
  1532. Get(webClientSharesPath+jsonAPISuffix, getAllShares)
  1533. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1534. Get(webClientSharesPath, s.handleClientGetShares)
  1535. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1536. Get(webClientSharePath, s.handleClientAddShareGet)
  1537. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1538. Post(webClientSharePath, s.handleClientAddSharePost)
  1539. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1540. Get(webClientSharePath+"/{id}", s.handleClientUpdateShareGet)
  1541. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1542. Post(webClientSharePath+"/{id}", s.handleClientUpdateSharePost)
  1543. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
  1544. Delete(webClientSharePath+"/{id}", deleteShare)
  1545. })
  1546. }
  1547. }
  1548. func (s *httpdServer) setupWebAdminRoutes() {
  1549. if s.enableWebAdmin {
  1550. s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
  1551. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1552. s.redirectToWebPath(w, r, webAdminLoginPath)
  1553. })
  1554. s.router.Get(webAdminLoginPath, s.handleWebAdminLogin)
  1555. if s.binding.OIDC.hasRoles() && !s.binding.isWebAdminOIDCLoginDisabled() {
  1556. s.router.Get(webAdminOIDCLoginPath, s.handleWebAdminOIDCLogin)
  1557. }
  1558. s.router.Get(webOAuth2RedirectPath, s.handleOAuth2TokenRedirect)
  1559. s.router.Get(webAdminSetupPath, s.handleWebAdminSetupGet)
  1560. s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
  1561. if !s.binding.isWebAdminLoginFormDisabled() {
  1562. s.router.Post(webAdminLoginPath, s.handleWebAdminLoginPost)
  1563. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1564. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1565. Get(webAdminTwoFactorPath, s.handleWebAdminTwoFactor)
  1566. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1567. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1568. Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
  1569. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1570. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1571. Get(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecovery)
  1572. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1573. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1574. Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
  1575. s.router.Get(webAdminForgotPwdPath, s.handleWebAdminForgotPwd)
  1576. s.router.Post(webAdminForgotPwdPath, s.handleWebAdminForgotPwdPost)
  1577. s.router.Get(webAdminResetPwdPath, s.handleWebAdminPasswordReset)
  1578. s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
  1579. }
  1580. s.router.Group(func(router chi.Router) {
  1581. if s.binding.OIDC.isEnabled() {
  1582. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebAdmin))
  1583. }
  1584. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1585. router.Use(jwtAuthenticatorWebAdmin)
  1586. router.Get(webLogoutPath, s.handleWebAdminLogout)
  1587. router.With(s.refreshCookie, s.checkAuthRequirements, s.requireBuiltinLogin).Get(
  1588. webAdminProfilePath, s.handleWebAdminProfile)
  1589. router.With(s.checkAuthRequirements, s.requireBuiltinLogin).Post(webAdminProfilePath, s.handleWebAdminProfilePost)
  1590. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webChangeAdminPwdPath, s.handleWebAdminChangePwd)
  1591. router.With(s.requireBuiltinLogin).Post(webChangeAdminPwdPath, s.handleWebAdminChangePwdPost)
  1592. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminMFAPath, s.handleWebAdminMFA)
  1593. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminMFAPath+"/qrcode", getQRCode)
  1594. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
  1595. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
  1596. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPSavePath, saveTOTPConfig)
  1597. router.With(verifyCSRFHeader, s.requireBuiltinLogin, s.refreshCookie).Get(webAdminRecoveryCodesPath,
  1598. getRecoveryCodes)
  1599. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
  1600. router.Group(func(router chi.Router) {
  1601. router.Use(s.checkAuthRequirements)
  1602. router.With(s.checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1603. Get(webUsersPath, s.handleGetWebUsers)
  1604. router.With(s.checkPerm(dataprovider.PermAdminViewUsers), compressor.Handler, s.refreshCookie).
  1605. Get(webUsersPath+jsonAPISuffix, getAllUsers)
  1606. router.With(s.checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1607. Get(webUserPath, s.handleWebAddUserGet)
  1608. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1609. Get(webUserPath+"/{username}", s.handleWebUpdateUserGet)
  1610. router.With(s.checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, s.handleWebAddUserPost)
  1611. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}",
  1612. s.handleWebUpdateUserPost)
  1613. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1614. Get(webGroupsPath, s.handleWebGetGroups)
  1615. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), compressor.Handler, s.refreshCookie).
  1616. Get(webGroupsPath+jsonAPISuffix, getAllGroups)
  1617. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1618. Get(webGroupPath, s.handleWebAddGroupGet)
  1619. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(webGroupPath, s.handleWebAddGroupPost)
  1620. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1621. Get(webGroupPath+"/{name}", s.handleWebUpdateGroupGet)
  1622. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(webGroupPath+"/{name}",
  1623. s.handleWebUpdateGroupPost)
  1624. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), verifyCSRFHeader).
  1625. Delete(webGroupPath+"/{name}", deleteGroup)
  1626. router.With(s.checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1627. Get(webConnectionsPath, s.handleWebGetConnections)
  1628. router.With(s.checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1629. Get(webConnectionsPath+jsonAPISuffix, getActiveConnections)
  1630. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1631. Get(webFoldersPath, s.handleWebGetFolders)
  1632. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), compressor.Handler, s.refreshCookie).
  1633. Get(webFoldersPath+jsonAPISuffix, getAllFolders)
  1634. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1635. Get(webFolderPath, s.handleWebAddFolderGet)
  1636. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(webFolderPath, s.handleWebAddFolderPost)
  1637. router.With(s.checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  1638. Get(webStatusPath, s.handleWebGetStatus)
  1639. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1640. Get(webAdminsPath, s.handleGetWebAdmins)
  1641. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1642. Get(webAdminsPath+jsonAPISuffix, getAllAdmins)
  1643. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1644. Get(webAdminPath, s.handleWebAddAdminGet)
  1645. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1646. Get(webAdminPath+"/{username}", s.handleWebUpdateAdminGet)
  1647. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminPath, s.handleWebAddAdminPost)
  1648. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminPath+"/{username}",
  1649. s.handleWebUpdateAdminPost)
  1650. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1651. Delete(webAdminPath+"/{username}", deleteAdmin)
  1652. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA), verifyCSRFHeader).
  1653. Put(webAdminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1654. router.With(s.checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  1655. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  1656. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1657. Get(webFolderPath+"/{name}", s.handleWebUpdateFolderGet)
  1658. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(webFolderPath+"/{name}",
  1659. s.handleWebUpdateFolderPost)
  1660. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), verifyCSRFHeader).
  1661. Delete(webFolderPath+"/{name}", deleteFolder)
  1662. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1663. Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
  1664. router.With(s.checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1665. Delete(webUserPath+"/{username}", deleteUser)
  1666. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA), verifyCSRFHeader).
  1667. Put(webUserPath+"/{username}/2fa/disable", disableUser2FA)
  1668. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1669. Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
  1670. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(webMaintenancePath, s.handleWebMaintenance)
  1671. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(webBackupPath, dumpData)
  1672. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webRestorePath, s.handleWebRestore)
  1673. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1674. Get(webTemplateUser, s.handleWebTemplateUserGet)
  1675. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webTemplateUser, s.handleWebTemplateUserPost)
  1676. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1677. Get(webTemplateFolder, s.handleWebTemplateFolderGet)
  1678. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webTemplateFolder, s.handleWebTemplateFolderPost)
  1679. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, s.handleWebDefenderPage)
  1680. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
  1681. router.With(s.checkPerm(dataprovider.PermAdminManageDefender), verifyCSRFHeader).
  1682. Delete(webDefenderHostsPath+"/{id}", deleteDefenderHostByID)
  1683. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1684. Get(webAdminEventActionsPath+jsonAPISuffix, getAllActions)
  1685. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1686. Get(webAdminEventActionsPath, s.handleWebGetEventActions)
  1687. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1688. Get(webAdminEventActionPath, s.handleWebAddEventActionGet)
  1689. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventActionPath,
  1690. s.handleWebAddEventActionPost)
  1691. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1692. Get(webAdminEventActionPath+"/{name}", s.handleWebUpdateEventActionGet)
  1693. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventActionPath+"/{name}",
  1694. s.handleWebUpdateEventActionPost)
  1695. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1696. Delete(webAdminEventActionPath+"/{name}", deleteEventAction)
  1697. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1698. Get(webAdminEventRulesPath+jsonAPISuffix, getAllRules)
  1699. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1700. Get(webAdminEventRulesPath, s.handleWebGetEventRules)
  1701. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1702. Get(webAdminEventRulePath, s.handleWebAddEventRuleGet)
  1703. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventRulePath,
  1704. s.handleWebAddEventRulePost)
  1705. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1706. Get(webAdminEventRulePath+"/{name}", s.handleWebUpdateEventRuleGet)
  1707. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventRulePath+"/{name}",
  1708. s.handleWebUpdateEventRulePost)
  1709. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1710. Delete(webAdminEventRulePath+"/{name}", deleteEventRule)
  1711. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1712. Post(webAdminEventRulePath+"/run/{name}", runOnDemandRule)
  1713. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1714. Get(webAdminRolesPath, s.handleWebGetRoles)
  1715. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1716. Get(webAdminRolesPath+jsonAPISuffix, getAllRoles)
  1717. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1718. Get(webAdminRolePath, s.handleWebAddRoleGet)
  1719. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminRolePath, s.handleWebAddRolePost)
  1720. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1721. Get(webAdminRolePath+"/{name}", s.handleWebUpdateRoleGet)
  1722. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminRolePath+"/{name}",
  1723. s.handleWebUpdateRolePost)
  1724. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1725. Delete(webAdminRolePath+"/{name}", deleteRole)
  1726. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), s.refreshCookie).Get(webEventsPath,
  1727. s.handleWebGetEvents)
  1728. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1729. Get(webEventsFsSearchPath, searchFsEvents)
  1730. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1731. Get(webEventsProviderSearchPath, searchProviderEvents)
  1732. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1733. Get(webEventsLogSearchPath, searchLogEvents)
  1734. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(webIPListsPath, s.handleWebIPListsPage)
  1735. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1736. Get(webIPListsPath+"/{type}", getIPListEntries)
  1737. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).Get(webIPListPath+"/{type}",
  1738. s.handleWebAddIPListEntryGet)
  1739. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webIPListPath+"/{type}",
  1740. s.handleWebAddIPListEntryPost)
  1741. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).Get(webIPListPath+"/{type}/{ipornet}",
  1742. s.handleWebUpdateIPListEntryGet)
  1743. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webIPListPath+"/{type}/{ipornet}",
  1744. s.handleWebUpdateIPListEntryPost)
  1745. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1746. Delete(webIPListPath+"/{type}/{ipornet}", deleteIPListEntry)
  1747. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).Get(webConfigsPath, s.handleWebConfigs)
  1748. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webConfigsPath, s.handleWebConfigsPost)
  1749. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader, s.refreshCookie).
  1750. Post(webConfigsPath+"/smtp/test", testSMTPConfig)
  1751. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader, s.refreshCookie).
  1752. Post(webOAuth2TokenPath, handleSMTPOAuth2TokenRequestPost)
  1753. })
  1754. })
  1755. }
  1756. }