server.go 65 KB

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