server.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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/sftpgo/sdk"
  21. "github.com/drakkan/sftpgo/v2/common"
  22. "github.com/drakkan/sftpgo/v2/dataprovider"
  23. "github.com/drakkan/sftpgo/v2/logger"
  24. "github.com/drakkan/sftpgo/v2/mfa"
  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.StatusFound)
  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",
  1004. updateUserQuotaUsage)
  1005. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/transfer-usage",
  1006. updateUserTransferQuotaUsage)
  1007. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateFolderUsedQuotaPath, updateFolderQuotaUsageCompat)
  1008. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage",
  1009. updateFolderQuotaUsage)
  1010. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
  1011. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
  1012. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
  1013. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderBanTime, getBanTime)
  1014. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderScore, getScore)
  1015. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Post(defenderUnban, unban)
  1016. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
  1017. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
  1018. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
  1019. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
  1020. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
  1021. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1022. router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Get(retentionChecksPath, getRetentionChecks)
  1023. router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Post(retentionBasePath+"/{username}/check",
  1024. startRetentionCheck)
  1025. router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Get(metadataChecksPath, getMetadataChecks)
  1026. router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Post(metadataBasePath+"/{username}/check",
  1027. startMetadataCheck)
  1028. router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1029. Get(fsEventsPath, searchFsEvents)
  1030. router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1031. Get(providerEventsPath, searchProviderEvents)
  1032. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1033. Get(apiKeysPath, getAPIKeys)
  1034. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1035. Post(apiKeysPath, addAPIKey)
  1036. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1037. Get(apiKeysPath+"/{id}", getAPIKeyByID)
  1038. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1039. Put(apiKeysPath+"/{id}", updateAPIKey)
  1040. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1041. Delete(apiKeysPath+"/{id}", deleteAPIKey)
  1042. })
  1043. s.router.Get(userTokenPath, s.getUserToken)
  1044. s.router.Group(func(router chi.Router) {
  1045. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
  1046. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1047. router.Use(jwtAuthenticatorAPIUser)
  1048. router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
  1049. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1050. Put(userPwdPath, changeUserPassword)
  1051. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).
  1052. Get(userPublicKeysPath, getUserPublicKeys)
  1053. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).
  1054. Put(userPublicKeysPath, setUserPublicKeys)
  1055. router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
  1056. router.With(forbidAPIKeyAuthentication).Put(userProfilePath, updateUserProfile)
  1057. // user TOTP APIs
  1058. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1059. Get(userTOTPConfigsPath, getTOTPConfigs)
  1060. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1061. Post(userTOTPGeneratePath, generateTOTPSecret)
  1062. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1063. Post(userTOTPValidatePath, validateTOTPPasscode)
  1064. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1065. Post(userTOTPSavePath, saveTOTPConfig)
  1066. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1067. Get(user2FARecoveryCodesPath, getRecoveryCodes)
  1068. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1069. Post(user2FARecoveryCodesPath, generateRecoveryCodes)
  1070. // compatibility layer to remove in v2.3
  1071. router.With(compressor.Handler).Get(userFolderPath, readUserFolder)
  1072. router.Get(userFilePath, getUserFile)
  1073. router.With(compressor.Handler).Get(userDirsPath, readUserFolder)
  1074. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userDirsPath, createUserDir)
  1075. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userDirsPath, renameUserDir)
  1076. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Delete(userDirsPath, deleteUserDir)
  1077. router.Get(userFilesPath, getUserFile)
  1078. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userFilesPath, uploadUserFiles)
  1079. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userFilesPath, renameUserFile)
  1080. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Delete(userFilesPath, deleteUserFile)
  1081. router.Post(userStreamZipPath, getUserFilesAsZipStream)
  1082. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Get(userSharesPath, getShares)
  1083. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Post(userSharesPath, addShare)
  1084. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Get(userSharesPath+"/{id}", getShareByID)
  1085. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Put(userSharesPath+"/{id}", updateShare)
  1086. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Delete(userSharesPath+"/{id}", deleteShare)
  1087. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userUploadFilePath, uploadUserFile)
  1088. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userFilesDirsMetadataPath, setFileDirMetadata)
  1089. })
  1090. if s.renderOpenAPI {
  1091. s.router.Group(func(router chi.Router) {
  1092. router.Use(compressor.Handler)
  1093. fileServer(router, webOpenAPIPath, http.Dir(s.openAPIPath))
  1094. })
  1095. }
  1096. if s.enableWebAdmin || s.enableWebClient {
  1097. s.router.Group(func(router chi.Router) {
  1098. router.Use(compressor.Handler)
  1099. fileServer(router, webStaticFilesPath, http.Dir(s.staticFilesPath))
  1100. })
  1101. if s.enableWebClient {
  1102. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1103. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1104. s.redirectToWebPath(w, r, webClientLoginPath)
  1105. })
  1106. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1107. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1108. s.redirectToWebPath(w, r, webClientLoginPath)
  1109. })
  1110. } else {
  1111. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1112. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1113. s.redirectToWebPath(w, r, webLoginPath)
  1114. })
  1115. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1116. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1117. s.redirectToWebPath(w, r, webLoginPath)
  1118. })
  1119. }
  1120. }
  1121. if s.enableWebClient {
  1122. s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
  1123. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1124. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  1125. })
  1126. s.router.Get(webClientLoginPath, s.handleClientWebLogin)
  1127. s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
  1128. s.router.Get(webClientForgotPwdPath, handleWebClientForgotPwd)
  1129. s.router.Post(webClientForgotPwdPath, handleWebClientForgotPwdPost)
  1130. s.router.Get(webClientResetPwdPath, handleWebClientPasswordReset)
  1131. s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
  1132. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1133. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1134. Get(webClientTwoFactorPath, handleWebClientTwoFactor)
  1135. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1136. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1137. Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
  1138. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1139. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1140. Get(webClientTwoFactorRecoveryPath, handleWebClientTwoFactorRecovery)
  1141. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1142. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1143. Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
  1144. // share API exposed to external users
  1145. s.router.Get(webClientPubSharesPath+"/{id}", downloadFromShare)
  1146. s.router.Post(webClientPubSharesPath+"/{id}", uploadFilesToShare)
  1147. s.router.Post(webClientPubSharesPath+"/{id}/{name}", uploadFileToShare)
  1148. s.router.Group(func(router chi.Router) {
  1149. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie))
  1150. router.Use(jwtAuthenticatorWebClient)
  1151. router.Get(webClientLogoutPath, handleWebClientLogout)
  1152. router.With(s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
  1153. router.With(s.refreshCookie).Get(webClientViewPDFPath, handleClientViewPDF)
  1154. router.With(s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
  1155. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1156. Post(webClientFilePath, uploadUserFile)
  1157. router.With(s.refreshCookie).Get(webClientEditFilePath, handleClientEditFile)
  1158. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1159. Patch(webClientFilesPath, renameUserFile)
  1160. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1161. Delete(webClientFilesPath, deleteUserFile)
  1162. router.With(compressor.Handler, s.refreshCookie).Get(webClientDirsPath, s.handleClientGetDirContents)
  1163. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1164. Post(webClientDirsPath, createUserDir)
  1165. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1166. Patch(webClientDirsPath, renameUserDir)
  1167. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1168. Delete(webClientDirsPath, deleteUserDir)
  1169. router.With(s.refreshCookie).Get(webClientDownloadZipPath, handleWebClientDownloadZip)
  1170. router.With(s.refreshCookie).Get(webClientProfilePath, handleClientGetProfile)
  1171. router.Post(webClientProfilePath, handleWebClientProfilePost)
  1172. router.With(checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1173. Get(webChangeClientPwdPath, handleWebClientChangePwd)
  1174. router.With(checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1175. Post(webChangeClientPwdPath, handleWebClientChangePwdPost)
  1176. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1177. Get(webClientMFAPath, handleWebClientMFA)
  1178. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1179. Post(webClientTOTPGeneratePath, generateTOTPSecret)
  1180. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1181. Post(webClientTOTPValidatePath, validateTOTPPasscode)
  1182. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1183. Post(webClientTOTPSavePath, saveTOTPConfig)
  1184. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
  1185. Get(webClientRecoveryCodesPath, getRecoveryCodes)
  1186. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1187. Post(webClientRecoveryCodesPath, generateRecoveryCodes)
  1188. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1189. Get(webClientSharesPath, handleClientGetShares)
  1190. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1191. Get(webClientSharePath, handleClientAddShareGet)
  1192. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Post(webClientSharePath,
  1193. handleClientAddSharePost)
  1194. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1195. Get(webClientSharePath+"/{id}", handleClientUpdateShareGet)
  1196. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1197. Post(webClientSharePath+"/{id}", handleClientUpdateSharePost)
  1198. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
  1199. Delete(webClientSharePath+"/{id}", deleteShare)
  1200. })
  1201. }
  1202. if s.enableWebAdmin {
  1203. s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
  1204. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1205. s.redirectToWebPath(w, r, webLoginPath)
  1206. })
  1207. s.router.Get(webLoginPath, s.handleWebAdminLogin)
  1208. s.router.Post(webLoginPath, s.handleWebAdminLoginPost)
  1209. s.router.Get(webAdminSetupPath, handleWebAdminSetupGet)
  1210. s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
  1211. s.router.Get(webAdminForgotPwdPath, handleWebAdminForgotPwd)
  1212. s.router.Post(webAdminForgotPwdPath, handleWebAdminForgotPwdPost)
  1213. s.router.Get(webAdminResetPwdPath, handleWebAdminPasswordReset)
  1214. s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
  1215. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1216. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1217. Get(webAdminTwoFactorPath, handleWebAdminTwoFactor)
  1218. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1219. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1220. Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
  1221. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1222. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1223. Get(webAdminTwoFactorRecoveryPath, handleWebAdminTwoFactorRecovery)
  1224. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1225. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1226. Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
  1227. s.router.Group(func(router chi.Router) {
  1228. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie))
  1229. router.Use(jwtAuthenticatorWebAdmin)
  1230. router.Get(webLogoutPath, handleWebLogout)
  1231. router.With(s.refreshCookie).Get(webAdminProfilePath, handleWebAdminProfile)
  1232. router.Post(webAdminProfilePath, handleWebAdminProfilePost)
  1233. router.With(s.refreshCookie).Get(webChangeAdminPwdPath, handleWebAdminChangePwd)
  1234. router.Post(webChangeAdminPwdPath, handleWebAdminChangePwdPost)
  1235. router.With(s.refreshCookie).Get(webAdminMFAPath, handleWebAdminMFA)
  1236. router.With(verifyCSRFHeader).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
  1237. router.With(verifyCSRFHeader).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
  1238. router.With(verifyCSRFHeader).Post(webAdminTOTPSavePath, saveTOTPConfig)
  1239. router.With(verifyCSRFHeader, s.refreshCookie).Get(webAdminRecoveryCodesPath, getRecoveryCodes)
  1240. router.With(verifyCSRFHeader).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
  1241. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1242. Get(webUsersPath, handleGetWebUsers)
  1243. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1244. Get(webUserPath, handleWebAddUserGet)
  1245. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1246. Get(webUserPath+"/{username}", handleWebUpdateUserGet)
  1247. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, handleWebAddUserPost)
  1248. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}", handleWebUpdateUserPost)
  1249. router.With(checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1250. Get(webConnectionsPath, handleWebGetConnections)
  1251. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1252. Get(webFoldersPath, handleWebGetFolders)
  1253. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1254. Get(webFolderPath, handleWebAddFolderGet)
  1255. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webFolderPath, handleWebAddFolderPost)
  1256. router.With(checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  1257. Get(webStatusPath, handleWebGetStatus)
  1258. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1259. Get(webAdminsPath, handleGetWebAdmins)
  1260. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1261. Get(webAdminPath, handleWebAddAdminGet)
  1262. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1263. Get(webAdminPath+"/{username}", handleWebUpdateAdminGet)
  1264. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, handleWebAddAdminPost)
  1265. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}",
  1266. handleWebUpdateAdminPost)
  1267. router.With(checkPerm(dataprovider.PermAdminManageAdmins), verifyCSRFHeader).
  1268. Delete(webAdminPath+"/{username}", deleteAdmin)
  1269. router.With(checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  1270. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  1271. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1272. Get(webFolderPath+"/{name}", handleWebUpdateFolderGet)
  1273. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webFolderPath+"/{name}",
  1274. handleWebUpdateFolderPost)
  1275. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1276. Delete(webFolderPath+"/{name}", deleteFolder)
  1277. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1278. Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
  1279. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1280. Delete(webUserPath+"/{username}", deleteUser)
  1281. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1282. Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
  1283. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, handleWebMaintenance)
  1284. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
  1285. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, handleWebRestore)
  1286. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1287. Get(webTemplateUser, handleWebTemplateUserGet)
  1288. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, handleWebTemplateUserPost)
  1289. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1290. Get(webTemplateFolder, handleWebTemplateFolderGet)
  1291. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateFolder, handleWebTemplateFolderPost)
  1292. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, handleWebDefenderPage)
  1293. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
  1294. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(webDefenderHostsPath+"/{id}",
  1295. deleteDefenderHostByID)
  1296. })
  1297. }
  1298. }