server.go 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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. err = handleDefenderEventLoginFailed(ipAddr, err)
  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. err = handleDefenderEventLoginFailed(ipAddr, err)
  895. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  896. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  897. return
  898. }
  899. if admin.Filters.TOTPConfig.Enabled {
  900. passcode := r.Header.Get(otpHeaderCode)
  901. if passcode == "" {
  902. logger.Debug(logSender, "", "TOTP enabled for admin %q and not passcode provided, authentication refused", admin.Username)
  903. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  904. err = handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials)
  905. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  906. return
  907. }
  908. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  909. if err != nil {
  910. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err),
  911. http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  912. return
  913. }
  914. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  915. admin.Filters.TOTPConfig.Secret.GetPayload())
  916. if !match || err != nil {
  917. logger.Debug(logSender, "invalid passcode for admin %q, match? %v, err: %v", admin.Username, match, err)
  918. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  919. err = handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials)
  920. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized),
  921. http.StatusUnauthorized)
  922. return
  923. }
  924. }
  925. s.generateAndSendToken(w, r, admin, ipAddr)
  926. }
  927. func (s *httpdServer) generateAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin, ip string) {
  928. c := jwtTokenClaims{
  929. Username: admin.Username,
  930. Permissions: admin.Permissions,
  931. Role: admin.Role,
  932. Signature: admin.GetSignature(),
  933. MustSetTwoFactorAuth: admin.Filters.RequireTwoFactor && !admin.Filters.TOTPConfig.Enabled,
  934. MustChangePassword: admin.Filters.RequirePasswordChange,
  935. }
  936. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI, ip)
  937. if err != nil {
  938. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  939. return
  940. }
  941. dataprovider.UpdateAdminLastLogin(&admin)
  942. common.DelayLogin(nil)
  943. render.JSON(w, r, resp)
  944. }
  945. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  946. if _, ok := r.Context().Value(oidcTokenKey).(string); ok {
  947. return
  948. }
  949. token, claims, err := jwtauth.FromContext(r.Context())
  950. if err != nil {
  951. return
  952. }
  953. tokenClaims := jwtTokenClaims{}
  954. tokenClaims.Decode(claims)
  955. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  956. return
  957. }
  958. if time.Until(token.Expiration()) > tokenRefreshThreshold {
  959. return
  960. }
  961. if util.Contains(token.Audience(), tokenAudienceWebClient) {
  962. s.refreshClientToken(w, r, tokenClaims)
  963. } else {
  964. s.refreshAdminToken(w, r, tokenClaims)
  965. }
  966. }
  967. func (s *httpdServer) refreshClientToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  968. user, err := dataprovider.GetUserWithGroupSettings(tokenClaims.Username, "")
  969. if err != nil {
  970. return
  971. }
  972. if user.GetSignature() != tokenClaims.Signature {
  973. logger.Debug(logSender, "", "signature mismatch for user %q, unable to refresh cookie", user.Username)
  974. return
  975. }
  976. if err := user.CheckLoginConditions(); err != nil {
  977. logger.Debug(logSender, "", "unable to refresh cookie for user %q: %v", user.Username, err)
  978. return
  979. }
  980. if err := checkHTTPClientUser(&user, r, xid.New().String(), true); err != nil {
  981. logger.Debug(logSender, "", "unable to refresh cookie for user %q: %v", user.Username, err)
  982. return
  983. }
  984. tokenClaims.Permissions = user.Filters.WebClient
  985. tokenClaims.Role = user.Role
  986. logger.Debug(logSender, "", "cookie refreshed for user %q", user.Username)
  987. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebClient, util.GetIPFromRemoteAddress(r.RemoteAddr)) //nolint:errcheck
  988. }
  989. func (s *httpdServer) refreshAdminToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  990. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  991. if err != nil {
  992. return
  993. }
  994. if admin.GetSignature() != tokenClaims.Signature {
  995. logger.Debug(logSender, "", "signature mismatch for admin %q, unable to refresh cookie", admin.Username)
  996. return
  997. }
  998. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  999. if err := admin.CanLogin(ipAddr); err != nil {
  1000. logger.Debug(logSender, "", "unable to refresh cookie for admin %q, err: %v", admin.Username, err)
  1001. return
  1002. }
  1003. tokenClaims.Permissions = admin.Permissions
  1004. tokenClaims.Role = admin.Role
  1005. tokenClaims.HideUserPageSections = admin.Filters.Preferences.HideUserPageSections
  1006. logger.Debug(logSender, "", "cookie refreshed for admin %q", admin.Username)
  1007. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebAdmin, ipAddr) //nolint:errcheck
  1008. }
  1009. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  1010. token, _, err := jwtauth.FromContext(r.Context())
  1011. if token == nil || err != nil {
  1012. _, err = r.Cookie(jwtCookieKey)
  1013. if err != nil {
  1014. return r
  1015. }
  1016. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  1017. ctx := jwtauth.NewContext(r.Context(), token, err)
  1018. return r.WithContext(ctx)
  1019. }
  1020. return r
  1021. }
  1022. func (s *httpdServer) parseHeaders(next http.Handler) http.Handler {
  1023. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1024. w.Header().Set("Server", version.GetServerVersion("/", false))
  1025. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1026. var ip net.IP
  1027. isUnixSocket := filepath.IsAbs(s.binding.Address)
  1028. if !isUnixSocket {
  1029. ip = net.ParseIP(ipAddr)
  1030. }
  1031. areHeadersAllowed := false
  1032. if isUnixSocket || ip != nil {
  1033. for _, allow := range s.binding.allowHeadersFrom {
  1034. if allow(ip) {
  1035. parsedIP := util.GetRealIP(r, s.binding.ClientIPProxyHeader, s.binding.ClientIPHeaderDepth)
  1036. if parsedIP != "" {
  1037. ipAddr = parsedIP
  1038. r.RemoteAddr = ipAddr
  1039. }
  1040. if forwardedProto := r.Header.Get(xForwardedProto); forwardedProto != "" {
  1041. ctx := context.WithValue(r.Context(), forwardedProtoKey, forwardedProto)
  1042. r = r.WithContext(ctx)
  1043. }
  1044. areHeadersAllowed = true
  1045. break
  1046. }
  1047. }
  1048. }
  1049. if !areHeadersAllowed {
  1050. for idx := range s.binding.Security.proxyHeaders {
  1051. r.Header.Del(s.binding.Security.proxyHeaders[idx])
  1052. }
  1053. }
  1054. next.ServeHTTP(w, r)
  1055. })
  1056. }
  1057. func (s *httpdServer) checkConnection(next http.Handler) http.Handler {
  1058. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1059. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1060. common.Connections.AddClientConnection(ipAddr)
  1061. defer common.Connections.RemoveClientConnection(ipAddr)
  1062. if err := common.Connections.IsNewConnectionAllowed(ipAddr, common.ProtocolHTTP); err != nil {
  1063. logger.Log(logger.LevelDebug, common.ProtocolHTTP, "", "connection not allowed from ip %q: %v", ipAddr, err)
  1064. s.sendForbiddenResponse(w, r, util.NewI18nError(err, util.I18nErrorConnectionForbidden))
  1065. return
  1066. }
  1067. if common.IsBanned(ipAddr, common.ProtocolHTTP) {
  1068. s.sendForbiddenResponse(w, r, util.NewI18nError(
  1069. util.NewGenericError("your IP address is blocked"),
  1070. util.I18nErrorIPForbidden),
  1071. )
  1072. return
  1073. }
  1074. if delay, err := common.LimitRate(common.ProtocolHTTP, ipAddr); err != nil {
  1075. delay += 499999999 * time.Nanosecond
  1076. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  1077. w.Header().Set("X-Retry-In", delay.String())
  1078. s.sendTooManyRequestResponse(w, r, err)
  1079. return
  1080. }
  1081. next.ServeHTTP(w, r)
  1082. })
  1083. }
  1084. func (s *httpdServer) sendTooManyRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
  1085. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1086. r = s.updateContextFromCookie(r)
  1087. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1088. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1089. util.NewI18nError(errors.New(http.StatusText(http.StatusTooManyRequests)), util.I18nError429Message), "")
  1090. return
  1091. }
  1092. s.renderMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1093. util.NewI18nError(errors.New(http.StatusText(http.StatusTooManyRequests)), util.I18nError429Message), "")
  1094. return
  1095. }
  1096. sendAPIResponse(w, r, err, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
  1097. }
  1098. func (s *httpdServer) sendForbiddenResponse(w http.ResponseWriter, r *http.Request, err error) {
  1099. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1100. r = s.updateContextFromCookie(r)
  1101. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1102. s.renderClientForbiddenPage(w, r, err)
  1103. return
  1104. }
  1105. s.renderForbiddenPage(w, r, err)
  1106. return
  1107. }
  1108. sendAPIResponse(w, r, err, "", http.StatusForbidden)
  1109. }
  1110. func (s *httpdServer) badHostHandler(w http.ResponseWriter, r *http.Request) {
  1111. host := r.Host
  1112. for _, header := range s.binding.Security.HostsProxyHeaders {
  1113. if h := r.Header.Get(header); h != "" {
  1114. host = h
  1115. break
  1116. }
  1117. }
  1118. s.sendForbiddenResponse(w, r, util.NewI18nError(
  1119. util.NewGenericError(fmt.Sprintf("The host %q is not allowed", host)),
  1120. util.I18nErrorConnectionForbidden,
  1121. ))
  1122. }
  1123. func (s *httpdServer) notFoundHandler(w http.ResponseWriter, r *http.Request) {
  1124. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1125. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1126. r = s.updateContextFromCookie(r)
  1127. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1128. s.renderClientNotFoundPage(w, r, nil)
  1129. return
  1130. }
  1131. s.renderNotFoundPage(w, r, nil)
  1132. return
  1133. }
  1134. sendAPIResponse(w, r, nil, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  1135. }
  1136. func (s *httpdServer) redirectToWebPath(w http.ResponseWriter, r *http.Request, webPath string) {
  1137. if dataprovider.HasAdmin() {
  1138. http.Redirect(w, r, webPath, http.StatusFound)
  1139. return
  1140. }
  1141. if s.enableWebAdmin {
  1142. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  1143. }
  1144. }
  1145. // The StripSlashes causes infinite redirects at the root path if used with http.FileServer.
  1146. // We also don't strip paths with more than one trailing slash, see #1434
  1147. func (s *httpdServer) mustStripSlash(r *http.Request) bool {
  1148. urlPath := getURLPath(r)
  1149. return !strings.HasSuffix(urlPath, "//") && !strings.HasPrefix(urlPath, webOpenAPIPath) &&
  1150. !strings.HasPrefix(urlPath, webStaticFilesPath) && !strings.HasPrefix(urlPath, acmeChallengeURI)
  1151. }
  1152. func (s *httpdServer) mustCheckPath(r *http.Request) bool {
  1153. urlPath := getURLPath(r)
  1154. return !strings.HasPrefix(urlPath, webStaticFilesPath) && !strings.HasPrefix(urlPath, acmeChallengeURI)
  1155. }
  1156. func (s *httpdServer) initializeRouter() {
  1157. var hasHTTPSRedirect bool
  1158. s.tokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(s.signingPassphrase), nil)
  1159. s.router = chi.NewRouter()
  1160. s.router.Use(middleware.RequestID)
  1161. s.router.Use(s.parseHeaders)
  1162. s.router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  1163. s.router.Use(middleware.Recoverer)
  1164. if s.binding.Security.Enabled {
  1165. secureMiddleware := secure.New(secure.Options{
  1166. AllowedHosts: s.binding.Security.AllowedHosts,
  1167. AllowedHostsAreRegex: s.binding.Security.AllowedHostsAreRegex,
  1168. HostsProxyHeaders: s.binding.Security.HostsProxyHeaders,
  1169. SSLProxyHeaders: s.binding.Security.getHTTPSProxyHeaders(),
  1170. STSSeconds: s.binding.Security.STSSeconds,
  1171. STSIncludeSubdomains: s.binding.Security.STSIncludeSubdomains,
  1172. STSPreload: s.binding.Security.STSPreload,
  1173. ContentTypeNosniff: s.binding.Security.ContentTypeNosniff,
  1174. ContentSecurityPolicy: s.binding.Security.ContentSecurityPolicy,
  1175. PermissionsPolicy: s.binding.Security.PermissionsPolicy,
  1176. CrossOriginOpenerPolicy: s.binding.Security.CrossOriginOpenerPolicy,
  1177. })
  1178. secureMiddleware.SetBadHostHandler(http.HandlerFunc(s.badHostHandler))
  1179. if s.binding.Security.CacheControl == "private" {
  1180. s.router.Use(cacheControlMiddleware)
  1181. }
  1182. s.router.Use(secureMiddleware.Handler)
  1183. if s.binding.Security.HTTPSRedirect {
  1184. s.router.Use(s.binding.Security.redirectHandler)
  1185. hasHTTPSRedirect = true
  1186. }
  1187. }
  1188. if s.cors.Enabled {
  1189. c := cors.New(cors.Options{
  1190. AllowedOrigins: util.RemoveDuplicates(s.cors.AllowedOrigins, true),
  1191. AllowedMethods: util.RemoveDuplicates(s.cors.AllowedMethods, true),
  1192. AllowedHeaders: util.RemoveDuplicates(s.cors.AllowedHeaders, true),
  1193. ExposedHeaders: util.RemoveDuplicates(s.cors.ExposedHeaders, true),
  1194. MaxAge: s.cors.MaxAge,
  1195. AllowCredentials: s.cors.AllowCredentials,
  1196. OptionsPassthrough: s.cors.OptionsPassthrough,
  1197. OptionsSuccessStatus: s.cors.OptionsSuccessStatus,
  1198. AllowPrivateNetwork: s.cors.AllowPrivateNetwork,
  1199. })
  1200. s.router.Use(c.Handler)
  1201. }
  1202. s.router.Use(middleware.Maybe(s.checkConnection, s.mustCheckPath))
  1203. s.router.Use(middleware.GetHead)
  1204. s.router.Use(middleware.Maybe(middleware.StripSlashes, s.mustStripSlash))
  1205. s.router.NotFound(s.notFoundHandler)
  1206. s.router.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  1207. render.PlainText(w, r, "ok")
  1208. })
  1209. if hasHTTPSRedirect {
  1210. if p := acme.GetHTTP01WebRoot(); p != "" {
  1211. serveStaticDir(s.router, acmeChallengeURI, p, true)
  1212. }
  1213. }
  1214. if s.enableRESTAPI {
  1215. // share API available to external users
  1216. s.router.Get(sharesPath+"/{id}", s.downloadFromShare) //nolint:goconst
  1217. s.router.Post(sharesPath+"/{id}", s.uploadFilesToShare)
  1218. s.router.Post(sharesPath+"/{id}/{name}", s.uploadFileToShare)
  1219. s.router.With(compressor.Handler).Get(sharesPath+"/{id}/dirs", s.readBrowsableShareContents)
  1220. s.router.Get(sharesPath+"/{id}/files", s.downloadBrowsableSharedFile)
  1221. s.router.Get(tokenPath, s.getToken)
  1222. s.router.Post(adminPath+"/{username}/forgot-password", forgotAdminPassword)
  1223. s.router.Post(adminPath+"/{username}/reset-password", resetAdminPassword)
  1224. s.router.Post(userPath+"/{username}/forgot-password", forgotUserPassword)
  1225. s.router.Post(userPath+"/{username}/reset-password", resetUserPassword)
  1226. s.router.Group(func(router chi.Router) {
  1227. router.Use(checkNodeToken(s.tokenAuth))
  1228. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeAdmin))
  1229. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1230. router.Use(jwtAuthenticatorAPI)
  1231. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  1232. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1233. render.JSON(w, r, version.Get())
  1234. })
  1235. router.With(forbidAPIKeyAuthentication).Get(logoutPath, s.logout)
  1236. router.With(forbidAPIKeyAuthentication).Get(adminProfilePath, getAdminProfile)
  1237. router.With(forbidAPIKeyAuthentication, s.checkAuthRequirements).Put(adminProfilePath, updateAdminProfile)
  1238. router.With(forbidAPIKeyAuthentication).Put(adminPwdPath, changeAdminPassword)
  1239. // admin TOTP APIs
  1240. router.With(forbidAPIKeyAuthentication).Get(adminTOTPConfigsPath, getTOTPConfigs)
  1241. router.With(forbidAPIKeyAuthentication).Post(adminTOTPGeneratePath, generateTOTPSecret)
  1242. router.With(forbidAPIKeyAuthentication).Post(adminTOTPValidatePath, validateTOTPPasscode)
  1243. router.With(forbidAPIKeyAuthentication).Post(adminTOTPSavePath, saveTOTPConfig)
  1244. router.With(forbidAPIKeyAuthentication).Get(admin2FARecoveryCodesPath, getRecoveryCodes)
  1245. router.With(forbidAPIKeyAuthentication).Post(admin2FARecoveryCodesPath, generateRecoveryCodes)
  1246. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1247. Get(apiKeysPath, getAPIKeys)
  1248. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1249. Post(apiKeysPath, addAPIKey)
  1250. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1251. Get(apiKeysPath+"/{id}", getAPIKeyByID)
  1252. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1253. Put(apiKeysPath+"/{id}", updateAPIKey)
  1254. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminAny)).
  1255. Delete(apiKeysPath+"/{id}", deleteAPIKey)
  1256. router.Group(func(router chi.Router) {
  1257. router.Use(s.checkAuthRequirements)
  1258. router.With(s.checkPerm(dataprovider.PermAdminViewServerStatus)).
  1259. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  1260. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1261. render.JSON(w, r, getServicesStatus())
  1262. })
  1263. router.With(s.checkPerm(dataprovider.PermAdminViewConnections)).Get(activeConnectionsPath, getActiveConnections)
  1264. router.With(s.checkPerm(dataprovider.PermAdminCloseConnections)).
  1265. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  1266. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/users/scans", getUsersQuotaScans)
  1267. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/users/{username}/scan", startUserQuotaScan)
  1268. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/folders/scans", getFoldersQuotaScans)
  1269. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/folders/{name}/scan", startFolderQuotaScan)
  1270. router.With(s.checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  1271. router.With(s.checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  1272. router.With(s.checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername) //nolint:goconst
  1273. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  1274. router.With(s.checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  1275. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA)).Put(userPath+"/{username}/2fa/disable", disableUser2FA) //nolint:goconst
  1276. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Get(folderPath, getFolders)
  1277. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Get(folderPath+"/{name}", getFolderByName) //nolint:goconst
  1278. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(folderPath, addFolder)
  1279. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Put(folderPath+"/{name}", updateFolder)
  1280. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Delete(folderPath+"/{name}", deleteFolder)
  1281. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Get(groupPath, getGroups)
  1282. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Get(groupPath+"/{name}", getGroupByName)
  1283. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(groupPath, addGroup)
  1284. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Put(groupPath+"/{name}", updateGroup)
  1285. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Delete(groupPath+"/{name}", deleteGroup)
  1286. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(dumpDataPath, dumpData)
  1287. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(loadDataPath, loadData)
  1288. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(loadDataPath, loadDataFromRequest)
  1289. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/usage",
  1290. updateUserQuotaUsage)
  1291. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/transfer-usage",
  1292. updateUserTransferQuotaUsage)
  1293. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage",
  1294. updateFolderQuotaUsage)
  1295. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
  1296. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
  1297. router.With(s.checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
  1298. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(adminPath, getAdmins)
  1299. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(adminPath, addAdmin)
  1300. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(adminPath+"/{username}", getAdminByUsername)
  1301. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(adminPath+"/{username}", updateAdmin)
  1302. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(adminPath+"/{username}", deleteAdmin)
  1303. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1304. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(retentionChecksPath, getRetentionChecks)
  1305. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(retentionBasePath+"/{username}/check",
  1306. startRetentionCheck)
  1307. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1308. Get(fsEventsPath, searchFsEvents)
  1309. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1310. Get(providerEventsPath, searchProviderEvents)
  1311. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1312. Get(logEventsPath, searchLogEvents)
  1313. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventActionsPath, getEventActions)
  1314. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventActionsPath+"/{name}", getEventActionByName)
  1315. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(eventActionsPath, addEventAction)
  1316. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(eventActionsPath+"/{name}", updateEventAction)
  1317. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(eventActionsPath+"/{name}", deleteEventAction)
  1318. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventRulesPath, getEventRules)
  1319. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(eventRulesPath+"/{name}", getEventRuleByName)
  1320. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(eventRulesPath, addEventRule)
  1321. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(eventRulesPath+"/{name}", updateEventRule)
  1322. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(eventRulesPath+"/{name}", deleteEventRule)
  1323. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(eventRulesPath+"/run/{name}", runOnDemandRule)
  1324. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(rolesPath, getRoles)
  1325. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(rolesPath, addRole)
  1326. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(rolesPath+"/{name}", getRoleByName)
  1327. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(rolesPath+"/{name}", updateRole)
  1328. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(rolesPath+"/{name}", deleteRole)
  1329. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler).Get(ipListsPath+"/{type}", getIPListEntries) //nolint:goconst
  1330. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(ipListsPath+"/{type}", addIPListEntry)
  1331. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(ipListsPath+"/{type}/{ipornet}", getIPListEntry) //nolint:goconst
  1332. router.With(s.checkPerm(dataprovider.PermAdminAny)).Put(ipListsPath+"/{type}/{ipornet}", updateIPListEntry)
  1333. router.With(s.checkPerm(dataprovider.PermAdminAny)).Delete(ipListsPath+"/{type}/{ipornet}", deleteIPListEntry)
  1334. })
  1335. })
  1336. s.router.Get(userTokenPath, s.getUserToken)
  1337. s.router.Group(func(router chi.Router) {
  1338. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
  1339. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1340. router.Use(jwtAuthenticatorAPIUser)
  1341. router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
  1342. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1343. Put(userPwdPath, changeUserPassword)
  1344. router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
  1345. router.With(forbidAPIKeyAuthentication, s.checkAuthRequirements).Put(userProfilePath, updateUserProfile)
  1346. // user TOTP APIs
  1347. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1348. Get(userTOTPConfigsPath, getTOTPConfigs)
  1349. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1350. Post(userTOTPGeneratePath, generateTOTPSecret)
  1351. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1352. Post(userTOTPValidatePath, validateTOTPPasscode)
  1353. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1354. Post(userTOTPSavePath, saveTOTPConfig)
  1355. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1356. Get(user2FARecoveryCodesPath, getRecoveryCodes)
  1357. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1358. Post(user2FARecoveryCodesPath, generateRecoveryCodes)
  1359. router.With(s.checkAuthRequirements, compressor.Handler).Get(userDirsPath, readUserFolder)
  1360. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1361. Post(userDirsPath, createUserDir)
  1362. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1363. Patch(userDirsPath, renameUserFsEntry)
  1364. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1365. Delete(userDirsPath, deleteUserDir)
  1366. router.With(s.checkAuthRequirements).Get(userFilesPath, getUserFile)
  1367. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1368. Post(userFilesPath, uploadUserFiles)
  1369. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1370. Patch(userFilesPath, renameUserFsEntry)
  1371. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1372. Delete(userFilesPath, deleteUserFile)
  1373. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1374. Post(userFileActionsPath+"/move", renameUserFsEntry)
  1375. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1376. Post(userFileActionsPath+"/copy", copyUserFsEntry)
  1377. router.With(s.checkAuthRequirements).Post(userStreamZipPath, getUserFilesAsZipStream)
  1378. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1379. Get(userSharesPath, getShares)
  1380. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1381. Post(userSharesPath, addShare)
  1382. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1383. Get(userSharesPath+"/{id}", getShareByID)
  1384. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1385. Put(userSharesPath+"/{id}", updateShare)
  1386. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1387. Delete(userSharesPath+"/{id}", deleteShare)
  1388. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1389. Post(userUploadFilePath, uploadUserFile)
  1390. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1391. Patch(userFilesDirsMetadataPath, setFileDirMetadata)
  1392. })
  1393. if s.renderOpenAPI {
  1394. s.router.Group(func(router chi.Router) {
  1395. router.Use(cleanCacheControlMiddleware)
  1396. router.Use(compressor.Handler)
  1397. serveStaticDir(router, webOpenAPIPath, s.openAPIPath, false)
  1398. })
  1399. }
  1400. }
  1401. if s.enableWebAdmin || s.enableWebClient {
  1402. s.router.Group(func(router chi.Router) {
  1403. router.Use(cleanCacheControlMiddleware)
  1404. router.Use(compressor.Handler)
  1405. serveStaticDir(router, webStaticFilesPath, s.staticFilesPath, true)
  1406. })
  1407. if s.binding.OIDC.isEnabled() {
  1408. s.router.Get(webOIDCRedirectPath, s.handleOIDCRedirect)
  1409. }
  1410. if s.enableWebClient {
  1411. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1412. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1413. s.redirectToWebPath(w, r, webClientLoginPath)
  1414. })
  1415. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1416. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1417. s.redirectToWebPath(w, r, webClientLoginPath)
  1418. })
  1419. } else {
  1420. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1421. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1422. s.redirectToWebPath(w, r, webAdminLoginPath)
  1423. })
  1424. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1425. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1426. s.redirectToWebPath(w, r, webAdminLoginPath)
  1427. })
  1428. }
  1429. }
  1430. s.setupWebClientRoutes()
  1431. s.setupWebAdminRoutes()
  1432. }
  1433. func (s *httpdServer) setupWebClientRoutes() {
  1434. if s.enableWebClient {
  1435. s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
  1436. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1437. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  1438. })
  1439. s.router.Get(webClientLoginPath, s.handleClientWebLogin)
  1440. if s.binding.OIDC.isEnabled() && !s.binding.isWebClientOIDCLoginDisabled() {
  1441. s.router.Get(webClientOIDCLoginPath, s.handleWebClientOIDCLogin)
  1442. }
  1443. if !s.binding.isWebClientLoginFormDisabled() {
  1444. s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
  1445. s.router.Get(webClientForgotPwdPath, s.handleWebClientForgotPwd)
  1446. s.router.Post(webClientForgotPwdPath, s.handleWebClientForgotPwdPost)
  1447. s.router.Get(webClientResetPwdPath, s.handleWebClientPasswordReset)
  1448. s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
  1449. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1450. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1451. Get(webClientTwoFactorPath, s.handleWebClientTwoFactor)
  1452. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1453. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1454. Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
  1455. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1456. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1457. Get(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecovery)
  1458. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1459. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1460. Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
  1461. }
  1462. // share routes available to external users
  1463. s.router.Get(webClientPubSharesPath+"/{id}/login", s.handleClientShareLoginGet)
  1464. s.router.Post(webClientPubSharesPath+"/{id}/login", s.handleClientShareLoginPost)
  1465. s.router.Get(webClientPubSharesPath+"/{id}", s.downloadFromShare)
  1466. s.router.Post(webClientPubSharesPath+"/{id}/partial", s.handleClientSharePartialDownload)
  1467. s.router.Get(webClientPubSharesPath+"/{id}/browse", s.handleShareGetFiles)
  1468. s.router.Post(webClientPubSharesPath+"/{id}/browse/exist", s.handleClientShareCheckExist)
  1469. s.router.Get(webClientPubSharesPath+"/{id}/download", s.handleClientSharedFile)
  1470. s.router.Get(webClientPubSharesPath+"/{id}/upload", s.handleClientUploadToShare)
  1471. s.router.With(compressor.Handler).Get(webClientPubSharesPath+"/{id}/dirs", s.handleShareGetDirContents)
  1472. s.router.Post(webClientPubSharesPath+"/{id}", s.uploadFilesToShare)
  1473. s.router.Post(webClientPubSharesPath+"/{id}/{name}", s.uploadFileToShare)
  1474. s.router.Get(webClientPubSharesPath+"/{id}/viewpdf", s.handleShareViewPDF)
  1475. s.router.Get(webClientPubSharesPath+"/{id}/getpdf", s.handleShareGetPDF)
  1476. s.router.Group(func(router chi.Router) {
  1477. if s.binding.OIDC.isEnabled() {
  1478. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebClient))
  1479. }
  1480. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1481. router.Use(jwtAuthenticatorWebClient)
  1482. router.Get(webClientLogoutPath, s.handleWebClientLogout)
  1483. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
  1484. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientViewPDFPath, s.handleClientViewPDF)
  1485. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientGetPDFPath, s.handleClientGetPDF)
  1486. router.With(s.checkAuthRequirements, s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
  1487. router.With(s.checkAuthRequirements, s.refreshCookie, verifyCSRFHeader).Get(webClientTasksPath+"/{id}",
  1488. getWebTask)
  1489. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1490. Post(webClientFilePath, uploadUserFile)
  1491. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1492. Post(webClientExistPath, s.handleClientCheckExist)
  1493. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientEditFilePath, s.handleClientEditFile)
  1494. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1495. Delete(webClientFilesPath, deleteUserFile)
  1496. router.With(s.checkAuthRequirements, compressor.Handler, s.refreshCookie).
  1497. Get(webClientDirsPath, s.handleClientGetDirContents)
  1498. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1499. Post(webClientDirsPath, createUserDir)
  1500. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1501. Delete(webClientDirsPath, taskDeleteDir)
  1502. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1503. Post(webClientFileActionsPath+"/move", taskRenameFsEntry)
  1504. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1505. Post(webClientFileActionsPath+"/copy", taskCopyFsEntry)
  1506. router.With(s.checkAuthRequirements, s.refreshCookie).
  1507. Post(webClientDownloadZipPath, s.handleWebClientDownloadZip)
  1508. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientPingPath, handlePingRequest)
  1509. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientProfilePath,
  1510. s.handleClientGetProfile)
  1511. router.With(s.checkAuthRequirements).Post(webClientProfilePath, s.handleWebClientProfilePost)
  1512. router.With(s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1513. Get(webChangeClientPwdPath, s.handleWebClientChangePwd)
  1514. router.With(s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1515. Post(webChangeClientPwdPath, s.handleWebClientChangePwdPost)
  1516. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1517. Get(webClientMFAPath, s.handleWebClientMFA)
  1518. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1519. Get(webClientMFAPath+"/qrcode", getQRCode)
  1520. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1521. Post(webClientTOTPGeneratePath, generateTOTPSecret)
  1522. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1523. Post(webClientTOTPValidatePath, validateTOTPPasscode)
  1524. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1525. Post(webClientTOTPSavePath, saveTOTPConfig)
  1526. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
  1527. Get(webClientRecoveryCodesPath, getRecoveryCodes)
  1528. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1529. Post(webClientRecoveryCodesPath, generateRecoveryCodes)
  1530. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), compressor.Handler, s.refreshCookie).
  1531. Get(webClientSharesPath+jsonAPISuffix, getAllShares)
  1532. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1533. Get(webClientSharesPath, s.handleClientGetShares)
  1534. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1535. Get(webClientSharePath, s.handleClientAddShareGet)
  1536. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1537. Post(webClientSharePath, s.handleClientAddSharePost)
  1538. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1539. Get(webClientSharePath+"/{id}", s.handleClientUpdateShareGet)
  1540. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1541. Post(webClientSharePath+"/{id}", s.handleClientUpdateSharePost)
  1542. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
  1543. Delete(webClientSharePath+"/{id}", deleteShare)
  1544. })
  1545. }
  1546. }
  1547. func (s *httpdServer) setupWebAdminRoutes() {
  1548. if s.enableWebAdmin {
  1549. s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
  1550. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1551. s.redirectToWebPath(w, r, webAdminLoginPath)
  1552. })
  1553. s.router.Get(webAdminLoginPath, s.handleWebAdminLogin)
  1554. if s.binding.OIDC.hasRoles() && !s.binding.isWebAdminOIDCLoginDisabled() {
  1555. s.router.Get(webAdminOIDCLoginPath, s.handleWebAdminOIDCLogin)
  1556. }
  1557. s.router.Get(webOAuth2RedirectPath, s.handleOAuth2TokenRedirect)
  1558. s.router.Get(webAdminSetupPath, s.handleWebAdminSetupGet)
  1559. s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
  1560. if !s.binding.isWebAdminLoginFormDisabled() {
  1561. s.router.Post(webAdminLoginPath, s.handleWebAdminLoginPost)
  1562. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1563. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1564. Get(webAdminTwoFactorPath, s.handleWebAdminTwoFactor)
  1565. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1566. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1567. Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
  1568. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1569. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1570. Get(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecovery)
  1571. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1572. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1573. Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
  1574. s.router.Get(webAdminForgotPwdPath, s.handleWebAdminForgotPwd)
  1575. s.router.Post(webAdminForgotPwdPath, s.handleWebAdminForgotPwdPost)
  1576. s.router.Get(webAdminResetPwdPath, s.handleWebAdminPasswordReset)
  1577. s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
  1578. }
  1579. s.router.Group(func(router chi.Router) {
  1580. if s.binding.OIDC.isEnabled() {
  1581. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebAdmin))
  1582. }
  1583. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1584. router.Use(jwtAuthenticatorWebAdmin)
  1585. router.Get(webLogoutPath, s.handleWebAdminLogout)
  1586. router.With(s.refreshCookie, s.checkAuthRequirements, s.requireBuiltinLogin).Get(
  1587. webAdminProfilePath, s.handleWebAdminProfile)
  1588. router.With(s.checkAuthRequirements, s.requireBuiltinLogin).Post(webAdminProfilePath, s.handleWebAdminProfilePost)
  1589. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webChangeAdminPwdPath, s.handleWebAdminChangePwd)
  1590. router.With(s.requireBuiltinLogin).Post(webChangeAdminPwdPath, s.handleWebAdminChangePwdPost)
  1591. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminMFAPath, s.handleWebAdminMFA)
  1592. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminMFAPath+"/qrcode", getQRCode)
  1593. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
  1594. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
  1595. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPSavePath, saveTOTPConfig)
  1596. router.With(verifyCSRFHeader, s.requireBuiltinLogin, s.refreshCookie).Get(webAdminRecoveryCodesPath,
  1597. getRecoveryCodes)
  1598. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
  1599. router.Group(func(router chi.Router) {
  1600. router.Use(s.checkAuthRequirements)
  1601. router.With(s.checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1602. Get(webUsersPath, s.handleGetWebUsers)
  1603. router.With(s.checkPerm(dataprovider.PermAdminViewUsers), compressor.Handler, s.refreshCookie).
  1604. Get(webUsersPath+jsonAPISuffix, getAllUsers)
  1605. router.With(s.checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1606. Get(webUserPath, s.handleWebAddUserGet)
  1607. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1608. Get(webUserPath+"/{username}", s.handleWebUpdateUserGet)
  1609. router.With(s.checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, s.handleWebAddUserPost)
  1610. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}",
  1611. s.handleWebUpdateUserPost)
  1612. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1613. Get(webGroupsPath, s.handleWebGetGroups)
  1614. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), compressor.Handler, s.refreshCookie).
  1615. Get(webGroupsPath+jsonAPISuffix, getAllGroups)
  1616. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1617. Get(webGroupPath, s.handleWebAddGroupGet)
  1618. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(webGroupPath, s.handleWebAddGroupPost)
  1619. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1620. Get(webGroupPath+"/{name}", s.handleWebUpdateGroupGet)
  1621. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(webGroupPath+"/{name}",
  1622. s.handleWebUpdateGroupPost)
  1623. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), verifyCSRFHeader).
  1624. Delete(webGroupPath+"/{name}", deleteGroup)
  1625. router.With(s.checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1626. Get(webConnectionsPath, s.handleWebGetConnections)
  1627. router.With(s.checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1628. Get(webConnectionsPath+jsonAPISuffix, getActiveConnections)
  1629. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1630. Get(webFoldersPath, s.handleWebGetFolders)
  1631. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), compressor.Handler, s.refreshCookie).
  1632. Get(webFoldersPath+jsonAPISuffix, getAllFolders)
  1633. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1634. Get(webFolderPath, s.handleWebAddFolderGet)
  1635. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(webFolderPath, s.handleWebAddFolderPost)
  1636. router.With(s.checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  1637. Get(webStatusPath, s.handleWebGetStatus)
  1638. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1639. Get(webAdminsPath, s.handleGetWebAdmins)
  1640. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1641. Get(webAdminsPath+jsonAPISuffix, getAllAdmins)
  1642. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1643. Get(webAdminPath, s.handleWebAddAdminGet)
  1644. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1645. Get(webAdminPath+"/{username}", s.handleWebUpdateAdminGet)
  1646. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminPath, s.handleWebAddAdminPost)
  1647. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminPath+"/{username}",
  1648. s.handleWebUpdateAdminPost)
  1649. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1650. Delete(webAdminPath+"/{username}", deleteAdmin)
  1651. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA), verifyCSRFHeader).
  1652. Put(webAdminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1653. router.With(s.checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  1654. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  1655. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1656. Get(webFolderPath+"/{name}", s.handleWebUpdateFolderGet)
  1657. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(webFolderPath+"/{name}",
  1658. s.handleWebUpdateFolderPost)
  1659. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), verifyCSRFHeader).
  1660. Delete(webFolderPath+"/{name}", deleteFolder)
  1661. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1662. Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
  1663. router.With(s.checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1664. Delete(webUserPath+"/{username}", deleteUser)
  1665. router.With(s.checkPerm(dataprovider.PermAdminDisableMFA), verifyCSRFHeader).
  1666. Put(webUserPath+"/{username}/2fa/disable", disableUser2FA)
  1667. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1668. Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
  1669. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(webMaintenancePath, s.handleWebMaintenance)
  1670. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(webBackupPath, dumpData)
  1671. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webRestorePath, s.handleWebRestore)
  1672. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1673. Get(webTemplateUser, s.handleWebTemplateUserGet)
  1674. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webTemplateUser, s.handleWebTemplateUserPost)
  1675. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1676. Get(webTemplateFolder, s.handleWebTemplateFolderGet)
  1677. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webTemplateFolder, s.handleWebTemplateFolderPost)
  1678. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, s.handleWebDefenderPage)
  1679. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
  1680. router.With(s.checkPerm(dataprovider.PermAdminManageDefender), verifyCSRFHeader).
  1681. Delete(webDefenderHostsPath+"/{id}", deleteDefenderHostByID)
  1682. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1683. Get(webAdminEventActionsPath+jsonAPISuffix, getAllActions)
  1684. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1685. Get(webAdminEventActionsPath, s.handleWebGetEventActions)
  1686. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1687. Get(webAdminEventActionPath, s.handleWebAddEventActionGet)
  1688. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventActionPath,
  1689. s.handleWebAddEventActionPost)
  1690. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1691. Get(webAdminEventActionPath+"/{name}", s.handleWebUpdateEventActionGet)
  1692. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventActionPath+"/{name}",
  1693. s.handleWebUpdateEventActionPost)
  1694. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1695. Delete(webAdminEventActionPath+"/{name}", deleteEventAction)
  1696. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1697. Get(webAdminEventRulesPath+jsonAPISuffix, getAllRules)
  1698. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1699. Get(webAdminEventRulesPath, s.handleWebGetEventRules)
  1700. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1701. Get(webAdminEventRulePath, s.handleWebAddEventRuleGet)
  1702. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventRulePath,
  1703. s.handleWebAddEventRulePost)
  1704. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1705. Get(webAdminEventRulePath+"/{name}", s.handleWebUpdateEventRuleGet)
  1706. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminEventRulePath+"/{name}",
  1707. s.handleWebUpdateEventRulePost)
  1708. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1709. Delete(webAdminEventRulePath+"/{name}", deleteEventRule)
  1710. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1711. Post(webAdminEventRulePath+"/run/{name}", runOnDemandRule)
  1712. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1713. Get(webAdminRolesPath, s.handleWebGetRoles)
  1714. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1715. Get(webAdminRolesPath+jsonAPISuffix, getAllRoles)
  1716. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1717. Get(webAdminRolePath, s.handleWebAddRoleGet)
  1718. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminRolePath, s.handleWebAddRolePost)
  1719. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).
  1720. Get(webAdminRolePath+"/{name}", s.handleWebUpdateRoleGet)
  1721. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webAdminRolePath+"/{name}",
  1722. s.handleWebUpdateRolePost)
  1723. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1724. Delete(webAdminRolePath+"/{name}", deleteRole)
  1725. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), s.refreshCookie).Get(webEventsPath,
  1726. s.handleWebGetEvents)
  1727. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1728. Get(webEventsFsSearchPath, searchFsEvents)
  1729. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1730. Get(webEventsProviderSearchPath, searchProviderEvents)
  1731. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1732. Get(webEventsLogSearchPath, searchLogEvents)
  1733. router.With(s.checkPerm(dataprovider.PermAdminAny)).Get(webIPListsPath, s.handleWebIPListsPage)
  1734. router.With(s.checkPerm(dataprovider.PermAdminAny), compressor.Handler, s.refreshCookie).
  1735. Get(webIPListsPath+"/{type}", getIPListEntries)
  1736. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).Get(webIPListPath+"/{type}",
  1737. s.handleWebAddIPListEntryGet)
  1738. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webIPListPath+"/{type}",
  1739. s.handleWebAddIPListEntryPost)
  1740. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).Get(webIPListPath+"/{type}/{ipornet}",
  1741. s.handleWebUpdateIPListEntryGet)
  1742. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webIPListPath+"/{type}/{ipornet}",
  1743. s.handleWebUpdateIPListEntryPost)
  1744. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader).
  1745. Delete(webIPListPath+"/{type}/{ipornet}", deleteIPListEntry)
  1746. router.With(s.checkPerm(dataprovider.PermAdminAny), s.refreshCookie).Get(webConfigsPath, s.handleWebConfigs)
  1747. router.With(s.checkPerm(dataprovider.PermAdminAny)).Post(webConfigsPath, s.handleWebConfigsPost)
  1748. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader, s.refreshCookie).
  1749. Post(webConfigsPath+"/smtp/test", testSMTPConfig)
  1750. router.With(s.checkPerm(dataprovider.PermAdminAny), verifyCSRFHeader, s.refreshCookie).
  1751. Post(webOAuth2TokenPath, handleSMTPOAuth2TokenRequestPost)
  1752. })
  1753. })
  1754. }
  1755. }