server.go 63 KB

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