server.go 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. package httpd
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "strings"
  12. "time"
  13. "github.com/go-chi/chi/v5"
  14. "github.com/go-chi/chi/v5/middleware"
  15. "github.com/go-chi/jwtauth/v5"
  16. "github.com/go-chi/render"
  17. "github.com/lestrrat-go/jwx/jwa"
  18. "github.com/rs/cors"
  19. "github.com/rs/xid"
  20. "github.com/drakkan/sftpgo/v2/common"
  21. "github.com/drakkan/sftpgo/v2/dataprovider"
  22. "github.com/drakkan/sftpgo/v2/logger"
  23. "github.com/drakkan/sftpgo/v2/mfa"
  24. "github.com/drakkan/sftpgo/v2/sdk"
  25. "github.com/drakkan/sftpgo/v2/smtp"
  26. "github.com/drakkan/sftpgo/v2/util"
  27. "github.com/drakkan/sftpgo/v2/version"
  28. )
  29. var (
  30. compressor = middleware.NewCompressor(5)
  31. xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto")
  32. )
  33. type httpdServer struct {
  34. binding Binding
  35. staticFilesPath string
  36. openAPIPath string
  37. enableWebAdmin bool
  38. enableWebClient bool
  39. renderOpenAPI bool
  40. router *chi.Mux
  41. tokenAuth *jwtauth.JWTAuth
  42. signingPassphrase string
  43. cors CorsConfig
  44. }
  45. func newHttpdServer(b Binding, staticFilesPath, signingPassphrase string, cors CorsConfig,
  46. openAPIPath string,
  47. ) *httpdServer {
  48. if openAPIPath == "" {
  49. b.RenderOpenAPI = false
  50. }
  51. return &httpdServer{
  52. binding: b,
  53. staticFilesPath: staticFilesPath,
  54. openAPIPath: openAPIPath,
  55. enableWebAdmin: b.EnableWebAdmin,
  56. enableWebClient: b.EnableWebClient,
  57. renderOpenAPI: b.RenderOpenAPI,
  58. signingPassphrase: signingPassphrase,
  59. cors: cors,
  60. }
  61. }
  62. func (s *httpdServer) listenAndServe() error {
  63. s.initializeRouter()
  64. httpServer := &http.Server{
  65. Handler: s.router,
  66. ReadHeaderTimeout: 30 * time.Second,
  67. ReadTimeout: 60 * time.Second,
  68. WriteTimeout: 60 * time.Second,
  69. IdleTimeout: 60 * time.Second,
  70. MaxHeaderBytes: 1 << 16, // 64KB
  71. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  72. }
  73. if certMgr != nil && s.binding.EnableHTTPS {
  74. config := &tls.Config{
  75. GetCertificate: certMgr.GetCertificateFunc(),
  76. MinVersion: tls.VersionTLS12,
  77. NextProtos: []string{"http/1.1", "h2"},
  78. CipherSuites: util.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
  79. PreferServerCipherSuites: true,
  80. }
  81. logger.Debug(logSender, "", "configured TLS cipher suites for binding %#v: %v", s.binding.GetAddress(),
  82. config.CipherSuites)
  83. httpServer.TLSConfig = config
  84. if s.binding.ClientAuthType == 1 {
  85. httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
  86. httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
  87. httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
  88. }
  89. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, true, logSender)
  90. }
  91. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, false, logSender)
  92. }
  93. func (s *httpdServer) verifyTLSConnection(state tls.ConnectionState) error {
  94. if certMgr != nil {
  95. var clientCrt *x509.Certificate
  96. var clientCrtName string
  97. if len(state.PeerCertificates) > 0 {
  98. clientCrt = state.PeerCertificates[0]
  99. clientCrtName = clientCrt.Subject.String()
  100. }
  101. if len(state.VerifiedChains) == 0 {
  102. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  103. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  104. }
  105. for _, verifiedChain := range state.VerifiedChains {
  106. var caCrt *x509.Certificate
  107. if len(verifiedChain) > 0 {
  108. caCrt = verifiedChain[len(verifiedChain)-1]
  109. }
  110. if certMgr.IsRevoked(clientCrt, caCrt) {
  111. logger.Debug(logSender, "", "tls handshake error, client certificate %#v has been revoked", clientCrtName)
  112. return common.ErrCrtRevoked
  113. }
  114. }
  115. }
  116. return nil
  117. }
  118. func (s *httpdServer) refreshCookie(next http.Handler) http.Handler {
  119. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  120. s.checkCookieExpiration(w, r)
  121. next.ServeHTTP(w, r)
  122. })
  123. }
  124. func (s *httpdServer) renderClientLoginPage(w http.ResponseWriter, error string) {
  125. data := loginPage{
  126. CurrentURL: webClientLoginPath,
  127. Version: version.Get().Version,
  128. Error: error,
  129. CSRFToken: createCSRFToken(),
  130. StaticURL: webStaticFilesPath,
  131. }
  132. if s.binding.showAdminLoginURL() {
  133. data.AltLoginURL = webLoginPath
  134. }
  135. if smtp.IsEnabled() {
  136. data.ForgotPwdURL = webClientForgotPwdPath
  137. }
  138. renderClientTemplate(w, templateClientLogin, data)
  139. }
  140. func (s *httpdServer) handleClientWebLogin(w http.ResponseWriter, r *http.Request) {
  141. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  142. if !dataprovider.HasAdmin() {
  143. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  144. return
  145. }
  146. s.renderClientLoginPage(w, "")
  147. }
  148. func (s *httpdServer) handleWebClientLoginPost(w http.ResponseWriter, r *http.Request) {
  149. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  150. if err := r.ParseForm(); err != nil {
  151. s.renderClientLoginPage(w, err.Error())
  152. return
  153. }
  154. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  155. username := r.Form.Get("username")
  156. password := r.Form.Get("password")
  157. if username == "" || password == "" {
  158. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}}, ipAddr, common.ErrNoCredentials)
  159. s.renderClientLoginPage(w, "Invalid credentials")
  160. return
  161. }
  162. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  163. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}}, ipAddr, err)
  164. s.renderClientLoginPage(w, err.Error())
  165. return
  166. }
  167. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolHTTP); err != nil {
  168. s.renderClientLoginPage(w, fmt.Sprintf("access denied by post connect hook: %v", err))
  169. return
  170. }
  171. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, common.ProtocolHTTP)
  172. if err != nil {
  173. updateLoginMetrics(&user, ipAddr, err)
  174. s.renderClientLoginPage(w, dataprovider.ErrInvalidCredentials.Error())
  175. return
  176. }
  177. connectionID := fmt.Sprintf("%v_%v", common.ProtocolHTTP, xid.New().String())
  178. if err := checkHTTPClientUser(&user, r, connectionID); err != nil {
  179. updateLoginMetrics(&user, ipAddr, err)
  180. s.renderClientLoginPage(w, err.Error())
  181. return
  182. }
  183. defer user.CloseFs() //nolint:errcheck
  184. err = user.CheckFsRoot(connectionID)
  185. if err != nil {
  186. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  187. updateLoginMetrics(&user, ipAddr, common.ErrInternalFailure)
  188. s.renderClientLoginPage(w, err.Error())
  189. return
  190. }
  191. s.loginUser(w, r, &user, connectionID, ipAddr, false, s.renderClientLoginPage)
  192. }
  193. func (s *httpdServer) handleWebClientPasswordResetPost(w http.ResponseWriter, r *http.Request) {
  194. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  195. err := r.ParseForm()
  196. if err != nil {
  197. renderClientResetPwdPage(w, err.Error())
  198. return
  199. }
  200. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  201. renderClientForbiddenPage(w, r, err.Error())
  202. return
  203. }
  204. _, user, err := handleResetPassword(r, r.Form.Get("code"), r.Form.Get("password"), false)
  205. if err != nil {
  206. if e, ok := err.(*util.ValidationError); ok {
  207. renderClientResetPwdPage(w, e.GetErrorString())
  208. return
  209. }
  210. renderClientResetPwdPage(w, err.Error())
  211. return
  212. }
  213. connectionID := fmt.Sprintf("%v_%v", common.ProtocolHTTP, xid.New().String())
  214. if err := checkHTTPClientUser(user, r, connectionID); err != nil {
  215. renderClientResetPwdPage(w, fmt.Sprintf("Password reset successfully but unable to login: %v", err.Error()))
  216. return
  217. }
  218. defer user.CloseFs() //nolint:errcheck
  219. err = user.CheckFsRoot(connectionID)
  220. if err != nil {
  221. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  222. renderClientResetPwdPage(w, fmt.Sprintf("Password reset successfully but unable to login: %v", err.Error()))
  223. return
  224. }
  225. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  226. s.loginUser(w, r, user, connectionID, ipAddr, false, renderClientResetPwdPage)
  227. }
  228. func (s *httpdServer) handleWebClientTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
  229. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  230. claims, err := getTokenClaims(r)
  231. if err != nil {
  232. renderNotFoundPage(w, r, nil)
  233. return
  234. }
  235. if err := r.ParseForm(); err != nil {
  236. renderClientTwoFactorRecoveryPage(w, err.Error())
  237. return
  238. }
  239. username := claims.Username
  240. recoveryCode := r.Form.Get("recovery_code")
  241. if username == "" || recoveryCode == "" {
  242. renderClientTwoFactorRecoveryPage(w, "Invalid credentials")
  243. return
  244. }
  245. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  246. renderClientTwoFactorRecoveryPage(w, err.Error())
  247. return
  248. }
  249. user, err := dataprovider.UserExists(username)
  250. if err != nil {
  251. renderClientTwoFactorRecoveryPage(w, "Invalid credentials")
  252. return
  253. }
  254. if !user.Filters.TOTPConfig.Enabled || !util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
  255. renderClientTwoFactorPage(w, "Two factory authentication is not enabled")
  256. return
  257. }
  258. for idx, code := range user.Filters.RecoveryCodes {
  259. if err := code.Secret.Decrypt(); err != nil {
  260. renderClientInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
  261. return
  262. }
  263. if code.Secret.GetPayload() == recoveryCode {
  264. if code.Used {
  265. renderClientTwoFactorRecoveryPage(w, "This recovery code was already used")
  266. return
  267. }
  268. user.Filters.RecoveryCodes[idx].Used = true
  269. err = dataprovider.UpdateUser(&user, dataprovider.ActionExecutorSelf, util.GetIPFromRemoteAddress(r.RemoteAddr))
  270. if err != nil {
  271. logger.Warn(logSender, "", "unable to set the recovery code %#v as used: %v", recoveryCode, err)
  272. renderClientInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
  273. return
  274. }
  275. connectionID := fmt.Sprintf("%v_%v", common.ProtocolHTTP, xid.New().String())
  276. s.loginUser(w, r, &user, connectionID, util.GetIPFromRemoteAddress(r.RemoteAddr), true,
  277. renderClientTwoFactorRecoveryPage)
  278. return
  279. }
  280. }
  281. renderClientTwoFactorRecoveryPage(w, "Invalid recovery code")
  282. }
  283. func (s *httpdServer) handleWebClientTwoFactorPost(w http.ResponseWriter, r *http.Request) {
  284. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  285. claims, err := getTokenClaims(r)
  286. if err != nil {
  287. renderNotFoundPage(w, r, nil)
  288. return
  289. }
  290. if err := r.ParseForm(); err != nil {
  291. renderClientTwoFactorPage(w, err.Error())
  292. return
  293. }
  294. username := claims.Username
  295. passcode := r.Form.Get("passcode")
  296. if username == "" || passcode == "" {
  297. renderClientTwoFactorPage(w, "Invalid credentials")
  298. return
  299. }
  300. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  301. renderClientTwoFactorPage(w, err.Error())
  302. return
  303. }
  304. user, err := dataprovider.UserExists(username)
  305. if err != nil {
  306. renderClientTwoFactorPage(w, "Invalid credentials")
  307. return
  308. }
  309. if !user.Filters.TOTPConfig.Enabled || !util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
  310. renderClientTwoFactorPage(w, "Two factory authentication is not enabled")
  311. return
  312. }
  313. err = user.Filters.TOTPConfig.Secret.Decrypt()
  314. if err != nil {
  315. renderClientInternalServerErrorPage(w, r, err)
  316. return
  317. }
  318. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  319. user.Filters.TOTPConfig.Secret.GetPayload())
  320. if !match || err != nil {
  321. renderClientTwoFactorPage(w, "Invalid authentication code")
  322. return
  323. }
  324. connectionID := fmt.Sprintf("%v_%v", common.ProtocolHTTP, xid.New().String())
  325. s.loginUser(w, r, &user, connectionID, util.GetIPFromRemoteAddress(r.RemoteAddr), true, renderClientTwoFactorPage)
  326. }
  327. func (s *httpdServer) handleWebAdminTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
  328. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  329. claims, err := getTokenClaims(r)
  330. if err != nil {
  331. renderNotFoundPage(w, r, nil)
  332. return
  333. }
  334. if err := r.ParseForm(); err != nil {
  335. renderTwoFactorRecoveryPage(w, err.Error())
  336. return
  337. }
  338. username := claims.Username
  339. recoveryCode := r.Form.Get("recovery_code")
  340. if username == "" || recoveryCode == "" {
  341. renderTwoFactorRecoveryPage(w, "Invalid credentials")
  342. return
  343. }
  344. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  345. renderTwoFactorRecoveryPage(w, err.Error())
  346. return
  347. }
  348. admin, err := dataprovider.AdminExists(username)
  349. if err != nil {
  350. renderTwoFactorRecoveryPage(w, "Invalid credentials")
  351. return
  352. }
  353. if !admin.Filters.TOTPConfig.Enabled {
  354. renderTwoFactorRecoveryPage(w, "Two factory authentication is not enabled")
  355. return
  356. }
  357. for idx, code := range admin.Filters.RecoveryCodes {
  358. if err := code.Secret.Decrypt(); err != nil {
  359. renderInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
  360. return
  361. }
  362. if code.Secret.GetPayload() == recoveryCode {
  363. if code.Used {
  364. renderTwoFactorRecoveryPage(w, "This recovery code was already used")
  365. return
  366. }
  367. admin.Filters.RecoveryCodes[idx].Used = true
  368. err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, util.GetIPFromRemoteAddress(r.RemoteAddr))
  369. if err != nil {
  370. logger.Warn(logSender, "", "unable to set the recovery code %#v as used: %v", recoveryCode, err)
  371. renderInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
  372. return
  373. }
  374. s.loginAdmin(w, r, &admin, true, renderTwoFactorRecoveryPage)
  375. return
  376. }
  377. }
  378. renderTwoFactorRecoveryPage(w, "Invalid recovery code")
  379. }
  380. func (s *httpdServer) handleWebAdminTwoFactorPost(w http.ResponseWriter, r *http.Request) {
  381. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  382. claims, err := getTokenClaims(r)
  383. if err != nil {
  384. renderNotFoundPage(w, r, nil)
  385. return
  386. }
  387. if err := r.ParseForm(); err != nil {
  388. renderTwoFactorPage(w, err.Error())
  389. return
  390. }
  391. username := claims.Username
  392. passcode := r.Form.Get("passcode")
  393. if username == "" || passcode == "" {
  394. renderTwoFactorPage(w, "Invalid credentials")
  395. return
  396. }
  397. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  398. renderTwoFactorPage(w, err.Error())
  399. return
  400. }
  401. admin, err := dataprovider.AdminExists(username)
  402. if err != nil {
  403. renderTwoFactorPage(w, "Invalid credentials")
  404. return
  405. }
  406. if !admin.Filters.TOTPConfig.Enabled {
  407. renderTwoFactorPage(w, "Two factory authentication is not enabled")
  408. return
  409. }
  410. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  411. if err != nil {
  412. renderInternalServerErrorPage(w, r, err)
  413. return
  414. }
  415. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  416. admin.Filters.TOTPConfig.Secret.GetPayload())
  417. if !match || err != nil {
  418. renderTwoFactorPage(w, "Invalid authentication code")
  419. return
  420. }
  421. s.loginAdmin(w, r, &admin, true, renderTwoFactorPage)
  422. }
  423. func (s *httpdServer) handleWebAdminLoginPost(w http.ResponseWriter, r *http.Request) {
  424. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  425. if err := r.ParseForm(); err != nil {
  426. s.renderAdminLoginPage(w, err.Error())
  427. return
  428. }
  429. username := r.Form.Get("username")
  430. password := r.Form.Get("password")
  431. if username == "" || password == "" {
  432. s.renderAdminLoginPage(w, "Invalid credentials")
  433. return
  434. }
  435. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  436. s.renderAdminLoginPage(w, err.Error())
  437. return
  438. }
  439. admin, err := dataprovider.CheckAdminAndPass(username, password, util.GetIPFromRemoteAddress(r.RemoteAddr))
  440. if err != nil {
  441. s.renderAdminLoginPage(w, err.Error())
  442. return
  443. }
  444. s.loginAdmin(w, r, &admin, false, s.renderAdminLoginPage)
  445. }
  446. func (s *httpdServer) renderAdminLoginPage(w http.ResponseWriter, error string) {
  447. data := loginPage{
  448. CurrentURL: webLoginPath,
  449. Version: version.Get().Version,
  450. Error: error,
  451. CSRFToken: createCSRFToken(),
  452. StaticURL: webStaticFilesPath,
  453. }
  454. if s.binding.showClientLoginURL() {
  455. data.AltLoginURL = webClientLoginPath
  456. }
  457. if smtp.IsEnabled() {
  458. data.ForgotPwdURL = webAdminForgotPwdPath
  459. }
  460. renderAdminTemplate(w, templateLogin, data)
  461. }
  462. func (s *httpdServer) handleWebAdminLogin(w http.ResponseWriter, r *http.Request) {
  463. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  464. if !dataprovider.HasAdmin() {
  465. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  466. return
  467. }
  468. s.renderAdminLoginPage(w, "")
  469. }
  470. func (s *httpdServer) handleWebAdminPasswordResetPost(w http.ResponseWriter, r *http.Request) {
  471. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  472. err := r.ParseForm()
  473. if err != nil {
  474. renderResetPwdPage(w, err.Error())
  475. return
  476. }
  477. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  478. renderForbiddenPage(w, r, err.Error())
  479. return
  480. }
  481. admin, _, err := handleResetPassword(r, r.Form.Get("code"), r.Form.Get("password"), true)
  482. if err != nil {
  483. if e, ok := err.(*util.ValidationError); ok {
  484. renderResetPwdPage(w, e.GetErrorString())
  485. return
  486. }
  487. renderResetPwdPage(w, err.Error())
  488. return
  489. }
  490. s.loginAdmin(w, r, admin, false, renderResetPwdPage)
  491. }
  492. func (s *httpdServer) handleWebAdminSetupPost(w http.ResponseWriter, r *http.Request) {
  493. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  494. if dataprovider.HasAdmin() {
  495. renderBadRequestPage(w, r, errors.New("an admin user already exists"))
  496. return
  497. }
  498. err := r.ParseForm()
  499. if err != nil {
  500. renderAdminSetupPage(w, r, "", err.Error())
  501. return
  502. }
  503. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  504. renderForbiddenPage(w, r, err.Error())
  505. return
  506. }
  507. username := r.Form.Get("username")
  508. password := r.Form.Get("password")
  509. confirmPassword := r.Form.Get("confirm_password")
  510. if username == "" {
  511. renderAdminSetupPage(w, r, username, "Please set a username")
  512. return
  513. }
  514. if password == "" {
  515. renderAdminSetupPage(w, r, username, "Please set a password")
  516. return
  517. }
  518. if password != confirmPassword {
  519. renderAdminSetupPage(w, r, username, "Passwords mismatch")
  520. return
  521. }
  522. admin := dataprovider.Admin{
  523. Username: username,
  524. Password: password,
  525. Status: 1,
  526. Permissions: []string{dataprovider.PermAdminAny},
  527. }
  528. err = dataprovider.AddAdmin(&admin, username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  529. if err != nil {
  530. renderAdminSetupPage(w, r, username, err.Error())
  531. return
  532. }
  533. s.loginAdmin(w, r, &admin, false, nil)
  534. }
  535. func (s *httpdServer) loginUser(
  536. w http.ResponseWriter, r *http.Request, user *dataprovider.User, connectionID, ipAddr string,
  537. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, error string),
  538. ) {
  539. c := jwtTokenClaims{
  540. Username: user.Username,
  541. Permissions: user.Filters.WebClient,
  542. Signature: user.GetSignature(),
  543. }
  544. audience := tokenAudienceWebClient
  545. if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) &&
  546. user.CanManageMFA() && !isSecondFactorAuth {
  547. audience = tokenAudienceWebClientPartial
  548. }
  549. err := c.createAndSetCookie(w, r, s.tokenAuth, audience)
  550. if err != nil {
  551. logger.Warn(logSender, connectionID, "unable to set user login cookie %v", err)
  552. updateLoginMetrics(user, ipAddr, common.ErrInternalFailure)
  553. errorFunc(w, err.Error())
  554. return
  555. }
  556. if isSecondFactorAuth {
  557. invalidateToken(r)
  558. }
  559. if audience == tokenAudienceWebClientPartial {
  560. http.Redirect(w, r, webClientTwoFactorPath, http.StatusFound)
  561. return
  562. }
  563. updateLoginMetrics(user, ipAddr, err)
  564. dataprovider.UpdateLastLogin(user)
  565. http.Redirect(w, r, webClientFilesPath, http.StatusFound)
  566. }
  567. func (s *httpdServer) loginAdmin(
  568. w http.ResponseWriter, r *http.Request, admin *dataprovider.Admin,
  569. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, error string),
  570. ) {
  571. c := jwtTokenClaims{
  572. Username: admin.Username,
  573. Permissions: admin.Permissions,
  574. Signature: admin.GetSignature(),
  575. }
  576. audience := tokenAudienceWebAdmin
  577. if admin.Filters.TOTPConfig.Enabled && admin.CanManageMFA() && !isSecondFactorAuth {
  578. audience = tokenAudienceWebAdminPartial
  579. }
  580. err := c.createAndSetCookie(w, r, s.tokenAuth, audience)
  581. if err != nil {
  582. logger.Warn(logSender, "", "unable to set admin login cookie %v", err)
  583. if errorFunc == nil {
  584. renderAdminSetupPage(w, r, admin.Username, err.Error())
  585. return
  586. }
  587. errorFunc(w, err.Error())
  588. return
  589. }
  590. if isSecondFactorAuth {
  591. invalidateToken(r)
  592. }
  593. if audience == tokenAudienceWebAdminPartial {
  594. http.Redirect(w, r, webAdminTwoFactorPath, http.StatusFound)
  595. return
  596. }
  597. dataprovider.UpdateAdminLastLogin(admin)
  598. http.Redirect(w, r, webUsersPath, http.StatusFound)
  599. }
  600. func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
  601. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  602. invalidateToken(r)
  603. sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
  604. }
  605. func (s *httpdServer) getUserToken(w http.ResponseWriter, r *http.Request) {
  606. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  607. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  608. username, password, ok := r.BasicAuth()
  609. if !ok {
  610. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}}, ipAddr, common.ErrNoCredentials)
  611. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  612. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  613. return
  614. }
  615. if username == "" || password == "" {
  616. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}}, ipAddr, common.ErrNoCredentials)
  617. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  618. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  619. return
  620. }
  621. if err := common.Config.ExecutePostConnectHook(ipAddr, common.ProtocolHTTP); err != nil {
  622. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  623. return
  624. }
  625. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, common.ProtocolHTTP)
  626. if err != nil {
  627. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  628. updateLoginMetrics(&user, ipAddr, err)
  629. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  630. http.StatusUnauthorized)
  631. return
  632. }
  633. connectionID := fmt.Sprintf("%v_%v", common.ProtocolHTTP, xid.New().String())
  634. if err := checkHTTPClientUser(&user, r, connectionID); err != nil {
  635. updateLoginMetrics(&user, ipAddr, err)
  636. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  637. return
  638. }
  639. if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
  640. passcode := r.Header.Get(otpHeaderCode)
  641. if passcode == "" {
  642. logger.Debug(logSender, "", "TOTP enabled for user %#v and not passcode provided, authentication refused", user.Username)
  643. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  644. updateLoginMetrics(&user, ipAddr, dataprovider.ErrInvalidCredentials)
  645. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  646. http.StatusUnauthorized)
  647. return
  648. }
  649. err = user.Filters.TOTPConfig.Secret.Decrypt()
  650. if err != nil {
  651. updateLoginMetrics(&user, ipAddr, common.ErrInternalFailure)
  652. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err), http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  653. return
  654. }
  655. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  656. user.Filters.TOTPConfig.Secret.GetPayload())
  657. if !match || err != nil {
  658. logger.Debug(logSender, "invalid passcode for user %#v, match? %v, err: %v", user.Username, match, err)
  659. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  660. updateLoginMetrics(&user, ipAddr, dataprovider.ErrInvalidCredentials)
  661. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  662. http.StatusUnauthorized)
  663. return
  664. }
  665. }
  666. defer user.CloseFs() //nolint:errcheck
  667. err = user.CheckFsRoot(connectionID)
  668. if err != nil {
  669. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  670. updateLoginMetrics(&user, ipAddr, common.ErrInternalFailure)
  671. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  672. return
  673. }
  674. s.generateAndSendUserToken(w, r, ipAddr, user)
  675. }
  676. func (s *httpdServer) generateAndSendUserToken(w http.ResponseWriter, r *http.Request, ipAddr string, user dataprovider.User) {
  677. c := jwtTokenClaims{
  678. Username: user.Username,
  679. Permissions: user.Filters.WebClient,
  680. Signature: user.GetSignature(),
  681. }
  682. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPIUser)
  683. if err != nil {
  684. updateLoginMetrics(&user, ipAddr, common.ErrInternalFailure)
  685. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  686. return
  687. }
  688. updateLoginMetrics(&user, ipAddr, err)
  689. dataprovider.UpdateLastLogin(&user)
  690. render.JSON(w, r, resp)
  691. }
  692. func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
  693. username, password, ok := r.BasicAuth()
  694. if !ok {
  695. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  696. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  697. return
  698. }
  699. admin, err := dataprovider.CheckAdminAndPass(username, password, util.GetIPFromRemoteAddress(r.RemoteAddr))
  700. if err != nil {
  701. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  702. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  703. return
  704. }
  705. if admin.Filters.TOTPConfig.Enabled {
  706. passcode := r.Header.Get(otpHeaderCode)
  707. if passcode == "" {
  708. logger.Debug(logSender, "", "TOTP enabled for admin %#v and not passcode provided, authentication refused", admin.Username)
  709. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  710. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  711. return
  712. }
  713. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  714. if err != nil {
  715. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err),
  716. http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  717. return
  718. }
  719. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  720. admin.Filters.TOTPConfig.Secret.GetPayload())
  721. if !match || err != nil {
  722. logger.Debug(logSender, "invalid passcode for admin %#v, match? %v, err: %v", admin.Username, match, err)
  723. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  724. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  725. http.StatusUnauthorized)
  726. return
  727. }
  728. }
  729. s.generateAndSendToken(w, r, admin)
  730. }
  731. func (s *httpdServer) generateAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin) {
  732. c := jwtTokenClaims{
  733. Username: admin.Username,
  734. Permissions: admin.Permissions,
  735. Signature: admin.GetSignature(),
  736. }
  737. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI)
  738. if err != nil {
  739. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  740. return
  741. }
  742. dataprovider.UpdateAdminLastLogin(&admin)
  743. render.JSON(w, r, resp)
  744. }
  745. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  746. token, claims, err := jwtauth.FromContext(r.Context())
  747. if err != nil {
  748. return
  749. }
  750. tokenClaims := jwtTokenClaims{}
  751. tokenClaims.Decode(claims)
  752. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  753. return
  754. }
  755. if time.Until(token.Expiration()) > tokenRefreshThreshold {
  756. return
  757. }
  758. if util.IsStringInSlice(tokenAudienceWebClient, token.Audience()) {
  759. s.refreshClientToken(w, r, tokenClaims)
  760. } else {
  761. s.refreshAdminToken(w, r, tokenClaims)
  762. }
  763. }
  764. func (s *httpdServer) refreshClientToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  765. user, err := dataprovider.UserExists(tokenClaims.Username)
  766. if err != nil {
  767. return
  768. }
  769. if user.GetSignature() != tokenClaims.Signature {
  770. logger.Debug(logSender, "", "signature mismatch for user %#v, unable to refresh cookie", user.Username)
  771. return
  772. }
  773. if err := checkHTTPClientUser(&user, r, xid.New().String()); err != nil {
  774. logger.Debug(logSender, "", "unable to refresh cookie for user %#v: %v", user.Username, err)
  775. return
  776. }
  777. tokenClaims.Permissions = user.Filters.WebClient
  778. logger.Debug(logSender, "", "cookie refreshed for user %#v", user.Username)
  779. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebClient) //nolint:errcheck
  780. }
  781. func (s *httpdServer) refreshAdminToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  782. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  783. if err != nil {
  784. return
  785. }
  786. if admin.Status != 1 {
  787. logger.Debug(logSender, "", "admin %#v is disabled, unable to refresh cookie", admin.Username)
  788. return
  789. }
  790. if admin.GetSignature() != tokenClaims.Signature {
  791. logger.Debug(logSender, "", "signature mismatch for admin %#v, unable to refresh cookie", admin.Username)
  792. return
  793. }
  794. if !admin.CanLoginFromIP(util.GetIPFromRemoteAddress(r.RemoteAddr)) {
  795. logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie", admin.Username, r.RemoteAddr)
  796. return
  797. }
  798. tokenClaims.Permissions = admin.Permissions
  799. logger.Debug(logSender, "", "cookie refreshed for admin %#v", admin.Username)
  800. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebAdmin) //nolint:errcheck
  801. }
  802. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  803. token, _, err := jwtauth.FromContext(r.Context())
  804. if token == nil || err != nil {
  805. _, err = r.Cookie("jwt")
  806. if err != nil {
  807. return r
  808. }
  809. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  810. ctx := jwtauth.NewContext(r.Context(), token, err)
  811. return r.WithContext(ctx)
  812. }
  813. return r
  814. }
  815. func (s *httpdServer) checkConnection(next http.Handler) http.Handler {
  816. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  817. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  818. ip := net.ParseIP(ipAddr)
  819. if ip != nil {
  820. for _, allow := range s.binding.allowHeadersFrom {
  821. if allow(ip) {
  822. parsedIP := util.GetRealIP(r)
  823. if parsedIP != "" {
  824. ipAddr = parsedIP
  825. r.RemoteAddr = ipAddr
  826. }
  827. if forwardedProto := r.Header.Get(xForwardedProto); forwardedProto != "" {
  828. ctx := context.WithValue(r.Context(), forwardedProtoKey, forwardedProto)
  829. r = r.WithContext(ctx)
  830. }
  831. break
  832. }
  833. }
  834. }
  835. common.Connections.AddClientConnection(ipAddr)
  836. defer common.Connections.RemoveClientConnection(ipAddr)
  837. if !common.Connections.IsNewConnectionAllowed(ipAddr) {
  838. logger.Log(logger.LevelDebug, common.ProtocolHTTP, "", "connection refused, configured limit reached")
  839. s.sendForbiddenResponse(w, r, "configured connections limit reached")
  840. return
  841. }
  842. if common.IsBanned(ipAddr) {
  843. s.sendForbiddenResponse(w, r, "your IP address is banned")
  844. return
  845. }
  846. if delay, err := common.LimitRate(common.ProtocolHTTP, ipAddr); err != nil {
  847. delay += 499999999 * time.Nanosecond
  848. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  849. w.Header().Set("X-Retry-In", delay.String())
  850. s.sendTooManyRequestResponse(w, r, err)
  851. return
  852. }
  853. next.ServeHTTP(w, r)
  854. })
  855. }
  856. func (s *httpdServer) sendTooManyRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
  857. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  858. r = s.updateContextFromCookie(r)
  859. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  860. renderClientMessagePage(w, r, http.StatusText(http.StatusTooManyRequests), "Rate limit exceeded",
  861. http.StatusTooManyRequests, err, "")
  862. return
  863. }
  864. renderMessagePage(w, r, http.StatusText(http.StatusTooManyRequests), "Rate limit exceeded", http.StatusTooManyRequests,
  865. err, "")
  866. return
  867. }
  868. sendAPIResponse(w, r, err, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
  869. }
  870. func (s *httpdServer) sendForbiddenResponse(w http.ResponseWriter, r *http.Request, message string) {
  871. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  872. r = s.updateContextFromCookie(r)
  873. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  874. renderClientForbiddenPage(w, r, message)
  875. return
  876. }
  877. renderForbiddenPage(w, r, message)
  878. return
  879. }
  880. sendAPIResponse(w, r, errors.New(message), message, http.StatusForbidden)
  881. }
  882. func (s *httpdServer) redirectToWebPath(w http.ResponseWriter, r *http.Request, webPath string) {
  883. if dataprovider.HasAdmin() {
  884. http.Redirect(w, r, webPath, http.StatusMovedPermanently)
  885. return
  886. }
  887. if s.enableWebAdmin {
  888. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  889. }
  890. }
  891. func (s *httpdServer) isStaticFileURL(r *http.Request) bool {
  892. var urlPath string
  893. rctx := chi.RouteContext(r.Context())
  894. if rctx != nil && rctx.RoutePath != "" {
  895. urlPath = rctx.RoutePath
  896. } else {
  897. urlPath = r.URL.Path
  898. }
  899. return !strings.HasPrefix(urlPath, webOpenAPIPath) && !strings.HasPrefix(urlPath, webStaticFilesPath)
  900. }
  901. func (s *httpdServer) initializeRouter() {
  902. s.tokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(s.signingPassphrase), nil)
  903. s.router = chi.NewRouter()
  904. s.router.Use(middleware.RequestID)
  905. s.router.Use(s.checkConnection)
  906. s.router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  907. s.router.Use(middleware.Recoverer)
  908. if s.cors.Enabled {
  909. c := cors.New(cors.Options{
  910. AllowedOrigins: s.cors.AllowedOrigins,
  911. AllowedMethods: s.cors.AllowedMethods,
  912. AllowedHeaders: s.cors.AllowedHeaders,
  913. ExposedHeaders: s.cors.ExposedHeaders,
  914. MaxAge: s.cors.MaxAge,
  915. AllowCredentials: s.cors.AllowCredentials,
  916. })
  917. s.router.Use(c.Handler)
  918. }
  919. s.router.Use(middleware.GetHead)
  920. // StripSlashes causes infinite redirects at the root path if used with http.FileServer
  921. s.router.Use(middleware.Maybe(middleware.StripSlashes, s.isStaticFileURL))
  922. s.router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  923. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  924. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  925. r = s.updateContextFromCookie(r)
  926. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  927. renderClientNotFoundPage(w, r, nil)
  928. return
  929. }
  930. renderNotFoundPage(w, r, nil)
  931. return
  932. }
  933. sendAPIResponse(w, r, nil, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  934. }))
  935. s.router.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  936. render.PlainText(w, r, "ok")
  937. })
  938. // share API exposed to external users
  939. s.router.Get(sharesPath+"/{id}", downloadFromShare)
  940. s.router.Post(sharesPath+"/{id}", uploadFilesToShare)
  941. s.router.Post(sharesPath+"/{id}/{name}", uploadFileToShare)
  942. s.router.Get(tokenPath, s.getToken)
  943. s.router.Post(adminPath+"/{username}/forgot-password", forgotAdminPassword)
  944. s.router.Post(adminPath+"/{username}/reset-password", resetAdminPassword)
  945. s.router.Post(userPath+"/{username}/forgot-password", forgotUserPassword)
  946. s.router.Post(userPath+"/{username}/reset-password", resetUserPassword)
  947. s.router.Group(func(router chi.Router) {
  948. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeAdmin))
  949. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  950. router.Use(jwtAuthenticatorAPI)
  951. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  952. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  953. render.JSON(w, r, version.Get())
  954. })
  955. router.With(forbidAPIKeyAuthentication).Get(logoutPath, s.logout)
  956. router.With(forbidAPIKeyAuthentication).Get(adminProfilePath, getAdminProfile)
  957. router.With(forbidAPIKeyAuthentication).Put(adminProfilePath, updateAdminProfile)
  958. router.With(forbidAPIKeyAuthentication).Put(adminPwdPath, changeAdminPassword)
  959. // compatibility layer to remove in v2.2
  960. router.With(forbidAPIKeyAuthentication).Put(adminPwdCompatPath, changeAdminPassword)
  961. // admin TOTP APIs
  962. router.With(forbidAPIKeyAuthentication).Get(adminTOTPConfigsPath, getTOTPConfigs)
  963. router.With(forbidAPIKeyAuthentication).Post(adminTOTPGeneratePath, generateTOTPSecret)
  964. router.With(forbidAPIKeyAuthentication).Post(adminTOTPValidatePath, validateTOTPPasscode)
  965. router.With(forbidAPIKeyAuthentication).Post(adminTOTPSavePath, saveTOTPConfig)
  966. router.With(forbidAPIKeyAuthentication).Get(admin2FARecoveryCodesPath, getRecoveryCodes)
  967. router.With(forbidAPIKeyAuthentication).Post(admin2FARecoveryCodesPath, generateRecoveryCodes)
  968. router.With(checkPerm(dataprovider.PermAdminViewServerStatus)).
  969. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  970. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  971. render.JSON(w, r, getServicesStatus())
  972. })
  973. router.With(checkPerm(dataprovider.PermAdminViewConnections)).
  974. Get(activeConnectionsPath, func(w http.ResponseWriter, r *http.Request) {
  975. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  976. render.JSON(w, r, common.Connections.GetStats())
  977. })
  978. router.With(checkPerm(dataprovider.PermAdminCloseConnections)).
  979. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  980. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanPath, getUsersQuotaScans)
  981. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/users/scans", getUsersQuotaScans)
  982. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanPath, startUserQuotaScanCompat)
  983. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/users/{username}/scan", startUserQuotaScan)
  984. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanVFolderPath, getFoldersQuotaScans)
  985. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/folders/scans", getFoldersQuotaScans)
  986. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanVFolderPath, startFolderQuotaScanCompat)
  987. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/folders/{name}/scan", startFolderQuotaScan)
  988. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  989. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  990. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername)
  991. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  992. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  993. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}/2fa/disable", disableUser2FA)
  994. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath, getFolders)
  995. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath+"/{name}", getFolderByName)
  996. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(folderPath, addFolder)
  997. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(folderPath+"/{name}", updateFolder)
  998. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(folderPath+"/{name}", deleteFolder)
  999. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(dumpDataPath, dumpData)
  1000. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(loadDataPath, loadData)
  1001. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(loadDataPath, loadDataFromRequest)
  1002. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateUsedQuotaPath, updateUserQuotaUsageCompat)
  1003. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/usage", updateUserQuotaUsage)
  1004. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateFolderUsedQuotaPath, updateFolderQuotaUsageCompat)
  1005. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage", updateFolderQuotaUsage)
  1006. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
  1007. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
  1008. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
  1009. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderBanTime, getBanTime)
  1010. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderScore, getScore)
  1011. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Post(defenderUnban, unban)
  1012. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
  1013. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
  1014. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
  1015. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
  1016. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
  1017. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1018. router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Get(retentionChecksPath, getRetentionChecks)
  1019. router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Post(retentionBasePath+"/{username}/check",
  1020. startRetentionCheck)
  1021. router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Get(metadataChecksPath, getMetadataChecks)
  1022. router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Post(metadataBasePath+"/{username}/check",
  1023. startMetadataCheck)
  1024. router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1025. Get(fsEventsPath, searchFsEvents)
  1026. router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1027. Get(providerEventsPath, searchProviderEvents)
  1028. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1029. Get(apiKeysPath, getAPIKeys)
  1030. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1031. Post(apiKeysPath, addAPIKey)
  1032. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1033. Get(apiKeysPath+"/{id}", getAPIKeyByID)
  1034. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1035. Put(apiKeysPath+"/{id}", updateAPIKey)
  1036. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1037. Delete(apiKeysPath+"/{id}", deleteAPIKey)
  1038. })
  1039. s.router.Get(userTokenPath, s.getUserToken)
  1040. s.router.Group(func(router chi.Router) {
  1041. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
  1042. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1043. router.Use(jwtAuthenticatorAPIUser)
  1044. router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
  1045. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1046. Put(userPwdPath, changeUserPassword)
  1047. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).
  1048. Get(userPublicKeysPath, getUserPublicKeys)
  1049. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).
  1050. Put(userPublicKeysPath, setUserPublicKeys)
  1051. router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
  1052. router.With(forbidAPIKeyAuthentication).Put(userProfilePath, updateUserProfile)
  1053. // user TOTP APIs
  1054. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1055. Get(userTOTPConfigsPath, getTOTPConfigs)
  1056. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1057. Post(userTOTPGeneratePath, generateTOTPSecret)
  1058. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1059. Post(userTOTPValidatePath, validateTOTPPasscode)
  1060. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1061. Post(userTOTPSavePath, saveTOTPConfig)
  1062. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1063. Get(user2FARecoveryCodesPath, getRecoveryCodes)
  1064. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1065. Post(user2FARecoveryCodesPath, generateRecoveryCodes)
  1066. // compatibility layer to remove in v2.3
  1067. router.With(compressor.Handler).Get(userFolderPath, readUserFolder)
  1068. router.Get(userFilePath, getUserFile)
  1069. router.With(compressor.Handler).Get(userDirsPath, readUserFolder)
  1070. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userDirsPath, createUserDir)
  1071. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userDirsPath, renameUserDir)
  1072. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Delete(userDirsPath, deleteUserDir)
  1073. router.Get(userFilesPath, getUserFile)
  1074. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userFilesPath, uploadUserFiles)
  1075. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userFilesPath, renameUserFile)
  1076. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Delete(userFilesPath, deleteUserFile)
  1077. router.Post(userStreamZipPath, getUserFilesAsZipStream)
  1078. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Get(userSharesPath, getShares)
  1079. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Post(userSharesPath, addShare)
  1080. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Get(userSharesPath+"/{id}", getShareByID)
  1081. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Put(userSharesPath+"/{id}", updateShare)
  1082. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Delete(userSharesPath+"/{id}", deleteShare)
  1083. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userUploadFilePath, uploadUserFile)
  1084. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userFilesDirsMetadataPath, setFileDirMetadata)
  1085. })
  1086. if s.renderOpenAPI {
  1087. s.router.Group(func(router chi.Router) {
  1088. router.Use(compressor.Handler)
  1089. fileServer(router, webOpenAPIPath, http.Dir(s.openAPIPath))
  1090. })
  1091. }
  1092. if s.enableWebAdmin || s.enableWebClient {
  1093. s.router.Group(func(router chi.Router) {
  1094. router.Use(compressor.Handler)
  1095. fileServer(router, webStaticFilesPath, http.Dir(s.staticFilesPath))
  1096. })
  1097. if s.enableWebClient {
  1098. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1099. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1100. s.redirectToWebPath(w, r, webClientLoginPath)
  1101. })
  1102. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1103. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1104. s.redirectToWebPath(w, r, webClientLoginPath)
  1105. })
  1106. } else {
  1107. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1108. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1109. s.redirectToWebPath(w, r, webLoginPath)
  1110. })
  1111. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1112. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1113. s.redirectToWebPath(w, r, webLoginPath)
  1114. })
  1115. }
  1116. }
  1117. if s.enableWebClient {
  1118. s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
  1119. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1120. http.Redirect(w, r, webClientLoginPath, http.StatusMovedPermanently)
  1121. })
  1122. s.router.Get(webClientLoginPath, s.handleClientWebLogin)
  1123. s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
  1124. s.router.Get(webClientForgotPwdPath, handleWebClientForgotPwd)
  1125. s.router.Post(webClientForgotPwdPath, handleWebClientForgotPwdPost)
  1126. s.router.Get(webClientResetPwdPath, handleWebClientPasswordReset)
  1127. s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
  1128. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1129. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1130. Get(webClientTwoFactorPath, handleWebClientTwoFactor)
  1131. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1132. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1133. Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
  1134. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1135. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1136. Get(webClientTwoFactorRecoveryPath, handleWebClientTwoFactorRecovery)
  1137. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1138. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1139. Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
  1140. // share API exposed to external users
  1141. s.router.Get(webClientPubSharesPath+"/{id}", downloadFromShare)
  1142. s.router.Post(webClientPubSharesPath+"/{id}", uploadFilesToShare)
  1143. s.router.Post(webClientPubSharesPath+"/{id}/{name}", uploadFileToShare)
  1144. s.router.Group(func(router chi.Router) {
  1145. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie))
  1146. router.Use(jwtAuthenticatorWebClient)
  1147. router.Get(webClientLogoutPath, handleWebClientLogout)
  1148. router.With(s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
  1149. router.With(s.refreshCookie).Get(webClientViewPDFPath, handleClientViewPDF)
  1150. router.With(s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
  1151. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1152. Post(webClientFilePath, uploadUserFile)
  1153. router.With(s.refreshCookie).Get(webClientEditFilePath, handleClientEditFile)
  1154. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1155. Patch(webClientFilesPath, renameUserFile)
  1156. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1157. Delete(webClientFilesPath, deleteUserFile)
  1158. router.With(compressor.Handler, s.refreshCookie).Get(webClientDirsPath, s.handleClientGetDirContents)
  1159. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1160. Post(webClientDirsPath, createUserDir)
  1161. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1162. Patch(webClientDirsPath, renameUserDir)
  1163. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1164. Delete(webClientDirsPath, deleteUserDir)
  1165. router.With(s.refreshCookie).Get(webClientDownloadZipPath, handleWebClientDownloadZip)
  1166. router.With(s.refreshCookie).Get(webClientProfilePath, handleClientGetProfile)
  1167. router.Post(webClientProfilePath, handleWebClientProfilePost)
  1168. router.With(checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1169. Get(webChangeClientPwdPath, handleWebClientChangePwd)
  1170. router.With(checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1171. Post(webChangeClientPwdPath, handleWebClientChangePwdPost)
  1172. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1173. Get(webClientMFAPath, handleWebClientMFA)
  1174. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1175. Post(webClientTOTPGeneratePath, generateTOTPSecret)
  1176. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1177. Post(webClientTOTPValidatePath, validateTOTPPasscode)
  1178. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1179. Post(webClientTOTPSavePath, saveTOTPConfig)
  1180. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
  1181. Get(webClientRecoveryCodesPath, getRecoveryCodes)
  1182. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1183. Post(webClientRecoveryCodesPath, generateRecoveryCodes)
  1184. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1185. Get(webClientSharesPath, handleClientGetShares)
  1186. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1187. Get(webClientSharePath, handleClientAddShareGet)
  1188. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Post(webClientSharePath,
  1189. handleClientAddSharePost)
  1190. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1191. Get(webClientSharePath+"/{id}", handleClientUpdateShareGet)
  1192. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1193. Post(webClientSharePath+"/{id}", handleClientUpdateSharePost)
  1194. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
  1195. Delete(webClientSharePath+"/{id}", deleteShare)
  1196. })
  1197. }
  1198. if s.enableWebAdmin {
  1199. s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
  1200. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1201. s.redirectToWebPath(w, r, webLoginPath)
  1202. })
  1203. s.router.Get(webLoginPath, s.handleWebAdminLogin)
  1204. s.router.Post(webLoginPath, s.handleWebAdminLoginPost)
  1205. s.router.Get(webAdminSetupPath, handleWebAdminSetupGet)
  1206. s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
  1207. s.router.Get(webAdminForgotPwdPath, handleWebAdminForgotPwd)
  1208. s.router.Post(webAdminForgotPwdPath, handleWebAdminForgotPwdPost)
  1209. s.router.Get(webAdminResetPwdPath, handleWebAdminPasswordReset)
  1210. s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
  1211. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1212. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1213. Get(webAdminTwoFactorPath, handleWebAdminTwoFactor)
  1214. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1215. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1216. Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
  1217. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1218. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1219. Get(webAdminTwoFactorRecoveryPath, handleWebAdminTwoFactorRecovery)
  1220. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1221. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1222. Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
  1223. s.router.Group(func(router chi.Router) {
  1224. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie))
  1225. router.Use(jwtAuthenticatorWebAdmin)
  1226. router.Get(webLogoutPath, handleWebLogout)
  1227. router.With(s.refreshCookie).Get(webAdminProfilePath, handleWebAdminProfile)
  1228. router.Post(webAdminProfilePath, handleWebAdminProfilePost)
  1229. router.With(s.refreshCookie).Get(webChangeAdminPwdPath, handleWebAdminChangePwd)
  1230. router.Post(webChangeAdminPwdPath, handleWebAdminChangePwdPost)
  1231. router.With(s.refreshCookie).Get(webAdminMFAPath, handleWebAdminMFA)
  1232. router.With(verifyCSRFHeader).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
  1233. router.With(verifyCSRFHeader).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
  1234. router.With(verifyCSRFHeader).Post(webAdminTOTPSavePath, saveTOTPConfig)
  1235. router.With(verifyCSRFHeader, s.refreshCookie).Get(webAdminRecoveryCodesPath, getRecoveryCodes)
  1236. router.With(verifyCSRFHeader).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
  1237. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1238. Get(webUsersPath, handleGetWebUsers)
  1239. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1240. Get(webUserPath, handleWebAddUserGet)
  1241. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1242. Get(webUserPath+"/{username}", handleWebUpdateUserGet)
  1243. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, handleWebAddUserPost)
  1244. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}", handleWebUpdateUserPost)
  1245. router.With(checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1246. Get(webConnectionsPath, handleWebGetConnections)
  1247. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1248. Get(webFoldersPath, handleWebGetFolders)
  1249. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1250. Get(webFolderPath, handleWebAddFolderGet)
  1251. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webFolderPath, handleWebAddFolderPost)
  1252. router.With(checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  1253. Get(webStatusPath, handleWebGetStatus)
  1254. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1255. Get(webAdminsPath, handleGetWebAdmins)
  1256. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1257. Get(webAdminPath, handleWebAddAdminGet)
  1258. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1259. Get(webAdminPath+"/{username}", handleWebUpdateAdminGet)
  1260. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, handleWebAddAdminPost)
  1261. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}",
  1262. handleWebUpdateAdminPost)
  1263. router.With(checkPerm(dataprovider.PermAdminManageAdmins), verifyCSRFHeader).
  1264. Delete(webAdminPath+"/{username}", deleteAdmin)
  1265. router.With(checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  1266. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  1267. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1268. Get(webFolderPath+"/{name}", handleWebUpdateFolderGet)
  1269. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webFolderPath+"/{name}",
  1270. handleWebUpdateFolderPost)
  1271. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1272. Delete(webFolderPath+"/{name}", deleteFolder)
  1273. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1274. Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
  1275. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1276. Delete(webUserPath+"/{username}", deleteUser)
  1277. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1278. Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
  1279. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, handleWebMaintenance)
  1280. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
  1281. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, handleWebRestore)
  1282. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1283. Get(webTemplateUser, handleWebTemplateUserGet)
  1284. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, handleWebTemplateUserPost)
  1285. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1286. Get(webTemplateFolder, handleWebTemplateFolderGet)
  1287. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateFolder, handleWebTemplateFolderPost)
  1288. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, handleWebDefenderPage)
  1289. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
  1290. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(webDefenderHostsPath+"/{id}",
  1291. deleteDefenderHostByID)
  1292. })
  1293. }
  1294. }