server.go 88 KB

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