server.go 88 KB

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