server.go 84 KB

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