server.go 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. installCode := r.Form.Get("install_code")
  573. if installationCode != "" && installCode != installationCode {
  574. renderAdminSetupPage(w, r, username, fmt.Sprintf("%v mismatch", installationCodeHint))
  575. return
  576. }
  577. if username == "" {
  578. renderAdminSetupPage(w, r, username, "Please set a username")
  579. return
  580. }
  581. if password == "" {
  582. renderAdminSetupPage(w, r, username, "Please set a password")
  583. return
  584. }
  585. if password != confirmPassword {
  586. renderAdminSetupPage(w, r, username, "Passwords mismatch")
  587. return
  588. }
  589. admin := dataprovider.Admin{
  590. Username: username,
  591. Password: password,
  592. Status: 1,
  593. Permissions: []string{dataprovider.PermAdminAny},
  594. }
  595. err = dataprovider.AddAdmin(&admin, username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  596. if err != nil {
  597. renderAdminSetupPage(w, r, username, err.Error())
  598. return
  599. }
  600. s.loginAdmin(w, r, &admin, false, nil)
  601. }
  602. func (s *httpdServer) loginUser(
  603. w http.ResponseWriter, r *http.Request, user *dataprovider.User, connectionID, ipAddr string,
  604. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, error string),
  605. ) {
  606. c := jwtTokenClaims{
  607. Username: user.Username,
  608. Permissions: user.Filters.WebClient,
  609. Signature: user.GetSignature(),
  610. }
  611. audience := tokenAudienceWebClient
  612. if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) &&
  613. user.CanManageMFA() && !isSecondFactorAuth {
  614. audience = tokenAudienceWebClientPartial
  615. }
  616. err := c.createAndSetCookie(w, r, s.tokenAuth, audience)
  617. if err != nil {
  618. logger.Warn(logSender, connectionID, "unable to set user login cookie %v", err)
  619. updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  620. errorFunc(w, err.Error())
  621. return
  622. }
  623. if isSecondFactorAuth {
  624. invalidateToken(r)
  625. }
  626. if audience == tokenAudienceWebClientPartial {
  627. http.Redirect(w, r, webClientTwoFactorPath, http.StatusFound)
  628. return
  629. }
  630. updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, err)
  631. dataprovider.UpdateLastLogin(user)
  632. http.Redirect(w, r, webClientFilesPath, http.StatusFound)
  633. }
  634. func (s *httpdServer) loginAdmin(
  635. w http.ResponseWriter, r *http.Request, admin *dataprovider.Admin,
  636. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, error string),
  637. ) {
  638. c := jwtTokenClaims{
  639. Username: admin.Username,
  640. Permissions: admin.Permissions,
  641. Signature: admin.GetSignature(),
  642. }
  643. audience := tokenAudienceWebAdmin
  644. if admin.Filters.TOTPConfig.Enabled && admin.CanManageMFA() && !isSecondFactorAuth {
  645. audience = tokenAudienceWebAdminPartial
  646. }
  647. err := c.createAndSetCookie(w, r, s.tokenAuth, audience)
  648. if err != nil {
  649. logger.Warn(logSender, "", "unable to set admin login cookie %v", err)
  650. if errorFunc == nil {
  651. renderAdminSetupPage(w, r, admin.Username, err.Error())
  652. return
  653. }
  654. errorFunc(w, err.Error())
  655. return
  656. }
  657. if isSecondFactorAuth {
  658. invalidateToken(r)
  659. }
  660. if audience == tokenAudienceWebAdminPartial {
  661. http.Redirect(w, r, webAdminTwoFactorPath, http.StatusFound)
  662. return
  663. }
  664. dataprovider.UpdateAdminLastLogin(admin)
  665. http.Redirect(w, r, webUsersPath, http.StatusFound)
  666. }
  667. func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
  668. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  669. invalidateToken(r)
  670. sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
  671. }
  672. func (s *httpdServer) getUserToken(w http.ResponseWriter, r *http.Request) {
  673. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  674. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  675. username, password, ok := r.BasicAuth()
  676. protocol := common.ProtocolHTTP
  677. if !ok {
  678. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  679. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  680. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  681. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  682. return
  683. }
  684. if username == "" || password == "" {
  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 err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
  692. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  693. return
  694. }
  695. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
  696. if err != nil {
  697. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  698. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  699. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  700. http.StatusUnauthorized)
  701. return
  702. }
  703. connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
  704. if err := checkHTTPClientUser(&user, r, connectionID); err != nil {
  705. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  706. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  707. return
  708. }
  709. if user.Filters.TOTPConfig.Enabled && util.IsStringInSlice(common.ProtocolHTTP, user.Filters.TOTPConfig.Protocols) {
  710. passcode := r.Header.Get(otpHeaderCode)
  711. if passcode == "" {
  712. logger.Debug(logSender, "", "TOTP enabled for user %#v and not passcode provided, authentication refused", user.Username)
  713. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  714. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  715. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  716. http.StatusUnauthorized)
  717. return
  718. }
  719. err = user.Filters.TOTPConfig.Secret.Decrypt()
  720. if err != nil {
  721. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  722. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err), http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  723. return
  724. }
  725. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  726. user.Filters.TOTPConfig.Secret.GetPayload())
  727. if !match || err != nil {
  728. logger.Debug(logSender, "invalid passcode for user %#v, match? %v, err: %v", user.Username, match, err)
  729. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  730. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  731. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  732. http.StatusUnauthorized)
  733. return
  734. }
  735. }
  736. defer user.CloseFs() //nolint:errcheck
  737. err = user.CheckFsRoot(connectionID)
  738. if err != nil {
  739. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  740. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  741. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  742. return
  743. }
  744. s.generateAndSendUserToken(w, r, ipAddr, user)
  745. }
  746. func (s *httpdServer) generateAndSendUserToken(w http.ResponseWriter, r *http.Request, ipAddr string, user dataprovider.User) {
  747. c := jwtTokenClaims{
  748. Username: user.Username,
  749. Permissions: user.Filters.WebClient,
  750. Signature: user.GetSignature(),
  751. }
  752. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPIUser)
  753. if err != nil {
  754. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  755. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  756. return
  757. }
  758. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  759. dataprovider.UpdateLastLogin(&user)
  760. render.JSON(w, r, resp)
  761. }
  762. func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
  763. username, password, ok := r.BasicAuth()
  764. if !ok {
  765. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  766. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  767. return
  768. }
  769. admin, err := dataprovider.CheckAdminAndPass(username, password, util.GetIPFromRemoteAddress(r.RemoteAddr))
  770. if err != nil {
  771. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  772. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  773. return
  774. }
  775. if admin.Filters.TOTPConfig.Enabled {
  776. passcode := r.Header.Get(otpHeaderCode)
  777. if passcode == "" {
  778. logger.Debug(logSender, "", "TOTP enabled for admin %#v and not passcode provided, authentication refused", admin.Username)
  779. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  780. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  781. return
  782. }
  783. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  784. if err != nil {
  785. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err),
  786. http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  787. return
  788. }
  789. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  790. admin.Filters.TOTPConfig.Secret.GetPayload())
  791. if !match || err != nil {
  792. logger.Debug(logSender, "invalid passcode for admin %#v, match? %v, err: %v", admin.Username, match, err)
  793. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  794. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  795. http.StatusUnauthorized)
  796. return
  797. }
  798. }
  799. s.generateAndSendToken(w, r, admin)
  800. }
  801. func (s *httpdServer) generateAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin) {
  802. c := jwtTokenClaims{
  803. Username: admin.Username,
  804. Permissions: admin.Permissions,
  805. Signature: admin.GetSignature(),
  806. }
  807. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI)
  808. if err != nil {
  809. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  810. return
  811. }
  812. dataprovider.UpdateAdminLastLogin(&admin)
  813. render.JSON(w, r, resp)
  814. }
  815. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  816. if _, ok := r.Context().Value(oidcTokenKey).(string); ok {
  817. return
  818. }
  819. token, claims, err := jwtauth.FromContext(r.Context())
  820. if err != nil {
  821. return
  822. }
  823. tokenClaims := jwtTokenClaims{}
  824. tokenClaims.Decode(claims)
  825. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  826. return
  827. }
  828. if time.Until(token.Expiration()) > tokenRefreshThreshold {
  829. return
  830. }
  831. if util.IsStringInSlice(tokenAudienceWebClient, token.Audience()) {
  832. s.refreshClientToken(w, r, tokenClaims)
  833. } else {
  834. s.refreshAdminToken(w, r, tokenClaims)
  835. }
  836. }
  837. func (s *httpdServer) refreshClientToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  838. user, err := dataprovider.UserExists(tokenClaims.Username)
  839. if err != nil {
  840. return
  841. }
  842. if user.GetSignature() != tokenClaims.Signature {
  843. logger.Debug(logSender, "", "signature mismatch for user %#v, unable to refresh cookie", user.Username)
  844. return
  845. }
  846. if err := checkHTTPClientUser(&user, r, xid.New().String()); err != nil {
  847. logger.Debug(logSender, "", "unable to refresh cookie for user %#v: %v", user.Username, err)
  848. return
  849. }
  850. tokenClaims.Permissions = user.Filters.WebClient
  851. logger.Debug(logSender, "", "cookie refreshed for user %#v", user.Username)
  852. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebClient) //nolint:errcheck
  853. }
  854. func (s *httpdServer) refreshAdminToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  855. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  856. if err != nil {
  857. return
  858. }
  859. if admin.Status != 1 {
  860. logger.Debug(logSender, "", "admin %#v is disabled, unable to refresh cookie", admin.Username)
  861. return
  862. }
  863. if admin.GetSignature() != tokenClaims.Signature {
  864. logger.Debug(logSender, "", "signature mismatch for admin %#v, unable to refresh cookie", admin.Username)
  865. return
  866. }
  867. if !admin.CanLoginFromIP(util.GetIPFromRemoteAddress(r.RemoteAddr)) {
  868. logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie", admin.Username, r.RemoteAddr)
  869. return
  870. }
  871. tokenClaims.Permissions = admin.Permissions
  872. logger.Debug(logSender, "", "cookie refreshed for admin %#v", admin.Username)
  873. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebAdmin) //nolint:errcheck
  874. }
  875. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  876. token, _, err := jwtauth.FromContext(r.Context())
  877. if token == nil || err != nil {
  878. _, err = r.Cookie(jwtCookieKey)
  879. if err != nil {
  880. return r
  881. }
  882. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  883. ctx := jwtauth.NewContext(r.Context(), token, err)
  884. return r.WithContext(ctx)
  885. }
  886. return r
  887. }
  888. func (s *httpdServer) checkConnection(next http.Handler) http.Handler {
  889. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  890. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  891. ip := net.ParseIP(ipAddr)
  892. areHeadersAllowed := false
  893. if ip != nil {
  894. for _, allow := range s.binding.allowHeadersFrom {
  895. if allow(ip) {
  896. parsedIP := util.GetRealIP(r)
  897. if parsedIP != "" {
  898. ipAddr = parsedIP
  899. r.RemoteAddr = ipAddr
  900. }
  901. if forwardedProto := r.Header.Get(xForwardedProto); forwardedProto != "" {
  902. ctx := context.WithValue(r.Context(), forwardedProtoKey, forwardedProto)
  903. r = r.WithContext(ctx)
  904. }
  905. areHeadersAllowed = true
  906. break
  907. }
  908. }
  909. }
  910. if !areHeadersAllowed {
  911. for idx := range s.binding.Security.proxyHeaders {
  912. r.Header.Del(s.binding.Security.proxyHeaders[idx])
  913. }
  914. }
  915. common.Connections.AddClientConnection(ipAddr)
  916. defer common.Connections.RemoveClientConnection(ipAddr)
  917. if !common.Connections.IsNewConnectionAllowed(ipAddr) {
  918. logger.Log(logger.LevelDebug, common.ProtocolHTTP, "", "connection refused, configured limit reached")
  919. s.sendForbiddenResponse(w, r, "configured connections limit reached")
  920. return
  921. }
  922. if common.IsBanned(ipAddr) {
  923. s.sendForbiddenResponse(w, r, "your IP address is banned")
  924. return
  925. }
  926. if delay, err := common.LimitRate(common.ProtocolHTTP, ipAddr); err != nil {
  927. delay += 499999999 * time.Nanosecond
  928. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  929. w.Header().Set("X-Retry-In", delay.String())
  930. s.sendTooManyRequestResponse(w, r, err)
  931. return
  932. }
  933. next.ServeHTTP(w, r)
  934. })
  935. }
  936. func (s *httpdServer) sendTooManyRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
  937. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  938. r = s.updateContextFromCookie(r)
  939. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  940. renderClientMessagePage(w, r, http.StatusText(http.StatusTooManyRequests), "Rate limit exceeded",
  941. http.StatusTooManyRequests, err, "")
  942. return
  943. }
  944. renderMessagePage(w, r, http.StatusText(http.StatusTooManyRequests), "Rate limit exceeded", http.StatusTooManyRequests,
  945. err, "")
  946. return
  947. }
  948. sendAPIResponse(w, r, err, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
  949. }
  950. func (s *httpdServer) sendForbiddenResponse(w http.ResponseWriter, r *http.Request, message string) {
  951. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  952. r = s.updateContextFromCookie(r)
  953. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  954. renderClientForbiddenPage(w, r, message)
  955. return
  956. }
  957. renderForbiddenPage(w, r, message)
  958. return
  959. }
  960. sendAPIResponse(w, r, errors.New(message), message, http.StatusForbidden)
  961. }
  962. func (s *httpdServer) badHostHandler(w http.ResponseWriter, r *http.Request) {
  963. host := r.Host
  964. for _, header := range s.binding.Security.HostsProxyHeaders {
  965. if h := r.Header.Get(header); h != "" {
  966. host = h
  967. break
  968. }
  969. }
  970. s.sendForbiddenResponse(w, r, fmt.Sprintf("The host %#v is not allowed", host))
  971. }
  972. func (s *httpdServer) redirectToWebPath(w http.ResponseWriter, r *http.Request, webPath string) {
  973. if dataprovider.HasAdmin() {
  974. http.Redirect(w, r, webPath, http.StatusFound)
  975. return
  976. }
  977. if s.enableWebAdmin {
  978. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  979. }
  980. }
  981. func (s *httpdServer) isStaticFileURL(r *http.Request) bool {
  982. var urlPath string
  983. rctx := chi.RouteContext(r.Context())
  984. if rctx != nil && rctx.RoutePath != "" {
  985. urlPath = rctx.RoutePath
  986. } else {
  987. urlPath = r.URL.Path
  988. }
  989. return !strings.HasPrefix(urlPath, webOpenAPIPath) && !strings.HasPrefix(urlPath, webStaticFilesPath)
  990. }
  991. func (s *httpdServer) initializeRouter() {
  992. s.tokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(s.signingPassphrase), nil)
  993. s.router = chi.NewRouter()
  994. s.router.Use(middleware.RequestID)
  995. s.router.Use(s.checkConnection)
  996. s.router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  997. s.router.Use(middleware.Recoverer)
  998. if s.binding.Security.Enabled {
  999. secureMiddleware := secure.New(secure.Options{
  1000. AllowedHosts: s.binding.Security.AllowedHosts,
  1001. AllowedHostsAreRegex: s.binding.Security.AllowedHostsAreRegex,
  1002. HostsProxyHeaders: s.binding.Security.HostsProxyHeaders,
  1003. SSLProxyHeaders: s.binding.Security.getHTTPSProxyHeaders(),
  1004. STSSeconds: s.binding.Security.STSSeconds,
  1005. STSIncludeSubdomains: s.binding.Security.STSIncludeSubdomains,
  1006. STSPreload: s.binding.Security.STSPreload,
  1007. ContentTypeNosniff: s.binding.Security.ContentTypeNosniff,
  1008. ContentSecurityPolicy: s.binding.Security.ContentSecurityPolicy,
  1009. PermissionsPolicy: s.binding.Security.PermissionsPolicy,
  1010. CrossOriginOpenerPolicy: s.binding.Security.CrossOriginOpenerPolicy,
  1011. ExpectCTHeader: s.binding.Security.ExpectCTHeader,
  1012. })
  1013. secureMiddleware.SetBadHostHandler(http.HandlerFunc(s.badHostHandler))
  1014. s.router.Use(secureMiddleware.Handler)
  1015. }
  1016. if s.cors.Enabled {
  1017. c := cors.New(cors.Options{
  1018. AllowedOrigins: s.cors.AllowedOrigins,
  1019. AllowedMethods: s.cors.AllowedMethods,
  1020. AllowedHeaders: s.cors.AllowedHeaders,
  1021. ExposedHeaders: s.cors.ExposedHeaders,
  1022. MaxAge: s.cors.MaxAge,
  1023. AllowCredentials: s.cors.AllowCredentials,
  1024. })
  1025. s.router.Use(c.Handler)
  1026. }
  1027. s.router.Use(middleware.GetHead)
  1028. // StripSlashes causes infinite redirects at the root path if used with http.FileServer
  1029. s.router.Use(middleware.Maybe(middleware.StripSlashes, s.isStaticFileURL))
  1030. s.router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1031. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1032. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1033. r = s.updateContextFromCookie(r)
  1034. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1035. renderClientNotFoundPage(w, r, nil)
  1036. return
  1037. }
  1038. renderNotFoundPage(w, r, nil)
  1039. return
  1040. }
  1041. sendAPIResponse(w, r, nil, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  1042. }))
  1043. s.router.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  1044. render.PlainText(w, r, "ok")
  1045. })
  1046. // share API exposed to external users
  1047. s.router.Get(sharesPath+"/{id}", downloadFromShare)
  1048. s.router.Post(sharesPath+"/{id}", uploadFilesToShare)
  1049. s.router.Post(sharesPath+"/{id}/{name}", uploadFileToShare)
  1050. s.router.With(compressor.Handler).Get(sharesPath+"/{id}/dirs", readBrowsableShareContents)
  1051. s.router.Get(sharesPath+"/{id}/files", downloadBrowsableSharedFile)
  1052. s.router.Get(tokenPath, s.getToken)
  1053. s.router.Post(adminPath+"/{username}/forgot-password", forgotAdminPassword)
  1054. s.router.Post(adminPath+"/{username}/reset-password", resetAdminPassword)
  1055. s.router.Post(userPath+"/{username}/forgot-password", forgotUserPassword)
  1056. s.router.Post(userPath+"/{username}/reset-password", resetUserPassword)
  1057. s.router.Group(func(router chi.Router) {
  1058. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeAdmin))
  1059. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1060. router.Use(jwtAuthenticatorAPI)
  1061. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  1062. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1063. render.JSON(w, r, version.Get())
  1064. })
  1065. router.With(forbidAPIKeyAuthentication).Get(logoutPath, s.logout)
  1066. router.With(forbidAPIKeyAuthentication).Get(adminProfilePath, getAdminProfile)
  1067. router.With(forbidAPIKeyAuthentication).Put(adminProfilePath, updateAdminProfile)
  1068. router.With(forbidAPIKeyAuthentication).Put(adminPwdPath, changeAdminPassword)
  1069. // compatibility layer to remove in v2.2
  1070. router.With(forbidAPIKeyAuthentication).Put(adminPwdCompatPath, changeAdminPassword)
  1071. // admin TOTP APIs
  1072. router.With(forbidAPIKeyAuthentication).Get(adminTOTPConfigsPath, getTOTPConfigs)
  1073. router.With(forbidAPIKeyAuthentication).Post(adminTOTPGeneratePath, generateTOTPSecret)
  1074. router.With(forbidAPIKeyAuthentication).Post(adminTOTPValidatePath, validateTOTPPasscode)
  1075. router.With(forbidAPIKeyAuthentication).Post(adminTOTPSavePath, saveTOTPConfig)
  1076. router.With(forbidAPIKeyAuthentication).Get(admin2FARecoveryCodesPath, getRecoveryCodes)
  1077. router.With(forbidAPIKeyAuthentication).Post(admin2FARecoveryCodesPath, generateRecoveryCodes)
  1078. router.With(checkPerm(dataprovider.PermAdminViewServerStatus)).
  1079. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  1080. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1081. render.JSON(w, r, getServicesStatus())
  1082. })
  1083. router.With(checkPerm(dataprovider.PermAdminViewConnections)).
  1084. Get(activeConnectionsPath, func(w http.ResponseWriter, r *http.Request) {
  1085. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1086. render.JSON(w, r, common.Connections.GetStats())
  1087. })
  1088. router.With(checkPerm(dataprovider.PermAdminCloseConnections)).
  1089. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  1090. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanPath, getUsersQuotaScans)
  1091. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/users/scans", getUsersQuotaScans)
  1092. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanPath, startUserQuotaScanCompat)
  1093. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/users/{username}/scan", startUserQuotaScan)
  1094. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanVFolderPath, getFoldersQuotaScans)
  1095. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/folders/scans", getFoldersQuotaScans)
  1096. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanVFolderPath, startFolderQuotaScanCompat)
  1097. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/folders/{name}/scan", startFolderQuotaScan)
  1098. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  1099. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  1100. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername)
  1101. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  1102. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  1103. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}/2fa/disable", disableUser2FA)
  1104. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath, getFolders)
  1105. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath+"/{name}", getFolderByName)
  1106. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(folderPath, addFolder)
  1107. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(folderPath+"/{name}", updateFolder)
  1108. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(folderPath+"/{name}", deleteFolder)
  1109. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(dumpDataPath, dumpData)
  1110. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(loadDataPath, loadData)
  1111. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(loadDataPath, loadDataFromRequest)
  1112. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateUsedQuotaPath, updateUserQuotaUsageCompat)
  1113. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/usage",
  1114. updateUserQuotaUsage)
  1115. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/transfer-usage",
  1116. updateUserTransferQuotaUsage)
  1117. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateFolderUsedQuotaPath, updateFolderQuotaUsageCompat)
  1118. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage",
  1119. updateFolderQuotaUsage)
  1120. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
  1121. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
  1122. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
  1123. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderBanTime, getBanTime)
  1124. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderScore, getScore)
  1125. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Post(defenderUnban, unban)
  1126. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
  1127. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
  1128. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
  1129. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
  1130. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
  1131. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1132. router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Get(retentionChecksPath, getRetentionChecks)
  1133. router.With(checkPerm(dataprovider.PermAdminRetentionChecks)).Post(retentionBasePath+"/{username}/check",
  1134. startRetentionCheck)
  1135. router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Get(metadataChecksPath, getMetadataChecks)
  1136. router.With(checkPerm(dataprovider.PermAdminMetadataChecks)).Post(metadataBasePath+"/{username}/check",
  1137. startMetadataCheck)
  1138. router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1139. Get(fsEventsPath, searchFsEvents)
  1140. router.With(checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1141. Get(providerEventsPath, searchProviderEvents)
  1142. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1143. Get(apiKeysPath, getAPIKeys)
  1144. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1145. Post(apiKeysPath, addAPIKey)
  1146. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1147. Get(apiKeysPath+"/{id}", getAPIKeyByID)
  1148. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1149. Put(apiKeysPath+"/{id}", updateAPIKey)
  1150. router.With(forbidAPIKeyAuthentication, checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1151. Delete(apiKeysPath+"/{id}", deleteAPIKey)
  1152. })
  1153. s.router.Get(userTokenPath, s.getUserToken)
  1154. s.router.Group(func(router chi.Router) {
  1155. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
  1156. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1157. router.Use(jwtAuthenticatorAPIUser)
  1158. router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
  1159. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1160. Put(userPwdPath, changeUserPassword)
  1161. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).
  1162. Get(userPublicKeysPath, getUserPublicKeys)
  1163. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientPubKeyChangeDisabled)).
  1164. Put(userPublicKeysPath, setUserPublicKeys)
  1165. router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
  1166. router.With(forbidAPIKeyAuthentication).Put(userProfilePath, updateUserProfile)
  1167. // user TOTP APIs
  1168. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1169. Get(userTOTPConfigsPath, getTOTPConfigs)
  1170. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1171. Post(userTOTPGeneratePath, generateTOTPSecret)
  1172. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1173. Post(userTOTPValidatePath, validateTOTPPasscode)
  1174. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1175. Post(userTOTPSavePath, saveTOTPConfig)
  1176. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1177. Get(user2FARecoveryCodesPath, getRecoveryCodes)
  1178. router.With(forbidAPIKeyAuthentication, checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1179. Post(user2FARecoveryCodesPath, generateRecoveryCodes)
  1180. // compatibility layer to remove in v2.3
  1181. router.With(compressor.Handler).Get(userFolderPath, readUserFolder)
  1182. router.Get(userFilePath, getUserFile)
  1183. router.With(compressor.Handler).Get(userDirsPath, readUserFolder)
  1184. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userDirsPath, createUserDir)
  1185. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userDirsPath, renameUserDir)
  1186. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Delete(userDirsPath, deleteUserDir)
  1187. router.Get(userFilesPath, getUserFile)
  1188. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userFilesPath, uploadUserFiles)
  1189. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userFilesPath, renameUserFile)
  1190. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Delete(userFilesPath, deleteUserFile)
  1191. router.Post(userStreamZipPath, getUserFilesAsZipStream)
  1192. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Get(userSharesPath, getShares)
  1193. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Post(userSharesPath, addShare)
  1194. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Get(userSharesPath+"/{id}", getShareByID)
  1195. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Put(userSharesPath+"/{id}", updateShare)
  1196. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Delete(userSharesPath+"/{id}", deleteShare)
  1197. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Post(userUploadFilePath, uploadUserFile)
  1198. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled)).Patch(userFilesDirsMetadataPath, setFileDirMetadata)
  1199. })
  1200. if s.renderOpenAPI {
  1201. s.router.Group(func(router chi.Router) {
  1202. router.Use(compressor.Handler)
  1203. fileServer(router, webOpenAPIPath, http.Dir(s.openAPIPath))
  1204. })
  1205. }
  1206. if s.enableWebAdmin || s.enableWebClient {
  1207. s.router.Group(func(router chi.Router) {
  1208. router.Use(compressor.Handler)
  1209. fileServer(router, webStaticFilesPath, http.Dir(s.staticFilesPath))
  1210. })
  1211. if s.binding.OIDC.isEnabled() {
  1212. s.router.Get(webOIDCRedirectPath, s.handleOIDCRedirect)
  1213. }
  1214. if s.enableWebClient {
  1215. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1216. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1217. s.redirectToWebPath(w, r, webClientLoginPath)
  1218. })
  1219. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1220. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1221. s.redirectToWebPath(w, r, webClientLoginPath)
  1222. })
  1223. } else {
  1224. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1225. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1226. s.redirectToWebPath(w, r, webAdminLoginPath)
  1227. })
  1228. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1229. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1230. s.redirectToWebPath(w, r, webAdminLoginPath)
  1231. })
  1232. }
  1233. }
  1234. s.setupWebClientRoutes()
  1235. s.setupWebAdminRoutes()
  1236. }
  1237. func (s *httpdServer) setupWebClientRoutes() {
  1238. if s.enableWebClient {
  1239. s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
  1240. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1241. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  1242. })
  1243. s.router.Get(webClientLoginPath, s.handleClientWebLogin)
  1244. if s.binding.OIDC.isEnabled() {
  1245. s.router.Get(webClientOIDCLoginPath, s.handleWebClientOIDCLogin)
  1246. }
  1247. s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
  1248. s.router.Get(webClientForgotPwdPath, handleWebClientForgotPwd)
  1249. s.router.Post(webClientForgotPwdPath, handleWebClientForgotPwdPost)
  1250. s.router.Get(webClientResetPwdPath, handleWebClientPasswordReset)
  1251. s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
  1252. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1253. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1254. Get(webClientTwoFactorPath, handleWebClientTwoFactor)
  1255. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1256. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1257. Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
  1258. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1259. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1260. Get(webClientTwoFactorRecoveryPath, handleWebClientTwoFactorRecovery)
  1261. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1262. jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1263. Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
  1264. // share API exposed to external users
  1265. s.router.Get(webClientPubSharesPath+"/{id}", downloadFromShare)
  1266. s.router.Get(webClientPubSharesPath+"/{id}/browse", handleShareGetFiles)
  1267. s.router.Get(webClientPubSharesPath+"/{id}/upload", handleClientUploadToShare)
  1268. s.router.With(compressor.Handler).Get(webClientPubSharesPath+"/{id}/dirs", handleShareGetDirContents)
  1269. s.router.Post(webClientPubSharesPath+"/{id}", uploadFilesToShare)
  1270. s.router.Post(webClientPubSharesPath+"/{id}/{name}", uploadFileToShare)
  1271. s.router.Group(func(router chi.Router) {
  1272. if s.binding.OIDC.isEnabled() {
  1273. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebClient))
  1274. }
  1275. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1276. router.Use(jwtAuthenticatorWebClient)
  1277. router.Get(webClientLogoutPath, s.handleWebClientLogout)
  1278. router.With(s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
  1279. router.With(s.refreshCookie).Get(webClientViewPDFPath, handleClientViewPDF)
  1280. router.With(s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
  1281. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1282. Post(webClientFilePath, uploadUserFile)
  1283. router.With(s.refreshCookie).Get(webClientEditFilePath, handleClientEditFile)
  1284. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1285. Patch(webClientFilesPath, renameUserFile)
  1286. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1287. Delete(webClientFilesPath, deleteUserFile)
  1288. router.With(compressor.Handler, s.refreshCookie).Get(webClientDirsPath, s.handleClientGetDirContents)
  1289. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1290. Post(webClientDirsPath, createUserDir)
  1291. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1292. Patch(webClientDirsPath, renameUserDir)
  1293. router.With(checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1294. Delete(webClientDirsPath, deleteUserDir)
  1295. router.With(s.refreshCookie).Get(webClientDownloadZipPath, handleWebClientDownloadZip)
  1296. router.With(s.refreshCookie, requireBuiltinLogin).Get(webClientProfilePath, handleClientGetProfile)
  1297. router.With(requireBuiltinLogin).Post(webClientProfilePath, handleWebClientProfilePost)
  1298. router.With(checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1299. Get(webChangeClientPwdPath, handleWebClientChangePwd)
  1300. router.With(checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1301. Post(webChangeClientPwdPath, s.handleWebClientChangePwdPost)
  1302. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1303. Get(webClientMFAPath, handleWebClientMFA)
  1304. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1305. Post(webClientTOTPGeneratePath, generateTOTPSecret)
  1306. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1307. Post(webClientTOTPValidatePath, validateTOTPPasscode)
  1308. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1309. Post(webClientTOTPSavePath, saveTOTPConfig)
  1310. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
  1311. Get(webClientRecoveryCodesPath, getRecoveryCodes)
  1312. router.With(checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1313. Post(webClientRecoveryCodesPath, generateRecoveryCodes)
  1314. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1315. Get(webClientSharesPath, handleClientGetShares)
  1316. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1317. Get(webClientSharePath, handleClientAddShareGet)
  1318. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).Post(webClientSharePath,
  1319. handleClientAddSharePost)
  1320. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1321. Get(webClientSharePath+"/{id}", handleClientUpdateShareGet)
  1322. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1323. Post(webClientSharePath+"/{id}", handleClientUpdateSharePost)
  1324. router.With(checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
  1325. Delete(webClientSharePath+"/{id}", deleteShare)
  1326. })
  1327. }
  1328. }
  1329. func (s *httpdServer) setupWebAdminRoutes() {
  1330. if s.enableWebAdmin {
  1331. s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
  1332. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1333. s.redirectToWebPath(w, r, webAdminLoginPath)
  1334. })
  1335. s.router.Get(webAdminLoginPath, s.handleWebAdminLogin)
  1336. if s.binding.OIDC.hasRoles() {
  1337. s.router.Get(webAdminOIDCLoginPath, s.handleWebAdminOIDCLogin)
  1338. }
  1339. s.router.Post(webAdminLoginPath, s.handleWebAdminLoginPost)
  1340. s.router.Get(webAdminSetupPath, handleWebAdminSetupGet)
  1341. s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
  1342. s.router.Get(webAdminForgotPwdPath, handleWebAdminForgotPwd)
  1343. s.router.Post(webAdminForgotPwdPath, handleWebAdminForgotPwdPost)
  1344. s.router.Get(webAdminResetPwdPath, handleWebAdminPasswordReset)
  1345. s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
  1346. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1347. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1348. Get(webAdminTwoFactorPath, handleWebAdminTwoFactor)
  1349. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1350. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1351. Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
  1352. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1353. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1354. Get(webAdminTwoFactorRecoveryPath, handleWebAdminTwoFactorRecovery)
  1355. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1356. jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1357. Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
  1358. s.router.Group(func(router chi.Router) {
  1359. if s.binding.OIDC.isEnabled() {
  1360. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebAdmin))
  1361. }
  1362. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1363. router.Use(jwtAuthenticatorWebAdmin)
  1364. router.Get(webLogoutPath, s.handleWebAdminLogout)
  1365. router.With(s.refreshCookie, requireBuiltinLogin).Get(webAdminProfilePath, handleWebAdminProfile)
  1366. router.With(requireBuiltinLogin).Post(webAdminProfilePath, handleWebAdminProfilePost)
  1367. router.With(s.refreshCookie, requireBuiltinLogin).Get(webChangeAdminPwdPath, handleWebAdminChangePwd)
  1368. router.With(requireBuiltinLogin).Post(webChangeAdminPwdPath, s.handleWebAdminChangePwdPost)
  1369. router.With(s.refreshCookie, requireBuiltinLogin).Get(webAdminMFAPath, handleWebAdminMFA)
  1370. router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
  1371. router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
  1372. router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminTOTPSavePath, saveTOTPConfig)
  1373. router.With(verifyCSRFHeader, requireBuiltinLogin, s.refreshCookie).Get(webAdminRecoveryCodesPath, getRecoveryCodes)
  1374. router.With(verifyCSRFHeader, requireBuiltinLogin).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
  1375. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1376. Get(webUsersPath, handleGetWebUsers)
  1377. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1378. Get(webUserPath, handleWebAddUserGet)
  1379. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1380. Get(webUserPath+"/{username}", handleWebUpdateUserGet)
  1381. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, handleWebAddUserPost)
  1382. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}", handleWebUpdateUserPost)
  1383. router.With(checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1384. Get(webConnectionsPath, handleWebGetConnections)
  1385. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1386. Get(webFoldersPath, handleWebGetFolders)
  1387. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1388. Get(webFolderPath, handleWebAddFolderGet)
  1389. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webFolderPath, handleWebAddFolderPost)
  1390. router.With(checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  1391. Get(webStatusPath, handleWebGetStatus)
  1392. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1393. Get(webAdminsPath, handleGetWebAdmins)
  1394. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1395. Get(webAdminPath, handleWebAddAdminGet)
  1396. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1397. Get(webAdminPath+"/{username}", handleWebUpdateAdminGet)
  1398. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, handleWebAddAdminPost)
  1399. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}",
  1400. handleWebUpdateAdminPost)
  1401. router.With(checkPerm(dataprovider.PermAdminManageAdmins), verifyCSRFHeader).
  1402. Delete(webAdminPath+"/{username}", deleteAdmin)
  1403. router.With(checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  1404. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  1405. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1406. Get(webFolderPath+"/{name}", handleWebUpdateFolderGet)
  1407. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webFolderPath+"/{name}",
  1408. handleWebUpdateFolderPost)
  1409. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1410. Delete(webFolderPath+"/{name}", deleteFolder)
  1411. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1412. Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
  1413. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1414. Delete(webUserPath+"/{username}", deleteUser)
  1415. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1416. Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
  1417. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, handleWebMaintenance)
  1418. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
  1419. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, handleWebRestore)
  1420. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1421. Get(webTemplateUser, handleWebTemplateUserGet)
  1422. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, handleWebTemplateUserPost)
  1423. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1424. Get(webTemplateFolder, handleWebTemplateFolderGet)
  1425. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateFolder, handleWebTemplateFolderPost)
  1426. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, handleWebDefenderPage)
  1427. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
  1428. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Delete(webDefenderHostsPath+"/{id}",
  1429. deleteDefenderHostByID)
  1430. })
  1431. }
  1432. }