server.go 66 KB

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