server.go 87 KB

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