server.go 88 KB

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