server.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "errors"
  20. "fmt"
  21. "log"
  22. "net"
  23. "net/http"
  24. "net/url"
  25. "path/filepath"
  26. "strings"
  27. "time"
  28. "github.com/go-chi/chi/v5"
  29. "github.com/go-chi/chi/v5/middleware"
  30. "github.com/go-chi/jwtauth/v5"
  31. "github.com/go-chi/render"
  32. "github.com/lestrrat-go/jwx/v2/jwa"
  33. "github.com/rs/cors"
  34. "github.com/rs/xid"
  35. "github.com/sftpgo/sdk"
  36. "github.com/unrolled/secure"
  37. "github.com/drakkan/sftpgo/v2/internal/acme"
  38. "github.com/drakkan/sftpgo/v2/internal/common"
  39. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  40. "github.com/drakkan/sftpgo/v2/internal/logger"
  41. "github.com/drakkan/sftpgo/v2/internal/mfa"
  42. "github.com/drakkan/sftpgo/v2/internal/smtp"
  43. "github.com/drakkan/sftpgo/v2/internal/util"
  44. "github.com/drakkan/sftpgo/v2/internal/version"
  45. )
  46. const (
  47. jsonAPISuffix = "/json"
  48. )
  49. var (
  50. compressor = middleware.NewCompressor(5)
  51. xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto")
  52. )
  53. type httpdServer struct {
  54. binding Binding
  55. staticFilesPath string
  56. openAPIPath string
  57. enableWebAdmin bool
  58. enableWebClient bool
  59. enableRESTAPI bool
  60. renderOpenAPI bool
  61. isShared int
  62. router *chi.Mux
  63. tokenAuth *jwtauth.JWTAuth
  64. signingPassphrase string
  65. cors CorsConfig
  66. }
  67. func newHttpdServer(b Binding, staticFilesPath, signingPassphrase string, cors CorsConfig,
  68. openAPIPath string,
  69. ) *httpdServer {
  70. if openAPIPath == "" {
  71. b.RenderOpenAPI = false
  72. }
  73. return &httpdServer{
  74. binding: b,
  75. staticFilesPath: staticFilesPath,
  76. openAPIPath: openAPIPath,
  77. enableWebAdmin: b.EnableWebAdmin,
  78. enableWebClient: b.EnableWebClient,
  79. enableRESTAPI: b.EnableRESTAPI,
  80. renderOpenAPI: b.RenderOpenAPI,
  81. signingPassphrase: signingPassphrase,
  82. cors: cors,
  83. }
  84. }
  85. func (s *httpdServer) setShared(value int) {
  86. s.isShared = value
  87. }
  88. func (s *httpdServer) listenAndServe() error {
  89. s.initializeRouter()
  90. httpServer := &http.Server{
  91. Handler: s.router,
  92. ReadHeaderTimeout: 30 * time.Second,
  93. ReadTimeout: 60 * time.Second,
  94. WriteTimeout: 60 * time.Second,
  95. IdleTimeout: 60 * time.Second,
  96. MaxHeaderBytes: 1 << 16, // 64KB
  97. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  98. }
  99. if certMgr != nil && s.binding.EnableHTTPS {
  100. certID := common.DefaultTLSKeyPaidID
  101. if getConfigPath(s.binding.CertificateFile, "") != "" && getConfigPath(s.binding.CertificateKeyFile, "") != "" {
  102. certID = s.binding.GetAddress()
  103. }
  104. config := &tls.Config{
  105. GetCertificate: certMgr.GetCertificateFunc(certID),
  106. MinVersion: util.GetTLSVersion(s.binding.MinTLSVersion),
  107. NextProtos: util.GetALPNProtocols(s.binding.Protocols),
  108. CipherSuites: util.GetTLSCiphersFromNames(s.binding.TLSCipherSuites),
  109. }
  110. httpServer.TLSConfig = config
  111. logger.Debug(logSender, "", "configured TLS cipher suites for binding %q: %v, certID: %v",
  112. s.binding.GetAddress(), httpServer.TLSConfig.CipherSuites, certID)
  113. if s.binding.ClientAuthType == 1 {
  114. httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
  115. httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
  116. httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
  117. }
  118. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, true, logSender)
  119. }
  120. return util.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, false, logSender)
  121. }
  122. func (s *httpdServer) verifyTLSConnection(state tls.ConnectionState) error {
  123. if certMgr != nil {
  124. var clientCrt *x509.Certificate
  125. var clientCrtName string
  126. if len(state.PeerCertificates) > 0 {
  127. clientCrt = state.PeerCertificates[0]
  128. clientCrtName = clientCrt.Subject.String()
  129. }
  130. if len(state.VerifiedChains) == 0 {
  131. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  132. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  133. }
  134. for _, verifiedChain := range state.VerifiedChains {
  135. var caCrt *x509.Certificate
  136. if len(verifiedChain) > 0 {
  137. caCrt = verifiedChain[len(verifiedChain)-1]
  138. }
  139. if certMgr.IsRevoked(clientCrt, caCrt) {
  140. logger.Debug(logSender, "", "tls handshake error, client certificate %q has been revoked", clientCrtName)
  141. return common.ErrCrtRevoked
  142. }
  143. }
  144. }
  145. return nil
  146. }
  147. func (s *httpdServer) refreshCookie(next http.Handler) http.Handler {
  148. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  149. s.checkCookieExpiration(w, r)
  150. next.ServeHTTP(w, r)
  151. })
  152. }
  153. func (s *httpdServer) renderClientLoginPage(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string) {
  154. data := loginPage{
  155. commonBasePage: getCommonBasePage(r),
  156. Title: util.I18nLoginTitle,
  157. CurrentURL: webClientLoginPath,
  158. Error: err,
  159. CSRFToken: createCSRFToken(ip),
  160. Branding: s.binding.Branding.WebClient,
  161. FormDisabled: s.binding.isWebClientLoginFormDisabled(),
  162. }
  163. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  164. data.CurrentURL += "?next=" + url.QueryEscape(next)
  165. }
  166. if s.binding.showAdminLoginURL() {
  167. data.AltLoginURL = webAdminLoginPath
  168. data.AltLoginName = s.binding.Branding.WebAdmin.ShortName
  169. }
  170. if smtp.IsEnabled() && !data.FormDisabled {
  171. data.ForgotPwdURL = webClientForgotPwdPath
  172. }
  173. if s.binding.OIDC.isEnabled() && !s.binding.isWebClientOIDCLoginDisabled() {
  174. data.OpenIDLoginURL = webClientOIDCLoginPath
  175. }
  176. renderClientTemplate(w, templateCommonLogin, data)
  177. }
  178. func (s *httpdServer) handleWebClientLogout(w http.ResponseWriter, r *http.Request) {
  179. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  180. c := jwtTokenClaims{}
  181. c.removeCookie(w, r, webBaseClientPath)
  182. s.logoutOIDCUser(w, r)
  183. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  184. }
  185. func (s *httpdServer) handleWebClientChangePwdPost(w http.ResponseWriter, r *http.Request) {
  186. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  187. if err := r.ParseForm(); err != nil {
  188. s.renderClientChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  189. return
  190. }
  191. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  192. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  193. return
  194. }
  195. err := doChangeUserPassword(r, strings.TrimSpace(r.Form.Get("current_password")),
  196. strings.TrimSpace(r.Form.Get("new_password1")), strings.TrimSpace(r.Form.Get("new_password2")))
  197. if err != nil {
  198. s.renderClientChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric))
  199. return
  200. }
  201. s.handleWebClientLogout(w, r)
  202. }
  203. func (s *httpdServer) handleClientWebLogin(w http.ResponseWriter, r *http.Request) {
  204. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  205. if !dataprovider.HasAdmin() {
  206. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  207. return
  208. }
  209. msg := getFlashMessage(w, r)
  210. s.renderClientLoginPage(w, r, msg.getI18nError(), util.GetIPFromRemoteAddress(r.RemoteAddr))
  211. }
  212. func (s *httpdServer) handleWebClientLoginPost(w http.ResponseWriter, r *http.Request) {
  213. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  214. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  215. if err := r.ParseForm(); err != nil {
  216. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  217. return
  218. }
  219. protocol := common.ProtocolHTTP
  220. username := strings.TrimSpace(r.Form.Get("username"))
  221. password := strings.TrimSpace(r.Form.Get("password"))
  222. if username == "" || password == "" {
  223. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  224. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  225. s.renderClientLoginPage(w, r,
  226. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  227. return
  228. }
  229. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  230. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  231. dataprovider.LoginMethodPassword, ipAddr, err)
  232. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  233. return
  234. }
  235. if err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
  236. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  237. dataprovider.LoginMethodPassword, ipAddr, err)
  238. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nError403Message), ipAddr)
  239. return
  240. }
  241. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
  242. if err != nil {
  243. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  244. s.renderClientLoginPage(w, r,
  245. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  246. return
  247. }
  248. connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
  249. if err := checkHTTPClientUser(&user, r, connectionID, true); err != nil {
  250. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  251. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nError403Message), ipAddr)
  252. return
  253. }
  254. defer user.CloseFs() //nolint:errcheck
  255. err = user.CheckFsRoot(connectionID)
  256. if err != nil {
  257. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  258. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  259. s.renderClientLoginPage(w, r, util.NewI18nError(err, util.I18nErrorFsGeneric), ipAddr)
  260. return
  261. }
  262. s.loginUser(w, r, &user, connectionID, ipAddr, false, s.renderClientLoginPage)
  263. }
  264. func (s *httpdServer) handleWebClientPasswordResetPost(w http.ResponseWriter, r *http.Request) {
  265. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  266. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  267. err := r.ParseForm()
  268. if err != nil {
  269. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  270. return
  271. }
  272. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  273. s.renderClientForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  274. return
  275. }
  276. newPassword := strings.TrimSpace(r.Form.Get("password"))
  277. confirmPassword := strings.TrimSpace(r.Form.Get("confirm_password"))
  278. _, user, err := handleResetPassword(r, strings.TrimSpace(r.Form.Get("code")),
  279. newPassword, confirmPassword, false)
  280. if err != nil {
  281. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric), ipAddr)
  282. return
  283. }
  284. connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
  285. if err := checkHTTPClientUser(user, r, connectionID, true); err != nil {
  286. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorDirList403), ipAddr)
  287. return
  288. }
  289. defer user.CloseFs() //nolint:errcheck
  290. err = user.CheckFsRoot(connectionID)
  291. if err != nil {
  292. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  293. s.renderClientResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorLoginAfterReset), ipAddr)
  294. return
  295. }
  296. s.loginUser(w, r, user, connectionID, ipAddr, false, s.renderClientResetPwdPage)
  297. }
  298. func (s *httpdServer) handleWebClientTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
  299. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  300. claims, err := getTokenClaims(r)
  301. if err != nil {
  302. s.renderNotFoundPage(w, r, nil)
  303. return
  304. }
  305. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  306. if err := r.ParseForm(); err != nil {
  307. s.renderClientTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  308. return
  309. }
  310. username := claims.Username
  311. recoveryCode := strings.TrimSpace(r.Form.Get("recovery_code"))
  312. if username == "" || recoveryCode == "" {
  313. s.renderClientTwoFactorRecoveryPage(w, r,
  314. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  315. return
  316. }
  317. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  318. s.renderClientTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  319. return
  320. }
  321. user, userMerged, err := dataprovider.GetUserVariants(username, "")
  322. if err != nil {
  323. if errors.Is(err, util.ErrNotFound) {
  324. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  325. }
  326. s.renderClientTwoFactorRecoveryPage(w, r,
  327. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  328. return
  329. }
  330. if !userMerged.Filters.TOTPConfig.Enabled || !util.Contains(userMerged.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) {
  331. s.renderClientTwoFactorPage(w, r, util.NewI18nError(
  332. util.NewValidationError("two factory authentication is not enabled"), util.I18n2FADisabled), ipAddr)
  333. return
  334. }
  335. for idx, code := range user.Filters.RecoveryCodes {
  336. if err := code.Secret.Decrypt(); err != nil {
  337. s.renderClientInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
  338. return
  339. }
  340. if code.Secret.GetPayload() == recoveryCode {
  341. if code.Used {
  342. s.renderClientTwoFactorRecoveryPage(w, r,
  343. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  344. return
  345. }
  346. user.Filters.RecoveryCodes[idx].Used = true
  347. err = dataprovider.UpdateUser(&user, dataprovider.ActionExecutorSelf, ipAddr, user.Role)
  348. if err != nil {
  349. logger.Warn(logSender, "", "unable to set the recovery code %q as used: %v", recoveryCode, err)
  350. s.renderClientInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
  351. return
  352. }
  353. connectionID := fmt.Sprintf("%v_%v", getProtocolFromRequest(r), xid.New().String())
  354. s.loginUser(w, r, &userMerged, connectionID, ipAddr, true,
  355. s.renderClientTwoFactorRecoveryPage)
  356. return
  357. }
  358. }
  359. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  360. s.renderClientTwoFactorRecoveryPage(w, r,
  361. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  362. }
  363. func (s *httpdServer) handleWebClientTwoFactorPost(w http.ResponseWriter, r *http.Request) {
  364. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  365. claims, err := getTokenClaims(r)
  366. if err != nil {
  367. s.renderNotFoundPage(w, r, nil)
  368. return
  369. }
  370. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  371. if err := r.ParseForm(); err != nil {
  372. s.renderClientTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  373. return
  374. }
  375. username := claims.Username
  376. passcode := strings.TrimSpace(r.Form.Get("passcode"))
  377. if username == "" || passcode == "" {
  378. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  379. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  380. s.renderClientTwoFactorPage(w, r,
  381. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  382. return
  383. }
  384. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  385. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  386. dataprovider.LoginMethodPassword, ipAddr, err)
  387. s.renderClientTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  388. return
  389. }
  390. user, err := dataprovider.GetUserWithGroupSettings(username, "")
  391. if err != nil {
  392. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  393. dataprovider.LoginMethodPassword, ipAddr, err)
  394. s.renderClientTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCredentials), ipAddr)
  395. return
  396. }
  397. if !user.Filters.TOTPConfig.Enabled || !util.Contains(user.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) {
  398. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  399. s.renderClientTwoFactorPage(w, r, util.NewI18nError(common.ErrInternalFailure, util.I18n2FADisabled), ipAddr)
  400. return
  401. }
  402. err = user.Filters.TOTPConfig.Secret.Decrypt()
  403. if err != nil {
  404. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  405. s.renderClientInternalServerErrorPage(w, r, err)
  406. return
  407. }
  408. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  409. user.Filters.TOTPConfig.Secret.GetPayload())
  410. if !match || err != nil {
  411. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  412. s.renderClientTwoFactorPage(w, r,
  413. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  414. return
  415. }
  416. connectionID := fmt.Sprintf("%s_%s", getProtocolFromRequest(r), xid.New().String())
  417. s.loginUser(w, r, &user, connectionID, ipAddr, true, s.renderClientTwoFactorPage)
  418. }
  419. func (s *httpdServer) handleWebAdminTwoFactorRecoveryPost(w http.ResponseWriter, r *http.Request) {
  420. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  421. claims, err := getTokenClaims(r)
  422. if err != nil {
  423. s.renderNotFoundPage(w, r, nil)
  424. return
  425. }
  426. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  427. if err := r.ParseForm(); err != nil {
  428. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  429. return
  430. }
  431. username := claims.Username
  432. recoveryCode := strings.TrimSpace(r.Form.Get("recovery_code"))
  433. if username == "" || recoveryCode == "" {
  434. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  435. ipAddr)
  436. return
  437. }
  438. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  439. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  440. return
  441. }
  442. admin, err := dataprovider.AdminExists(username)
  443. if err != nil {
  444. if errors.Is(err, util.ErrNotFound) {
  445. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  446. }
  447. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  448. ipAddr)
  449. return
  450. }
  451. if !admin.Filters.TOTPConfig.Enabled {
  452. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(util.NewValidationError("two factory authentication is not enabled"), util.I18n2FADisabled), ipAddr)
  453. return
  454. }
  455. for idx, code := range admin.Filters.RecoveryCodes {
  456. if err := code.Secret.Decrypt(); err != nil {
  457. s.renderInternalServerErrorPage(w, r, fmt.Errorf("unable to decrypt recovery code: %w", err))
  458. return
  459. }
  460. if code.Secret.GetPayload() == recoveryCode {
  461. if code.Used {
  462. s.renderTwoFactorRecoveryPage(w, r,
  463. util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials), ipAddr)
  464. return
  465. }
  466. admin.Filters.RecoveryCodes[idx].Used = true
  467. err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, ipAddr, admin.Role)
  468. if err != nil {
  469. logger.Warn(logSender, "", "unable to set the recovery code %q as used: %v", recoveryCode, err)
  470. s.renderInternalServerErrorPage(w, r, errors.New("unable to set the recovery code as used"))
  471. return
  472. }
  473. s.loginAdmin(w, r, &admin, true, s.renderTwoFactorRecoveryPage, ipAddr)
  474. return
  475. }
  476. }
  477. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  478. s.renderTwoFactorRecoveryPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  479. ipAddr)
  480. }
  481. func (s *httpdServer) handleWebAdminTwoFactorPost(w http.ResponseWriter, r *http.Request) {
  482. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  483. claims, err := getTokenClaims(r)
  484. if err != nil {
  485. s.renderNotFoundPage(w, r, nil)
  486. return
  487. }
  488. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  489. if err := r.ParseForm(); err != nil {
  490. s.renderTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  491. return
  492. }
  493. username := claims.Username
  494. passcode := strings.TrimSpace(r.Form.Get("passcode"))
  495. if username == "" || passcode == "" {
  496. s.renderTwoFactorPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  497. ipAddr)
  498. return
  499. }
  500. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  501. err = handleDefenderEventLoginFailed(ipAddr, err)
  502. s.renderTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  503. return
  504. }
  505. admin, err := dataprovider.AdminExists(username)
  506. if err != nil {
  507. if errors.Is(err, util.ErrNotFound) {
  508. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  509. }
  510. s.renderTwoFactorPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCredentials), ipAddr)
  511. return
  512. }
  513. if !admin.Filters.TOTPConfig.Enabled {
  514. s.renderTwoFactorPage(w, r, util.NewI18nError(common.ErrInternalFailure, util.I18n2FADisabled), ipAddr)
  515. return
  516. }
  517. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  518. if err != nil {
  519. s.renderInternalServerErrorPage(w, r, err)
  520. return
  521. }
  522. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  523. admin.Filters.TOTPConfig.Secret.GetPayload())
  524. if !match || err != nil {
  525. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  526. s.renderTwoFactorPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  527. ipAddr)
  528. return
  529. }
  530. s.loginAdmin(w, r, &admin, true, s.renderTwoFactorPage, ipAddr)
  531. }
  532. func (s *httpdServer) handleWebAdminLoginPost(w http.ResponseWriter, r *http.Request) {
  533. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  534. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  535. if err := r.ParseForm(); err != nil {
  536. s.renderAdminLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  537. return
  538. }
  539. username := strings.TrimSpace(r.Form.Get("username"))
  540. password := strings.TrimSpace(r.Form.Get("password"))
  541. if username == "" || password == "" {
  542. s.renderAdminLoginPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  543. ipAddr)
  544. return
  545. }
  546. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  547. s.renderAdminLoginPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF), ipAddr)
  548. return
  549. }
  550. admin, err := dataprovider.CheckAdminAndPass(username, password, ipAddr)
  551. if err != nil {
  552. handleDefenderEventLoginFailed(ipAddr, err) //nolint:errcheck
  553. s.renderAdminLoginPage(w, r, util.NewI18nError(dataprovider.ErrInvalidCredentials, util.I18nErrorInvalidCredentials),
  554. ipAddr)
  555. return
  556. }
  557. s.loginAdmin(w, r, &admin, false, s.renderAdminLoginPage, ipAddr)
  558. }
  559. func (s *httpdServer) renderAdminLoginPage(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string) {
  560. data := loginPage{
  561. commonBasePage: getCommonBasePage(r),
  562. Title: util.I18nLoginTitle,
  563. CurrentURL: webAdminLoginPath,
  564. Error: err,
  565. CSRFToken: createCSRFToken(ip),
  566. Branding: s.binding.Branding.WebAdmin,
  567. FormDisabled: s.binding.isWebAdminLoginFormDisabled(),
  568. }
  569. if s.binding.showClientLoginURL() {
  570. data.AltLoginURL = webClientLoginPath
  571. data.AltLoginName = s.binding.Branding.WebClient.ShortName
  572. }
  573. if smtp.IsEnabled() && !data.FormDisabled {
  574. data.ForgotPwdURL = webAdminForgotPwdPath
  575. }
  576. if s.binding.OIDC.hasRoles() && !s.binding.isWebAdminOIDCLoginDisabled() {
  577. data.OpenIDLoginURL = webAdminOIDCLoginPath
  578. }
  579. renderAdminTemplate(w, templateCommonLogin, data)
  580. }
  581. func (s *httpdServer) handleWebAdminLogin(w http.ResponseWriter, r *http.Request) {
  582. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  583. if !dataprovider.HasAdmin() {
  584. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  585. return
  586. }
  587. msg := getFlashMessage(w, r)
  588. s.renderAdminLoginPage(w, r, msg.getI18nError(), util.GetIPFromRemoteAddress(r.RemoteAddr))
  589. }
  590. func (s *httpdServer) handleWebAdminLogout(w http.ResponseWriter, r *http.Request) {
  591. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  592. c := jwtTokenClaims{}
  593. c.removeCookie(w, r, webBaseAdminPath)
  594. s.logoutOIDCUser(w, r)
  595. http.Redirect(w, r, webAdminLoginPath, http.StatusFound)
  596. }
  597. func (s *httpdServer) handleWebAdminChangePwdPost(w http.ResponseWriter, r *http.Request) {
  598. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  599. err := r.ParseForm()
  600. if err != nil {
  601. s.renderChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm))
  602. return
  603. }
  604. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  605. s.renderForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  606. return
  607. }
  608. err = doChangeAdminPassword(r, strings.TrimSpace(r.Form.Get("current_password")),
  609. strings.TrimSpace(r.Form.Get("new_password1")), strings.TrimSpace(r.Form.Get("new_password2")))
  610. if err != nil {
  611. s.renderChangePasswordPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric))
  612. return
  613. }
  614. s.handleWebAdminLogout(w, r)
  615. }
  616. func (s *httpdServer) handleWebAdminPasswordResetPost(w http.ResponseWriter, r *http.Request) {
  617. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  618. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  619. err := r.ParseForm()
  620. if err != nil {
  621. s.renderResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidForm), ipAddr)
  622. return
  623. }
  624. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  625. s.renderForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  626. return
  627. }
  628. newPassword := strings.TrimSpace(r.Form.Get("password"))
  629. confirmPassword := strings.TrimSpace(r.Form.Get("confirm_password"))
  630. admin, _, err := handleResetPassword(r, strings.TrimSpace(r.Form.Get("code")),
  631. newPassword, confirmPassword, true)
  632. if err != nil {
  633. s.renderResetPwdPage(w, r, util.NewI18nError(err, util.I18nErrorChangePwdGeneric), ipAddr)
  634. return
  635. }
  636. s.loginAdmin(w, r, admin, false, s.renderResetPwdPage, ipAddr)
  637. }
  638. func (s *httpdServer) handleWebAdminSetupPost(w http.ResponseWriter, r *http.Request) {
  639. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  640. if dataprovider.HasAdmin() {
  641. s.renderBadRequestPage(w, r, errors.New("an admin user already exists"))
  642. return
  643. }
  644. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  645. err := r.ParseForm()
  646. if err != nil {
  647. s.renderAdminSetupPage(w, r, "", ipAddr, util.NewI18nError(err, util.I18nErrorInvalidForm))
  648. return
  649. }
  650. if err := verifyCSRFToken(r.Form.Get(csrfFormToken), ipAddr); err != nil {
  651. s.renderForbiddenPage(w, r, util.NewI18nError(err, util.I18nErrorInvalidCSRF))
  652. return
  653. }
  654. username := strings.TrimSpace(r.Form.Get("username"))
  655. password := strings.TrimSpace(r.Form.Get("password"))
  656. confirmPassword := strings.TrimSpace(r.Form.Get("confirm_password"))
  657. installCode := strings.TrimSpace(r.Form.Get("install_code"))
  658. if installationCode != "" && installCode != resolveInstallationCode() {
  659. s.renderAdminSetupPage(w, r, username, ipAddr,
  660. util.NewI18nError(
  661. util.NewValidationError(fmt.Sprintf("%v mismatch", installationCodeHint)),
  662. util.I18nErrorSetupInstallCode),
  663. )
  664. return
  665. }
  666. if username == "" {
  667. s.renderAdminSetupPage(w, r, username, ipAddr,
  668. util.NewI18nError(util.NewValidationError("please set a username"), util.I18nError500Message))
  669. return
  670. }
  671. if password == "" {
  672. s.renderAdminSetupPage(w, r, username, ipAddr,
  673. util.NewI18nError(util.NewValidationError("please set a password"), util.I18nError500Message))
  674. return
  675. }
  676. if password != confirmPassword {
  677. s.renderAdminSetupPage(w, r, username, ipAddr,
  678. util.NewI18nError(errors.New("the two password fields do not match"), util.I18nErrorChangePwdNoMatch))
  679. return
  680. }
  681. admin := dataprovider.Admin{
  682. Username: username,
  683. Password: password,
  684. Status: 1,
  685. Permissions: []string{dataprovider.PermAdminAny},
  686. }
  687. err = dataprovider.AddAdmin(&admin, username, ipAddr, "")
  688. if err != nil {
  689. s.renderAdminSetupPage(w, r, username, ipAddr, util.NewI18nError(err, util.I18nError500Message))
  690. return
  691. }
  692. s.loginAdmin(w, r, &admin, false, nil, ipAddr)
  693. }
  694. func (s *httpdServer) loginUser(
  695. w http.ResponseWriter, r *http.Request, user *dataprovider.User, connectionID, ipAddr string,
  696. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string),
  697. ) {
  698. c := jwtTokenClaims{
  699. Username: user.Username,
  700. Permissions: user.Filters.WebClient,
  701. Signature: user.GetSignature(),
  702. Role: user.Role,
  703. MustSetTwoFactorAuth: user.MustSetSecondFactor(),
  704. MustChangePassword: user.MustChangePassword(),
  705. RequiredTwoFactorProtocols: user.Filters.TwoFactorAuthProtocols,
  706. }
  707. audience := tokenAudienceWebClient
  708. if user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) &&
  709. user.CanManageMFA() && !isSecondFactorAuth {
  710. audience = tokenAudienceWebClientPartial
  711. }
  712. err := c.createAndSetCookie(w, r, s.tokenAuth, audience, ipAddr)
  713. if err != nil {
  714. logger.Warn(logSender, connectionID, "unable to set user login cookie %v", err)
  715. updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  716. errorFunc(w, r, util.NewI18nError(err, util.I18nError500Message), ipAddr)
  717. return
  718. }
  719. if isSecondFactorAuth {
  720. invalidateToken(r)
  721. }
  722. if audience == tokenAudienceWebClientPartial {
  723. redirectPath := webClientTwoFactorPath
  724. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  725. redirectPath += "?next=" + url.QueryEscape(next)
  726. }
  727. http.Redirect(w, r, redirectPath, http.StatusFound)
  728. return
  729. }
  730. updateLoginMetrics(user, dataprovider.LoginMethodPassword, ipAddr, err)
  731. dataprovider.UpdateLastLogin(user)
  732. if next := r.URL.Query().Get("next"); strings.HasPrefix(next, webClientFilesPath) {
  733. http.Redirect(w, r, next, http.StatusFound)
  734. return
  735. }
  736. http.Redirect(w, r, webClientFilesPath, http.StatusFound)
  737. }
  738. func (s *httpdServer) loginAdmin(
  739. w http.ResponseWriter, r *http.Request, admin *dataprovider.Admin,
  740. isSecondFactorAuth bool, errorFunc func(w http.ResponseWriter, r *http.Request, err *util.I18nError, ip string),
  741. ipAddr string,
  742. ) {
  743. c := jwtTokenClaims{
  744. Username: admin.Username,
  745. Permissions: admin.Permissions,
  746. Role: admin.Role,
  747. Signature: admin.GetSignature(),
  748. HideUserPageSections: admin.Filters.Preferences.HideUserPageSections,
  749. }
  750. audience := tokenAudienceWebAdmin
  751. if admin.Filters.TOTPConfig.Enabled && admin.CanManageMFA() && !isSecondFactorAuth {
  752. audience = tokenAudienceWebAdminPartial
  753. }
  754. err := c.createAndSetCookie(w, r, s.tokenAuth, audience, ipAddr)
  755. if err != nil {
  756. logger.Warn(logSender, "", "unable to set admin login cookie %v", err)
  757. if errorFunc == nil {
  758. s.renderAdminSetupPage(w, r, admin.Username, ipAddr, util.NewI18nError(err, util.I18nError500Message))
  759. return
  760. }
  761. errorFunc(w, r, util.NewI18nError(err, util.I18nError500Message), ipAddr)
  762. return
  763. }
  764. if isSecondFactorAuth {
  765. invalidateToken(r)
  766. }
  767. if audience == tokenAudienceWebAdminPartial {
  768. http.Redirect(w, r, webAdminTwoFactorPath, http.StatusFound)
  769. return
  770. }
  771. dataprovider.UpdateAdminLastLogin(admin)
  772. http.Redirect(w, r, webUsersPath, http.StatusFound)
  773. }
  774. func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
  775. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  776. invalidateToken(r)
  777. sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
  778. }
  779. func (s *httpdServer) getUserToken(w http.ResponseWriter, r *http.Request) {
  780. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  781. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  782. username, password, ok := r.BasicAuth()
  783. protocol := common.ProtocolHTTP
  784. if !ok {
  785. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  786. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  787. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  788. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  789. return
  790. }
  791. if username == "" || password == "" {
  792. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  793. dataprovider.LoginMethodPassword, ipAddr, common.ErrNoCredentials)
  794. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  795. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  796. return
  797. }
  798. if err := common.Config.ExecutePostConnectHook(ipAddr, protocol); err != nil {
  799. updateLoginMetrics(&dataprovider.User{BaseUser: sdk.BaseUser{Username: username}},
  800. dataprovider.LoginMethodPassword, ipAddr, err)
  801. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  802. return
  803. }
  804. user, err := dataprovider.CheckUserAndPass(username, password, ipAddr, protocol)
  805. if err != nil {
  806. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  807. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  808. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  809. http.StatusUnauthorized)
  810. return
  811. }
  812. connectionID := fmt.Sprintf("%v_%v", protocol, xid.New().String())
  813. if err := checkHTTPClientUser(&user, r, connectionID, true); err != nil {
  814. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  815. sendAPIResponse(w, r, err, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  816. return
  817. }
  818. if user.Filters.TOTPConfig.Enabled && util.Contains(user.Filters.TOTPConfig.Protocols, common.ProtocolHTTP) {
  819. passcode := r.Header.Get(otpHeaderCode)
  820. if passcode == "" {
  821. logger.Debug(logSender, "", "TOTP enabled for user %q and not passcode provided, authentication refused", user.Username)
  822. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  823. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  824. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  825. http.StatusUnauthorized)
  826. return
  827. }
  828. err = user.Filters.TOTPConfig.Secret.Decrypt()
  829. if err != nil {
  830. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  831. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err), http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  832. return
  833. }
  834. match, err := mfa.ValidateTOTPPasscode(user.Filters.TOTPConfig.ConfigName, passcode,
  835. user.Filters.TOTPConfig.Secret.GetPayload())
  836. if !match || err != nil {
  837. logger.Debug(logSender, "invalid passcode for user %q, match? %v, err: %v", user.Username, match, err)
  838. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  839. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, dataprovider.ErrInvalidCredentials)
  840. sendAPIResponse(w, r, dataprovider.ErrInvalidCredentials, http.StatusText(http.StatusUnauthorized),
  841. http.StatusUnauthorized)
  842. return
  843. }
  844. }
  845. defer user.CloseFs() //nolint:errcheck
  846. err = user.CheckFsRoot(connectionID)
  847. if err != nil {
  848. logger.Warn(logSender, connectionID, "unable to check fs root: %v", err)
  849. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  850. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  851. return
  852. }
  853. s.generateAndSendUserToken(w, r, ipAddr, user)
  854. }
  855. func (s *httpdServer) generateAndSendUserToken(w http.ResponseWriter, r *http.Request, ipAddr string, user dataprovider.User) {
  856. c := jwtTokenClaims{
  857. Username: user.Username,
  858. Permissions: user.Filters.WebClient,
  859. Signature: user.GetSignature(),
  860. Role: user.Role,
  861. MustSetTwoFactorAuth: user.MustSetSecondFactor(),
  862. MustChangePassword: user.MustChangePassword(),
  863. RequiredTwoFactorProtocols: user.Filters.TwoFactorAuthProtocols,
  864. }
  865. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPIUser, ipAddr)
  866. if err != nil {
  867. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, common.ErrInternalFailure)
  868. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  869. return
  870. }
  871. updateLoginMetrics(&user, dataprovider.LoginMethodPassword, ipAddr, err)
  872. dataprovider.UpdateLastLogin(&user)
  873. render.JSON(w, r, resp)
  874. }
  875. func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
  876. username, password, ok := r.BasicAuth()
  877. if !ok {
  878. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  879. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  880. return
  881. }
  882. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  883. admin, err := dataprovider.CheckAdminAndPass(username, password, ipAddr)
  884. if err != nil {
  885. err = handleDefenderEventLoginFailed(ipAddr, err)
  886. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  887. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  888. return
  889. }
  890. if admin.Filters.TOTPConfig.Enabled {
  891. passcode := r.Header.Get(otpHeaderCode)
  892. if passcode == "" {
  893. logger.Debug(logSender, "", "TOTP enabled for admin %q and not passcode provided, authentication refused", admin.Username)
  894. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  895. err = handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials)
  896. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  897. return
  898. }
  899. err = admin.Filters.TOTPConfig.Secret.Decrypt()
  900. if err != nil {
  901. sendAPIResponse(w, r, fmt.Errorf("unable to decrypt TOTP secret: %w", err),
  902. http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  903. return
  904. }
  905. match, err := mfa.ValidateTOTPPasscode(admin.Filters.TOTPConfig.ConfigName, passcode,
  906. admin.Filters.TOTPConfig.Secret.GetPayload())
  907. if !match || err != nil {
  908. logger.Debug(logSender, "invalid passcode for admin %q, match? %v, err: %v", admin.Username, match, err)
  909. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  910. err = handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials)
  911. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized),
  912. http.StatusUnauthorized)
  913. return
  914. }
  915. }
  916. s.generateAndSendToken(w, r, admin, ipAddr)
  917. }
  918. func (s *httpdServer) generateAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin, ip string) {
  919. c := jwtTokenClaims{
  920. Username: admin.Username,
  921. Permissions: admin.Permissions,
  922. Role: admin.Role,
  923. Signature: admin.GetSignature(),
  924. }
  925. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI, ip)
  926. if err != nil {
  927. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  928. return
  929. }
  930. dataprovider.UpdateAdminLastLogin(&admin)
  931. render.JSON(w, r, resp)
  932. }
  933. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  934. if _, ok := r.Context().Value(oidcTokenKey).(string); ok {
  935. return
  936. }
  937. token, claims, err := jwtauth.FromContext(r.Context())
  938. if err != nil {
  939. return
  940. }
  941. tokenClaims := jwtTokenClaims{}
  942. tokenClaims.Decode(claims)
  943. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  944. return
  945. }
  946. if time.Until(token.Expiration()) > tokenRefreshThreshold {
  947. return
  948. }
  949. if util.Contains(token.Audience(), tokenAudienceWebClient) {
  950. s.refreshClientToken(w, r, tokenClaims)
  951. } else {
  952. s.refreshAdminToken(w, r, tokenClaims)
  953. }
  954. }
  955. func (s *httpdServer) refreshClientToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  956. user, err := dataprovider.GetUserWithGroupSettings(tokenClaims.Username, "")
  957. if err != nil {
  958. return
  959. }
  960. if user.GetSignature() != tokenClaims.Signature {
  961. logger.Debug(logSender, "", "signature mismatch for user %q, unable to refresh cookie", user.Username)
  962. return
  963. }
  964. if err := checkHTTPClientUser(&user, r, xid.New().String(), true); err != nil {
  965. logger.Debug(logSender, "", "unable to refresh cookie for user %q: %v", user.Username, err)
  966. return
  967. }
  968. tokenClaims.Permissions = user.Filters.WebClient
  969. tokenClaims.Role = user.Role
  970. logger.Debug(logSender, "", "cookie refreshed for user %q", user.Username)
  971. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebClient, util.GetIPFromRemoteAddress(r.RemoteAddr)) //nolint:errcheck
  972. }
  973. func (s *httpdServer) refreshAdminToken(w http.ResponseWriter, r *http.Request, tokenClaims jwtTokenClaims) {
  974. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  975. if err != nil {
  976. return
  977. }
  978. if admin.Status != 1 {
  979. logger.Debug(logSender, "", "admin %q is disabled, unable to refresh cookie", admin.Username)
  980. return
  981. }
  982. if admin.GetSignature() != tokenClaims.Signature {
  983. logger.Debug(logSender, "", "signature mismatch for admin %q, unable to refresh cookie", admin.Username)
  984. return
  985. }
  986. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  987. if !admin.CanLoginFromIP(ipAddr) {
  988. logger.Debug(logSender, "", "admin %q cannot login from %v, unable to refresh cookie", admin.Username, r.RemoteAddr)
  989. return
  990. }
  991. tokenClaims.Permissions = admin.Permissions
  992. tokenClaims.Role = admin.Role
  993. tokenClaims.HideUserPageSections = admin.Filters.Preferences.HideUserPageSections
  994. logger.Debug(logSender, "", "cookie refreshed for admin %q", admin.Username)
  995. tokenClaims.createAndSetCookie(w, r, s.tokenAuth, tokenAudienceWebAdmin, ipAddr) //nolint:errcheck
  996. }
  997. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  998. token, _, err := jwtauth.FromContext(r.Context())
  999. if token == nil || err != nil {
  1000. _, err = r.Cookie(jwtCookieKey)
  1001. if err != nil {
  1002. return r
  1003. }
  1004. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  1005. ctx := jwtauth.NewContext(r.Context(), token, err)
  1006. return r.WithContext(ctx)
  1007. }
  1008. return r
  1009. }
  1010. func (s *httpdServer) parseHeaders(next http.Handler) http.Handler {
  1011. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1012. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1013. var ip net.IP
  1014. isUnixSocket := filepath.IsAbs(s.binding.Address)
  1015. if !isUnixSocket {
  1016. ip = net.ParseIP(ipAddr)
  1017. }
  1018. areHeadersAllowed := false
  1019. if isUnixSocket || ip != nil {
  1020. for _, allow := range s.binding.allowHeadersFrom {
  1021. if allow(ip) {
  1022. parsedIP := util.GetRealIP(r, s.binding.ClientIPProxyHeader, s.binding.ClientIPHeaderDepth)
  1023. if parsedIP != "" {
  1024. ipAddr = parsedIP
  1025. r.RemoteAddr = ipAddr
  1026. }
  1027. if forwardedProto := r.Header.Get(xForwardedProto); forwardedProto != "" {
  1028. ctx := context.WithValue(r.Context(), forwardedProtoKey, forwardedProto)
  1029. r = r.WithContext(ctx)
  1030. }
  1031. areHeadersAllowed = true
  1032. break
  1033. }
  1034. }
  1035. }
  1036. if !areHeadersAllowed {
  1037. for idx := range s.binding.Security.proxyHeaders {
  1038. r.Header.Del(s.binding.Security.proxyHeaders[idx])
  1039. }
  1040. }
  1041. next.ServeHTTP(w, r)
  1042. })
  1043. }
  1044. func (s *httpdServer) checkConnection(next http.Handler) http.Handler {
  1045. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1046. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  1047. common.Connections.AddClientConnection(ipAddr)
  1048. defer common.Connections.RemoveClientConnection(ipAddr)
  1049. if err := common.Connections.IsNewConnectionAllowed(ipAddr, common.ProtocolHTTP); err != nil {
  1050. logger.Log(logger.LevelDebug, common.ProtocolHTTP, "", "connection not allowed from ip %q: %v", ipAddr, err)
  1051. s.sendForbiddenResponse(w, r, util.NewI18nError(err, util.I18nErrorConnectionForbidden))
  1052. return
  1053. }
  1054. if common.IsBanned(ipAddr, common.ProtocolHTTP) {
  1055. s.sendForbiddenResponse(w, r, util.NewI18nError(
  1056. util.NewGenericError("your IP address is blocked"),
  1057. util.I18nErrorIPForbidden),
  1058. )
  1059. return
  1060. }
  1061. if delay, err := common.LimitRate(common.ProtocolHTTP, ipAddr); err != nil {
  1062. delay += 499999999 * time.Nanosecond
  1063. w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
  1064. w.Header().Set("X-Retry-In", delay.String())
  1065. s.sendTooManyRequestResponse(w, r, err)
  1066. return
  1067. }
  1068. next.ServeHTTP(w, r)
  1069. })
  1070. }
  1071. func (s *httpdServer) sendTooManyRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
  1072. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1073. r = s.updateContextFromCookie(r)
  1074. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1075. s.renderClientMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1076. util.NewI18nError(errors.New(http.StatusText(http.StatusTooManyRequests)), util.I18nError429Message), "")
  1077. return
  1078. }
  1079. s.renderMessagePage(w, r, util.I18nError429Title, http.StatusTooManyRequests,
  1080. util.NewI18nError(errors.New(http.StatusText(http.StatusTooManyRequests)), util.I18nError429Message), "")
  1081. return
  1082. }
  1083. sendAPIResponse(w, r, err, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)
  1084. }
  1085. func (s *httpdServer) sendForbiddenResponse(w http.ResponseWriter, r *http.Request, err error) {
  1086. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1087. r = s.updateContextFromCookie(r)
  1088. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1089. s.renderClientForbiddenPage(w, r, err)
  1090. return
  1091. }
  1092. s.renderForbiddenPage(w, r, err)
  1093. return
  1094. }
  1095. sendAPIResponse(w, r, err, "", http.StatusForbidden)
  1096. }
  1097. func (s *httpdServer) badHostHandler(w http.ResponseWriter, r *http.Request) {
  1098. host := r.Host
  1099. for _, header := range s.binding.Security.HostsProxyHeaders {
  1100. if h := r.Header.Get(header); h != "" {
  1101. host = h
  1102. break
  1103. }
  1104. }
  1105. s.sendForbiddenResponse(w, r, util.NewI18nError(
  1106. util.NewGenericError(fmt.Sprintf("The host %q is not allowed", host)),
  1107. util.I18nErrorConnectionForbidden,
  1108. ))
  1109. }
  1110. func (s *httpdServer) notFoundHandler(w http.ResponseWriter, r *http.Request) {
  1111. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1112. if (s.enableWebAdmin || s.enableWebClient) && isWebRequest(r) {
  1113. r = s.updateContextFromCookie(r)
  1114. if s.enableWebClient && (isWebClientRequest(r) || !s.enableWebAdmin) {
  1115. s.renderClientNotFoundPage(w, r, nil)
  1116. return
  1117. }
  1118. s.renderNotFoundPage(w, r, nil)
  1119. return
  1120. }
  1121. sendAPIResponse(w, r, nil, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  1122. }
  1123. func (s *httpdServer) redirectToWebPath(w http.ResponseWriter, r *http.Request, webPath string) {
  1124. if dataprovider.HasAdmin() {
  1125. http.Redirect(w, r, webPath, http.StatusFound)
  1126. return
  1127. }
  1128. if s.enableWebAdmin {
  1129. http.Redirect(w, r, webAdminSetupPath, http.StatusFound)
  1130. }
  1131. }
  1132. // The StripSlashes causes infinite redirects at the root path if used with http.FileServer.
  1133. // We also don't strip paths with more than one trailing slash, see #1434
  1134. func (s *httpdServer) mustStripSlash(r *http.Request) bool {
  1135. var urlPath string
  1136. rctx := chi.RouteContext(r.Context())
  1137. if rctx != nil && rctx.RoutePath != "" {
  1138. urlPath = rctx.RoutePath
  1139. } else {
  1140. urlPath = r.URL.Path
  1141. }
  1142. return !strings.HasSuffix(urlPath, "//") && !strings.HasPrefix(urlPath, webOpenAPIPath) &&
  1143. !strings.HasPrefix(urlPath, webStaticFilesPath) && !strings.HasPrefix(urlPath, acmeChallengeURI)
  1144. }
  1145. func (s *httpdServer) initializeRouter() {
  1146. var hasHTTPSRedirect bool
  1147. s.tokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(s.signingPassphrase), nil)
  1148. s.router = chi.NewRouter()
  1149. s.router.Use(middleware.RequestID)
  1150. s.router.Use(s.parseHeaders)
  1151. s.router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  1152. s.router.Use(middleware.Recoverer)
  1153. s.router.Use(s.checkConnection)
  1154. if s.binding.Security.Enabled {
  1155. secureMiddleware := secure.New(secure.Options{
  1156. AllowedHosts: s.binding.Security.AllowedHosts,
  1157. AllowedHostsAreRegex: s.binding.Security.AllowedHostsAreRegex,
  1158. HostsProxyHeaders: s.binding.Security.HostsProxyHeaders,
  1159. SSLProxyHeaders: s.binding.Security.getHTTPSProxyHeaders(),
  1160. STSSeconds: s.binding.Security.STSSeconds,
  1161. STSIncludeSubdomains: s.binding.Security.STSIncludeSubdomains,
  1162. STSPreload: s.binding.Security.STSPreload,
  1163. ContentTypeNosniff: s.binding.Security.ContentTypeNosniff,
  1164. ContentSecurityPolicy: s.binding.Security.ContentSecurityPolicy,
  1165. PermissionsPolicy: s.binding.Security.PermissionsPolicy,
  1166. CrossOriginOpenerPolicy: s.binding.Security.CrossOriginOpenerPolicy,
  1167. })
  1168. secureMiddleware.SetBadHostHandler(http.HandlerFunc(s.badHostHandler))
  1169. s.router.Use(secureMiddleware.Handler)
  1170. if s.binding.Security.HTTPSRedirect {
  1171. s.router.Use(s.binding.Security.redirectHandler)
  1172. hasHTTPSRedirect = true
  1173. }
  1174. }
  1175. if s.cors.Enabled {
  1176. c := cors.New(cors.Options{
  1177. AllowedOrigins: util.RemoveDuplicates(s.cors.AllowedOrigins, true),
  1178. AllowedMethods: util.RemoveDuplicates(s.cors.AllowedMethods, true),
  1179. AllowedHeaders: util.RemoveDuplicates(s.cors.AllowedHeaders, true),
  1180. ExposedHeaders: util.RemoveDuplicates(s.cors.ExposedHeaders, true),
  1181. MaxAge: s.cors.MaxAge,
  1182. AllowCredentials: s.cors.AllowCredentials,
  1183. OptionsPassthrough: s.cors.OptionsPassthrough,
  1184. OptionsSuccessStatus: s.cors.OptionsSuccessStatus,
  1185. AllowPrivateNetwork: s.cors.AllowPrivateNetwork,
  1186. })
  1187. s.router.Use(c.Handler)
  1188. }
  1189. s.router.Use(middleware.GetHead)
  1190. s.router.Use(middleware.Maybe(middleware.StripSlashes, s.mustStripSlash))
  1191. s.router.NotFound(s.notFoundHandler)
  1192. s.router.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  1193. render.PlainText(w, r, "ok")
  1194. })
  1195. s.router.Get(robotsTxtPath, func(w http.ResponseWriter, r *http.Request) {
  1196. render.PlainText(w, r, "User-agent: *\nDisallow: /")
  1197. })
  1198. if hasHTTPSRedirect {
  1199. if p := acme.GetHTTP01WebRoot(); p != "" {
  1200. serveStaticDir(s.router, acmeChallengeURI, p, true)
  1201. }
  1202. }
  1203. if s.enableRESTAPI {
  1204. // share API available to external users
  1205. s.router.Get(sharesPath+"/{id}", s.downloadFromShare) //nolint:goconst
  1206. s.router.Post(sharesPath+"/{id}", s.uploadFilesToShare)
  1207. s.router.Post(sharesPath+"/{id}/{name}", s.uploadFileToShare)
  1208. s.router.With(compressor.Handler).Get(sharesPath+"/{id}/dirs", s.readBrowsableShareContents)
  1209. s.router.Get(sharesPath+"/{id}/files", s.downloadBrowsableSharedFile)
  1210. s.router.Get(tokenPath, s.getToken)
  1211. s.router.Post(adminPath+"/{username}/forgot-password", forgotAdminPassword)
  1212. s.router.Post(adminPath+"/{username}/reset-password", resetAdminPassword)
  1213. s.router.Post(userPath+"/{username}/forgot-password", forgotUserPassword)
  1214. s.router.Post(userPath+"/{username}/reset-password", resetUserPassword)
  1215. s.router.Group(func(router chi.Router) {
  1216. router.Use(checkNodeToken(s.tokenAuth))
  1217. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeAdmin))
  1218. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1219. router.Use(jwtAuthenticatorAPI)
  1220. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  1221. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1222. render.JSON(w, r, version.Get())
  1223. })
  1224. router.With(forbidAPIKeyAuthentication).Get(logoutPath, s.logout)
  1225. router.With(forbidAPIKeyAuthentication).Get(adminProfilePath, getAdminProfile)
  1226. router.With(forbidAPIKeyAuthentication).Put(adminProfilePath, updateAdminProfile)
  1227. router.With(forbidAPIKeyAuthentication).Put(adminPwdPath, changeAdminPassword)
  1228. // admin TOTP APIs
  1229. router.With(forbidAPIKeyAuthentication).Get(adminTOTPConfigsPath, getTOTPConfigs)
  1230. router.With(forbidAPIKeyAuthentication).Post(adminTOTPGeneratePath, generateTOTPSecret)
  1231. router.With(forbidAPIKeyAuthentication).Post(adminTOTPValidatePath, validateTOTPPasscode)
  1232. router.With(forbidAPIKeyAuthentication).Post(adminTOTPSavePath, saveTOTPConfig)
  1233. router.With(forbidAPIKeyAuthentication).Get(admin2FARecoveryCodesPath, getRecoveryCodes)
  1234. router.With(forbidAPIKeyAuthentication).Post(admin2FARecoveryCodesPath, generateRecoveryCodes)
  1235. router.With(s.checkPerm(dataprovider.PermAdminViewServerStatus)).
  1236. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  1237. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1238. render.JSON(w, r, getServicesStatus())
  1239. })
  1240. router.With(s.checkPerm(dataprovider.PermAdminViewConnections)).Get(activeConnectionsPath, getActiveConnections)
  1241. router.With(s.checkPerm(dataprovider.PermAdminCloseConnections)).
  1242. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  1243. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/users/scans", getUsersQuotaScans)
  1244. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/users/{username}/scan", startUserQuotaScan)
  1245. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotasBasePath+"/folders/scans", getFoldersQuotaScans)
  1246. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotasBasePath+"/folders/{name}/scan", startFolderQuotaScan)
  1247. router.With(s.checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  1248. router.With(s.checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  1249. router.With(s.checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername) //nolint:goconst
  1250. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  1251. router.With(s.checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  1252. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}/2fa/disable", disableUser2FA)
  1253. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Get(folderPath, getFolders)
  1254. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Get(folderPath+"/{name}", getFolderByName) //nolint:goconst
  1255. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(folderPath, addFolder)
  1256. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Put(folderPath+"/{name}", updateFolder)
  1257. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Delete(folderPath+"/{name}", deleteFolder)
  1258. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Get(groupPath, getGroups)
  1259. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Get(groupPath+"/{name}", getGroupByName)
  1260. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(groupPath, addGroup)
  1261. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Put(groupPath+"/{name}", updateGroup)
  1262. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Delete(groupPath+"/{name}", deleteGroup)
  1263. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Get(dumpDataPath, dumpData)
  1264. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Get(loadDataPath, loadData)
  1265. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Post(loadDataPath, loadDataFromRequest)
  1266. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/usage",
  1267. updateUserQuotaUsage)
  1268. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/users/{username}/transfer-usage",
  1269. updateUserTransferQuotaUsage)
  1270. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Put(quotasBasePath+"/folders/{name}/usage",
  1271. updateFolderQuotaUsage)
  1272. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts, getDefenderHosts)
  1273. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderHosts+"/{id}", getDefenderHostByID)
  1274. router.With(s.checkPerm(dataprovider.PermAdminManageDefender)).Delete(defenderHosts+"/{id}", deleteDefenderHostByID)
  1275. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
  1276. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
  1277. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
  1278. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
  1279. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
  1280. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}/2fa/disable", disableAdmin2FA)
  1281. router.With(s.checkPerm(dataprovider.PermAdminRetentionChecks)).Get(retentionChecksPath, getRetentionChecks)
  1282. router.With(s.checkPerm(dataprovider.PermAdminRetentionChecks)).Post(retentionBasePath+"/{username}/check",
  1283. startRetentionCheck)
  1284. router.With(s.checkPerm(dataprovider.PermAdminMetadataChecks)).Get(metadataChecksPath, getMetadataChecks)
  1285. router.With(s.checkPerm(dataprovider.PermAdminMetadataChecks)).Post(metadataBasePath+"/{username}/check",
  1286. startMetadataCheck)
  1287. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1288. Get(fsEventsPath, searchFsEvents)
  1289. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1290. Get(providerEventsPath, searchProviderEvents)
  1291. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler).
  1292. Get(logEventsPath, searchLogEvents)
  1293. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1294. Get(apiKeysPath, getAPIKeys)
  1295. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1296. Post(apiKeysPath, addAPIKey)
  1297. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1298. Get(apiKeysPath+"/{id}", getAPIKeyByID)
  1299. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1300. Put(apiKeysPath+"/{id}", updateAPIKey)
  1301. router.With(forbidAPIKeyAuthentication, s.checkPerm(dataprovider.PermAdminManageAPIKeys)).
  1302. Delete(apiKeysPath+"/{id}", deleteAPIKey)
  1303. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Get(eventActionsPath, getEventActions)
  1304. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Get(eventActionsPath+"/{name}", getEventActionByName)
  1305. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(eventActionsPath, addEventAction)
  1306. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Put(eventActionsPath+"/{name}", updateEventAction)
  1307. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Delete(eventActionsPath+"/{name}", deleteEventAction)
  1308. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Get(eventRulesPath, getEventRules)
  1309. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Get(eventRulesPath+"/{name}", getEventRuleByName)
  1310. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(eventRulesPath, addEventRule)
  1311. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Put(eventRulesPath+"/{name}", updateEventRule)
  1312. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Delete(eventRulesPath+"/{name}", deleteEventRule)
  1313. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(eventRulesPath+"/run/{name}", runOnDemandRule)
  1314. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Get(rolesPath, getRoles)
  1315. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Post(rolesPath, addRole)
  1316. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Get(rolesPath+"/{name}", getRoleByName)
  1317. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Put(rolesPath+"/{name}", updateRole)
  1318. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Delete(rolesPath+"/{name}", deleteRole)
  1319. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists), compressor.Handler).Get(ipListsPath+"/{type}", getIPListEntries) //nolint:goconst
  1320. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Post(ipListsPath+"/{type}", addIPListEntry)
  1321. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Get(ipListsPath+"/{type}/{ipornet}", getIPListEntry) //nolint:goconst
  1322. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Put(ipListsPath+"/{type}/{ipornet}", updateIPListEntry)
  1323. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Delete(ipListsPath+"/{type}/{ipornet}", deleteIPListEntry)
  1324. })
  1325. s.router.Get(userTokenPath, s.getUserToken)
  1326. s.router.Group(func(router chi.Router) {
  1327. router.Use(checkAPIKeyAuth(s.tokenAuth, dataprovider.APIKeyScopeUser))
  1328. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  1329. router.Use(jwtAuthenticatorAPIUser)
  1330. router.With(forbidAPIKeyAuthentication).Get(userLogoutPath, s.logout)
  1331. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1332. Put(userPwdPath, changeUserPassword)
  1333. router.With(forbidAPIKeyAuthentication).Get(userProfilePath, getUserProfile)
  1334. router.With(forbidAPIKeyAuthentication, s.checkAuthRequirements).Put(userProfilePath, updateUserProfile)
  1335. // user TOTP APIs
  1336. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1337. Get(userTOTPConfigsPath, getTOTPConfigs)
  1338. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1339. Post(userTOTPGeneratePath, generateTOTPSecret)
  1340. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1341. Post(userTOTPValidatePath, validateTOTPPasscode)
  1342. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1343. Post(userTOTPSavePath, saveTOTPConfig)
  1344. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1345. Get(user2FARecoveryCodesPath, getRecoveryCodes)
  1346. router.With(forbidAPIKeyAuthentication, s.checkHTTPUserPerm(sdk.WebClientMFADisabled)).
  1347. Post(user2FARecoveryCodesPath, generateRecoveryCodes)
  1348. router.With(s.checkAuthRequirements, compressor.Handler).Get(userDirsPath, readUserFolder)
  1349. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1350. Post(userDirsPath, createUserDir)
  1351. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1352. Patch(userDirsPath, renameUserFsEntry)
  1353. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1354. Delete(userDirsPath, deleteUserDir)
  1355. router.With(s.checkAuthRequirements).Get(userFilesPath, getUserFile)
  1356. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1357. Post(userFilesPath, uploadUserFiles)
  1358. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1359. Patch(userFilesPath, renameUserFsEntry)
  1360. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1361. Delete(userFilesPath, deleteUserFile)
  1362. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1363. Post(userFileActionsPath+"/move", renameUserFsEntry)
  1364. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1365. Post(userFileActionsPath+"/copy", copyUserFsEntry)
  1366. router.With(s.checkAuthRequirements).Post(userStreamZipPath, getUserFilesAsZipStream)
  1367. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1368. Get(userSharesPath, getShares)
  1369. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1370. Post(userSharesPath, addShare)
  1371. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1372. Get(userSharesPath+"/{id}", getShareByID)
  1373. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1374. Put(userSharesPath+"/{id}", updateShare)
  1375. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1376. Delete(userSharesPath+"/{id}", deleteShare)
  1377. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1378. Post(userUploadFilePath, uploadUserFile)
  1379. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled)).
  1380. Patch(userFilesDirsMetadataPath, setFileDirMetadata)
  1381. })
  1382. if s.renderOpenAPI {
  1383. s.router.Group(func(router chi.Router) {
  1384. router.Use(compressor.Handler)
  1385. serveStaticDir(router, webOpenAPIPath, s.openAPIPath, false)
  1386. })
  1387. }
  1388. }
  1389. if s.enableWebAdmin || s.enableWebClient {
  1390. s.router.Group(func(router chi.Router) {
  1391. router.Use(compressor.Handler)
  1392. serveStaticDir(router, webStaticFilesPath, s.staticFilesPath, true)
  1393. })
  1394. if s.binding.OIDC.isEnabled() {
  1395. s.router.Get(webOIDCRedirectPath, s.handleOIDCRedirect)
  1396. }
  1397. if s.enableWebClient {
  1398. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1399. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1400. s.redirectToWebPath(w, r, webClientLoginPath)
  1401. })
  1402. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1403. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1404. s.redirectToWebPath(w, r, webClientLoginPath)
  1405. })
  1406. } else {
  1407. s.router.Get(webRootPath, func(w http.ResponseWriter, r *http.Request) {
  1408. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1409. s.redirectToWebPath(w, r, webAdminLoginPath)
  1410. })
  1411. s.router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  1412. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1413. s.redirectToWebPath(w, r, webAdminLoginPath)
  1414. })
  1415. }
  1416. }
  1417. s.setupWebClientRoutes()
  1418. s.setupWebAdminRoutes()
  1419. }
  1420. func (s *httpdServer) setupWebClientRoutes() {
  1421. if s.enableWebClient {
  1422. s.router.Get(webBaseClientPath, func(w http.ResponseWriter, r *http.Request) {
  1423. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  1424. http.Redirect(w, r, webClientLoginPath, http.StatusFound)
  1425. })
  1426. s.router.Get(webClientLoginPath, s.handleClientWebLogin)
  1427. if s.binding.OIDC.isEnabled() && !s.binding.isWebClientOIDCLoginDisabled() {
  1428. s.router.Get(webClientOIDCLoginPath, s.handleWebClientOIDCLogin)
  1429. }
  1430. if !s.binding.isWebClientLoginFormDisabled() {
  1431. s.router.Post(webClientLoginPath, s.handleWebClientLoginPost)
  1432. s.router.Get(webClientForgotPwdPath, s.handleWebClientForgotPwd)
  1433. s.router.Post(webClientForgotPwdPath, s.handleWebClientForgotPwdPost)
  1434. s.router.Get(webClientResetPwdPath, s.handleWebClientPasswordReset)
  1435. s.router.Post(webClientResetPwdPath, s.handleWebClientPasswordResetPost)
  1436. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1437. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1438. Get(webClientTwoFactorPath, s.handleWebClientTwoFactor)
  1439. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1440. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1441. Post(webClientTwoFactorPath, s.handleWebClientTwoFactorPost)
  1442. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1443. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1444. Get(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecovery)
  1445. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1446. s.jwtAuthenticatorPartial(tokenAudienceWebClientPartial)).
  1447. Post(webClientTwoFactorRecoveryPath, s.handleWebClientTwoFactorRecoveryPost)
  1448. }
  1449. // share routes available to external users
  1450. s.router.Get(webClientPubSharesPath+"/{id}/login", s.handleClientShareLoginGet)
  1451. s.router.Post(webClientPubSharesPath+"/{id}/login", s.handleClientShareLoginPost)
  1452. s.router.Get(webClientPubSharesPath+"/{id}", s.downloadFromShare)
  1453. s.router.Post(webClientPubSharesPath+"/{id}/partial", s.handleClientSharePartialDownload)
  1454. s.router.Get(webClientPubSharesPath+"/{id}/browse", s.handleShareGetFiles)
  1455. s.router.Post(webClientPubSharesPath+"/{id}/browse/exist", s.handleClientShareCheckExist)
  1456. s.router.Get(webClientPubSharesPath+"/{id}/download", s.handleClientSharedFile)
  1457. s.router.Get(webClientPubSharesPath+"/{id}/upload", s.handleClientUploadToShare)
  1458. s.router.With(compressor.Handler).Get(webClientPubSharesPath+"/{id}/dirs", s.handleShareGetDirContents)
  1459. s.router.Post(webClientPubSharesPath+"/{id}", s.uploadFilesToShare)
  1460. s.router.Post(webClientPubSharesPath+"/{id}/{name}", s.uploadFileToShare)
  1461. s.router.Get(webClientPubSharesPath+"/{id}/viewpdf", s.handleShareViewPDF)
  1462. s.router.Get(webClientPubSharesPath+"/{id}/getpdf", s.handleShareGetPDF)
  1463. s.router.Group(func(router chi.Router) {
  1464. if s.binding.OIDC.isEnabled() {
  1465. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebClient))
  1466. }
  1467. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1468. router.Use(jwtAuthenticatorWebClient)
  1469. router.Get(webClientLogoutPath, s.handleWebClientLogout)
  1470. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientFilesPath, s.handleClientGetFiles)
  1471. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientViewPDFPath, s.handleClientViewPDF)
  1472. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientGetPDFPath, s.handleClientGetPDF)
  1473. router.With(s.checkAuthRequirements, s.refreshCookie, verifyCSRFHeader).Get(webClientFilePath, getUserFile)
  1474. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1475. Post(webClientFilePath, uploadUserFile)
  1476. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1477. Post(webClientExistPath, s.handleClientCheckExist)
  1478. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientEditFilePath, s.handleClientEditFile)
  1479. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1480. Delete(webClientFilesPath, deleteUserFile)
  1481. router.With(s.checkAuthRequirements, compressor.Handler, s.refreshCookie).
  1482. Get(webClientDirsPath, s.handleClientGetDirContents)
  1483. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1484. Post(webClientDirsPath, createUserDir)
  1485. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1486. Delete(webClientDirsPath, deleteUserDir)
  1487. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1488. Post(webClientFileActionsPath+"/move", renameUserFsEntry)
  1489. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientWriteDisabled), verifyCSRFHeader).
  1490. Post(webClientFileActionsPath+"/copy", copyUserFsEntry)
  1491. router.With(s.checkAuthRequirements, s.refreshCookie).
  1492. Post(webClientDownloadZipPath, s.handleWebClientDownloadZip)
  1493. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientPingPath, handlePingRequest)
  1494. router.With(s.checkAuthRequirements, s.refreshCookie).Get(webClientProfilePath,
  1495. s.handleClientGetProfile)
  1496. router.With(s.checkAuthRequirements).Post(webClientProfilePath, s.handleWebClientProfilePost)
  1497. router.With(s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1498. Get(webChangeClientPwdPath, s.handleWebClientChangePwd)
  1499. router.With(s.checkHTTPUserPerm(sdk.WebClientPasswordChangeDisabled)).
  1500. Post(webChangeClientPwdPath, s.handleWebClientChangePwdPost)
  1501. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1502. Get(webClientMFAPath, s.handleWebClientMFA)
  1503. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), s.refreshCookie).
  1504. Get(webClientMFAPath+"/qrcode", getQRCode)
  1505. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1506. Post(webClientTOTPGeneratePath, generateTOTPSecret)
  1507. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1508. Post(webClientTOTPValidatePath, validateTOTPPasscode)
  1509. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1510. Post(webClientTOTPSavePath, saveTOTPConfig)
  1511. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader, s.refreshCookie).
  1512. Get(webClientRecoveryCodesPath, getRecoveryCodes)
  1513. router.With(s.checkHTTPUserPerm(sdk.WebClientMFADisabled), verifyCSRFHeader).
  1514. Post(webClientRecoveryCodesPath, generateRecoveryCodes)
  1515. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), compressor.Handler, s.refreshCookie).
  1516. Get(webClientSharesPath+jsonAPISuffix, getAllShares)
  1517. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1518. Get(webClientSharesPath, s.handleClientGetShares)
  1519. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1520. Get(webClientSharePath, s.handleClientAddShareGet)
  1521. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1522. Post(webClientSharePath, s.handleClientAddSharePost)
  1523. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), s.refreshCookie).
  1524. Get(webClientSharePath+"/{id}", s.handleClientUpdateShareGet)
  1525. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled)).
  1526. Post(webClientSharePath+"/{id}", s.handleClientUpdateSharePost)
  1527. router.With(s.checkAuthRequirements, s.checkHTTPUserPerm(sdk.WebClientSharesDisabled), verifyCSRFHeader).
  1528. Delete(webClientSharePath+"/{id}", deleteShare)
  1529. })
  1530. }
  1531. }
  1532. func (s *httpdServer) setupWebAdminRoutes() {
  1533. if s.enableWebAdmin {
  1534. s.router.Get(webBaseAdminPath, func(w http.ResponseWriter, r *http.Request) {
  1535. r.Body = http.MaxBytesReader(w, r.Body, maxLoginBodySize)
  1536. s.redirectToWebPath(w, r, webAdminLoginPath)
  1537. })
  1538. s.router.Get(webAdminLoginPath, s.handleWebAdminLogin)
  1539. if s.binding.OIDC.hasRoles() && !s.binding.isWebAdminOIDCLoginDisabled() {
  1540. s.router.Get(webAdminOIDCLoginPath, s.handleWebAdminOIDCLogin)
  1541. }
  1542. s.router.Get(webOAuth2RedirectPath, s.handleOAuth2TokenRedirect)
  1543. s.router.Get(webAdminSetupPath, s.handleWebAdminSetupGet)
  1544. s.router.Post(webAdminSetupPath, s.handleWebAdminSetupPost)
  1545. if !s.binding.isWebAdminLoginFormDisabled() {
  1546. s.router.Post(webAdminLoginPath, s.handleWebAdminLoginPost)
  1547. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1548. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1549. Get(webAdminTwoFactorPath, s.handleWebAdminTwoFactor)
  1550. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1551. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1552. Post(webAdminTwoFactorPath, s.handleWebAdminTwoFactorPost)
  1553. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1554. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1555. Get(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecovery)
  1556. s.router.With(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie),
  1557. s.jwtAuthenticatorPartial(tokenAudienceWebAdminPartial)).
  1558. Post(webAdminTwoFactorRecoveryPath, s.handleWebAdminTwoFactorRecoveryPost)
  1559. s.router.Get(webAdminForgotPwdPath, s.handleWebAdminForgotPwd)
  1560. s.router.Post(webAdminForgotPwdPath, s.handleWebAdminForgotPwdPost)
  1561. s.router.Get(webAdminResetPwdPath, s.handleWebAdminPasswordReset)
  1562. s.router.Post(webAdminResetPwdPath, s.handleWebAdminPasswordResetPost)
  1563. }
  1564. s.router.Group(func(router chi.Router) {
  1565. if s.binding.OIDC.isEnabled() {
  1566. router.Use(s.oidcTokenAuthenticator(tokenAudienceWebAdmin))
  1567. }
  1568. router.Use(jwtauth.Verify(s.tokenAuth, tokenFromContext, jwtauth.TokenFromCookie))
  1569. router.Use(jwtAuthenticatorWebAdmin)
  1570. router.Get(webLogoutPath, s.handleWebAdminLogout)
  1571. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminProfilePath, s.handleWebAdminProfile)
  1572. router.With(s.requireBuiltinLogin).Post(webAdminProfilePath, s.handleWebAdminProfilePost)
  1573. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webChangeAdminPwdPath, s.handleWebAdminChangePwd)
  1574. router.With(s.requireBuiltinLogin).Post(webChangeAdminPwdPath, s.handleWebAdminChangePwdPost)
  1575. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminMFAPath, s.handleWebAdminMFA)
  1576. router.With(s.refreshCookie, s.requireBuiltinLogin).Get(webAdminMFAPath+"/qrcode", getQRCode)
  1577. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPGeneratePath, generateTOTPSecret)
  1578. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPValidatePath, validateTOTPPasscode)
  1579. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminTOTPSavePath, saveTOTPConfig)
  1580. router.With(verifyCSRFHeader, s.requireBuiltinLogin, s.refreshCookie).Get(webAdminRecoveryCodesPath,
  1581. getRecoveryCodes)
  1582. router.With(verifyCSRFHeader, s.requireBuiltinLogin).Post(webAdminRecoveryCodesPath, generateRecoveryCodes)
  1583. router.With(s.checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  1584. Get(webUsersPath, s.handleGetWebUsers)
  1585. router.With(s.checkPerm(dataprovider.PermAdminViewUsers), compressor.Handler, s.refreshCookie).
  1586. Get(webUsersPath+jsonAPISuffix, getAllUsers)
  1587. router.With(s.checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  1588. Get(webUserPath, s.handleWebAddUserGet)
  1589. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  1590. Get(webUserPath+"/{username}", s.handleWebUpdateUserGet)
  1591. router.With(s.checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, s.handleWebAddUserPost)
  1592. router.With(s.checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}",
  1593. s.handleWebUpdateUserPost)
  1594. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1595. Get(webGroupsPath, s.handleWebGetGroups)
  1596. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), compressor.Handler, s.refreshCookie).
  1597. Get(webGroupsPath+jsonAPISuffix, getAllGroups)
  1598. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1599. Get(webGroupPath, s.handleWebAddGroupGet)
  1600. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(webGroupPath, s.handleWebAddGroupPost)
  1601. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), s.refreshCookie).
  1602. Get(webGroupPath+"/{name}", s.handleWebUpdateGroupGet)
  1603. router.With(s.checkPerm(dataprovider.PermAdminManageGroups)).Post(webGroupPath+"/{name}",
  1604. s.handleWebUpdateGroupPost)
  1605. router.With(s.checkPerm(dataprovider.PermAdminManageGroups), verifyCSRFHeader).
  1606. Delete(webGroupPath+"/{name}", deleteGroup)
  1607. router.With(s.checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1608. Get(webConnectionsPath, s.handleWebGetConnections)
  1609. router.With(s.checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  1610. Get(webConnectionsPath+jsonAPISuffix, getActiveConnections)
  1611. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1612. Get(webFoldersPath, s.handleWebGetFolders)
  1613. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), compressor.Handler, s.refreshCookie).
  1614. Get(webFoldersPath+jsonAPISuffix, getAllFolders)
  1615. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1616. Get(webFolderPath, s.handleWebAddFolderGet)
  1617. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(webFolderPath, s.handleWebAddFolderPost)
  1618. router.With(s.checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  1619. Get(webStatusPath, s.handleWebGetStatus)
  1620. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1621. Get(webAdminsPath, s.handleGetWebAdmins)
  1622. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins), compressor.Handler, s.refreshCookie).
  1623. Get(webAdminsPath+jsonAPISuffix, getAllAdmins)
  1624. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1625. Get(webAdminPath, s.handleWebAddAdminGet)
  1626. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  1627. Get(webAdminPath+"/{username}", s.handleWebUpdateAdminGet)
  1628. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, s.handleWebAddAdminPost)
  1629. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}",
  1630. s.handleWebUpdateAdminPost)
  1631. router.With(s.checkPerm(dataprovider.PermAdminManageAdmins), verifyCSRFHeader).
  1632. Delete(webAdminPath+"/{username}", deleteAdmin)
  1633. router.With(s.checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  1634. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  1635. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), s.refreshCookie).
  1636. Get(webFolderPath+"/{name}", s.handleWebUpdateFolderGet)
  1637. router.With(s.checkPerm(dataprovider.PermAdminManageFolders)).Post(webFolderPath+"/{name}",
  1638. s.handleWebUpdateFolderPost)
  1639. router.With(s.checkPerm(dataprovider.PermAdminManageFolders), verifyCSRFHeader).
  1640. Delete(webFolderPath+"/{name}", deleteFolder)
  1641. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1642. Post(webScanVFolderPath+"/{name}", startFolderQuotaScan)
  1643. router.With(s.checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  1644. Delete(webUserPath+"/{username}", deleteUser)
  1645. router.With(s.checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  1646. Post(webQuotaScanPath+"/{username}", startUserQuotaScan)
  1647. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, s.handleWebMaintenance)
  1648. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
  1649. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, s.handleWebRestore)
  1650. router.With(s.checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1651. Get(webTemplateUser, s.handleWebTemplateUserGet)
  1652. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, s.handleWebTemplateUserPost)
  1653. router.With(s.checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  1654. Get(webTemplateFolder, s.handleWebTemplateFolderGet)
  1655. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateFolder, s.handleWebTemplateFolderPost)
  1656. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderPath, s.handleWebDefenderPage)
  1657. router.With(s.checkPerm(dataprovider.PermAdminViewDefender)).Get(webDefenderHostsPath, getDefenderHosts)
  1658. router.With(s.checkPerm(dataprovider.PermAdminManageDefender)).Delete(webDefenderHostsPath+"/{id}",
  1659. deleteDefenderHostByID)
  1660. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), compressor.Handler, s.refreshCookie).
  1661. Get(webAdminEventActionsPath+jsonAPISuffix, getAllActions)
  1662. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), s.refreshCookie).
  1663. Get(webAdminEventActionsPath, s.handleWebGetEventActions)
  1664. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), s.refreshCookie).
  1665. Get(webAdminEventActionPath, s.handleWebAddEventActionGet)
  1666. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(webAdminEventActionPath,
  1667. s.handleWebAddEventActionPost)
  1668. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), s.refreshCookie).
  1669. Get(webAdminEventActionPath+"/{name}", s.handleWebUpdateEventActionGet)
  1670. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(webAdminEventActionPath+"/{name}",
  1671. s.handleWebUpdateEventActionPost)
  1672. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), verifyCSRFHeader).
  1673. Delete(webAdminEventActionPath+"/{name}", deleteEventAction)
  1674. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), compressor.Handler, s.refreshCookie).
  1675. Get(webAdminEventRulesPath+jsonAPISuffix, getAllRules)
  1676. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), s.refreshCookie).
  1677. Get(webAdminEventRulesPath, s.handleWebGetEventRules)
  1678. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), s.refreshCookie).
  1679. Get(webAdminEventRulePath, s.handleWebAddEventRuleGet)
  1680. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(webAdminEventRulePath,
  1681. s.handleWebAddEventRulePost)
  1682. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), s.refreshCookie).
  1683. Get(webAdminEventRulePath+"/{name}", s.handleWebUpdateEventRuleGet)
  1684. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules)).Post(webAdminEventRulePath+"/{name}",
  1685. s.handleWebUpdateEventRulePost)
  1686. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), verifyCSRFHeader).
  1687. Delete(webAdminEventRulePath+"/{name}", deleteEventRule)
  1688. router.With(s.checkPerm(dataprovider.PermAdminManageEventRules), verifyCSRFHeader).
  1689. Post(webAdminEventRulePath+"/run/{name}", runOnDemandRule)
  1690. router.With(s.checkPerm(dataprovider.PermAdminManageRoles), s.refreshCookie).
  1691. Get(webAdminRolesPath, s.handleWebGetRoles)
  1692. router.With(s.checkPerm(dataprovider.PermAdminManageRoles), compressor.Handler, s.refreshCookie).
  1693. Get(webAdminRolesPath+jsonAPISuffix, getAllRoles)
  1694. router.With(s.checkPerm(dataprovider.PermAdminManageRoles), s.refreshCookie).
  1695. Get(webAdminRolePath, s.handleWebAddRoleGet)
  1696. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Post(webAdminRolePath, s.handleWebAddRolePost)
  1697. router.With(s.checkPerm(dataprovider.PermAdminManageRoles), s.refreshCookie).
  1698. Get(webAdminRolePath+"/{name}", s.handleWebUpdateRoleGet)
  1699. router.With(s.checkPerm(dataprovider.PermAdminManageRoles)).Post(webAdminRolePath+"/{name}",
  1700. s.handleWebUpdateRolePost)
  1701. router.With(s.checkPerm(dataprovider.PermAdminManageRoles), verifyCSRFHeader).
  1702. Delete(webAdminRolePath+"/{name}", deleteRole)
  1703. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), s.refreshCookie).Get(webEventsPath,
  1704. s.handleWebGetEvents)
  1705. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1706. Get(webEventsFsSearchPath, searchFsEvents)
  1707. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1708. Get(webEventsProviderSearchPath, searchProviderEvents)
  1709. router.With(s.checkPerm(dataprovider.PermAdminViewEvents), compressor.Handler, s.refreshCookie).
  1710. Get(webEventsLogSearchPath, searchLogEvents)
  1711. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Get(webIPListsPath, s.handleWebIPListsPage)
  1712. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists), compressor.Handler, s.refreshCookie).
  1713. Get(webIPListsPath+"/{type}", getIPListEntries)
  1714. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists), s.refreshCookie).Get(webIPListPath+"/{type}",
  1715. s.handleWebAddIPListEntryGet)
  1716. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Post(webIPListPath+"/{type}",
  1717. s.handleWebAddIPListEntryPost)
  1718. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists), s.refreshCookie).Get(webIPListPath+"/{type}/{ipornet}",
  1719. s.handleWebUpdateIPListEntryGet)
  1720. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists)).Post(webIPListPath+"/{type}/{ipornet}",
  1721. s.handleWebUpdateIPListEntryPost)
  1722. router.With(s.checkPerm(dataprovider.PermAdminManageIPLists), verifyCSRFHeader).
  1723. Delete(webIPListPath+"/{type}/{ipornet}", deleteIPListEntry)
  1724. router.With(s.checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).Get(webConfigsPath, s.handleWebConfigs)
  1725. router.With(s.checkPerm(dataprovider.PermAdminManageSystem)).Post(webConfigsPath, s.handleWebConfigsPost)
  1726. router.With(s.checkPerm(dataprovider.PermAdminManageSystem), verifyCSRFHeader, s.refreshCookie).
  1727. Post(webConfigsPath+"/smtp/test", testSMTPConfig)
  1728. router.With(s.checkPerm(dataprovider.PermAdminManageSystem), verifyCSRFHeader, s.refreshCookie).
  1729. Post(webOAuth2TokenPath, handleSMTPOAuth2TokenRequestPost)
  1730. })
  1731. }
  1732. }