server.go 66 KB

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