server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. package httpd
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "time"
  10. "github.com/go-chi/chi"
  11. "github.com/go-chi/chi/middleware"
  12. "github.com/go-chi/jwtauth"
  13. "github.com/go-chi/render"
  14. "github.com/drakkan/sftpgo/common"
  15. "github.com/drakkan/sftpgo/dataprovider"
  16. "github.com/drakkan/sftpgo/logger"
  17. "github.com/drakkan/sftpgo/utils"
  18. "github.com/drakkan/sftpgo/version"
  19. )
  20. var compressor = middleware.NewCompressor(5)
  21. type httpdServer struct {
  22. binding Binding
  23. staticFilesPath string
  24. enableWebAdmin bool
  25. router *chi.Mux
  26. tokenAuth *jwtauth.JWTAuth
  27. }
  28. func newHttpdServer(b Binding, staticFilesPath string, enableWebAdmin bool) *httpdServer {
  29. return &httpdServer{
  30. binding: b,
  31. staticFilesPath: staticFilesPath,
  32. enableWebAdmin: enableWebAdmin && b.EnableWebAdmin,
  33. }
  34. }
  35. func (s *httpdServer) listenAndServe() error {
  36. s.initializeRouter()
  37. httpServer := &http.Server{
  38. Handler: s.router,
  39. ReadTimeout: 60 * time.Second,
  40. WriteTimeout: 60 * time.Second,
  41. IdleTimeout: 120 * time.Second,
  42. MaxHeaderBytes: 1 << 16, // 64KB
  43. ErrorLog: log.New(&logger.StdLoggerWrapper{Sender: logSender}, "", 0),
  44. }
  45. if certMgr != nil && s.binding.EnableHTTPS {
  46. config := &tls.Config{
  47. GetCertificate: certMgr.GetCertificateFunc(),
  48. MinVersion: tls.VersionTLS12,
  49. }
  50. httpServer.TLSConfig = config
  51. if s.binding.ClientAuthType == 1 {
  52. httpServer.TLSConfig.ClientCAs = certMgr.GetRootCAs()
  53. httpServer.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
  54. httpServer.TLSConfig.VerifyConnection = s.verifyTLSConnection
  55. }
  56. return utils.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, true, logSender)
  57. }
  58. return utils.HTTPListenAndServe(httpServer, s.binding.Address, s.binding.Port, false, logSender)
  59. }
  60. func (s *httpdServer) verifyTLSConnection(state tls.ConnectionState) error {
  61. if certMgr != nil {
  62. var clientCrt *x509.Certificate
  63. var clientCrtName string
  64. if len(state.PeerCertificates) > 0 {
  65. clientCrt = state.PeerCertificates[0]
  66. clientCrtName = clientCrt.Subject.String()
  67. }
  68. if len(state.VerifiedChains) == 0 {
  69. logger.Warn(logSender, "", "TLS connection cannot be verified: unable to get verification chain")
  70. return errors.New("TLS connection cannot be verified: unable to get verification chain")
  71. }
  72. for _, verifiedChain := range state.VerifiedChains {
  73. var caCrt *x509.Certificate
  74. if len(verifiedChain) > 0 {
  75. caCrt = verifiedChain[len(verifiedChain)-1]
  76. }
  77. if certMgr.IsRevoked(clientCrt, caCrt) {
  78. logger.Debug(logSender, "", "tls handshake error, client certificate %#v has been revoked", clientCrtName)
  79. return common.ErrCrtRevoked
  80. }
  81. }
  82. }
  83. return nil
  84. }
  85. func (s *httpdServer) refreshCookie(next http.Handler) http.Handler {
  86. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  87. s.checkCookieExpiration(w, r)
  88. next.ServeHTTP(w, r)
  89. })
  90. }
  91. func (s *httpdServer) handleWebLoginPost(w http.ResponseWriter, r *http.Request) {
  92. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  93. if err := r.ParseForm(); err != nil {
  94. renderLoginPage(w, err.Error())
  95. return
  96. }
  97. username := r.Form.Get("username")
  98. password := r.Form.Get("password")
  99. if username == "" || password == "" {
  100. renderLoginPage(w, "Invalid credentials")
  101. return
  102. }
  103. if err := verifyCSRFToken(r.Form.Get(csrfFormToken)); err != nil {
  104. renderLoginPage(w, err.Error())
  105. return
  106. }
  107. admin, err := dataprovider.CheckAdminAndPass(username, password, utils.GetIPFromRemoteAddress(r.RemoteAddr))
  108. if err != nil {
  109. renderLoginPage(w, err.Error())
  110. return
  111. }
  112. if connAddr, ok := r.Context().Value(connAddrKey).(string); ok {
  113. if connAddr != r.RemoteAddr {
  114. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(connAddr)) {
  115. renderLoginPage(w, fmt.Sprintf("Login from IP %v is not allowed", connAddr))
  116. return
  117. }
  118. }
  119. }
  120. c := jwtTokenClaims{
  121. Username: admin.Username,
  122. Permissions: admin.Permissions,
  123. Signature: admin.GetSignature(),
  124. }
  125. err = c.createAndSetCookie(w, r, s.tokenAuth)
  126. if err != nil {
  127. renderLoginPage(w, err.Error())
  128. return
  129. }
  130. http.Redirect(w, r, webUsersPath, http.StatusFound)
  131. }
  132. func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
  133. invalidateToken(r)
  134. sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
  135. }
  136. func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
  137. username, password, ok := r.BasicAuth()
  138. if !ok {
  139. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  140. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  141. return
  142. }
  143. admin, err := dataprovider.CheckAdminAndPass(username, password, utils.GetIPFromRemoteAddress(r.RemoteAddr))
  144. if err != nil {
  145. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  146. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  147. return
  148. }
  149. s.checkAddrAndSendToken(w, r, admin)
  150. }
  151. func (s *httpdServer) checkAddrAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin) {
  152. if connAddr, ok := r.Context().Value(connAddrKey).(string); ok {
  153. if connAddr != r.RemoteAddr {
  154. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(connAddr)) {
  155. sendAPIResponse(w, r, nil, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  156. return
  157. }
  158. }
  159. }
  160. c := jwtTokenClaims{
  161. Username: admin.Username,
  162. Permissions: admin.Permissions,
  163. Signature: admin.GetSignature(),
  164. }
  165. resp, err := c.createTokenResponse(s.tokenAuth, tokenAudienceAPI)
  166. if err != nil {
  167. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  168. return
  169. }
  170. render.JSON(w, r, resp)
  171. }
  172. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  173. token, claims, err := jwtauth.FromContext(r.Context())
  174. if err != nil {
  175. return
  176. }
  177. tokenClaims := jwtTokenClaims{}
  178. tokenClaims.Decode(claims)
  179. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  180. return
  181. }
  182. if time.Until(token.Expiration()) > tokenRefreshMin {
  183. return
  184. }
  185. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  186. if err != nil {
  187. return
  188. }
  189. if admin.Status != 1 {
  190. logger.Debug(logSender, "", "admin %#v is disabled, unable to refresh cookie", admin.Username)
  191. return
  192. }
  193. if admin.GetSignature() != tokenClaims.Signature {
  194. logger.Debug(logSender, "", "signature mismatch for admin %#v, unable to refresh cookie", admin.Username)
  195. return
  196. }
  197. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(r.RemoteAddr)) {
  198. logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie", admin.Username, r.RemoteAddr)
  199. return
  200. }
  201. if connAddr, ok := r.Context().Value(connAddrKey).(string); ok {
  202. if connAddr != r.RemoteAddr {
  203. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(connAddr)) {
  204. logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie",
  205. admin.Username, connAddr)
  206. return
  207. }
  208. }
  209. }
  210. logger.Debug(logSender, "", "cookie refreshed for admin %#v", admin.Username)
  211. tokenClaims.createAndSetCookie(w, r, s.tokenAuth) //nolint:errcheck
  212. }
  213. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  214. token, _, err := jwtauth.FromContext(r.Context())
  215. if token == nil || err != nil {
  216. _, err = r.Cookie("jwt")
  217. if err != nil {
  218. return r
  219. }
  220. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  221. ctx := jwtauth.NewContext(r.Context(), token, err)
  222. return r.WithContext(ctx)
  223. }
  224. return r
  225. }
  226. func (s *httpdServer) initializeRouter() {
  227. s.tokenAuth = jwtauth.New("HS256", utils.GenerateRandomBytes(32), nil)
  228. s.router = chi.NewRouter()
  229. s.router.Use(saveConnectionAddress)
  230. s.router.Use(middleware.GetHead)
  231. s.router.Group(func(r chi.Router) {
  232. r.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  233. render.PlainText(w, r, "ok")
  234. })
  235. })
  236. s.router.Group(func(router chi.Router) {
  237. router.Use(middleware.RequestID)
  238. router.Use(middleware.RealIP)
  239. router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  240. router.Use(middleware.Recoverer)
  241. router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  242. if s.enableWebAdmin && isWebAdminRequest(r) {
  243. r = s.updateContextFromCookie(r)
  244. renderNotFoundPage(w, r, nil)
  245. return
  246. }
  247. sendAPIResponse(w, r, nil, "Not Found", http.StatusNotFound)
  248. }))
  249. router.Get(tokenPath, s.getToken)
  250. router.Group(func(router chi.Router) {
  251. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromHeader))
  252. router.Use(jwtAuthenticator)
  253. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  254. render.JSON(w, r, version.Get())
  255. })
  256. router.Get(logoutPath, s.logout)
  257. router.Put(adminPwdPath, changeAdminPassword)
  258. router.With(checkPerm(dataprovider.PermAdminViewServerStatus)).
  259. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  260. render.JSON(w, r, getServicesStatus())
  261. })
  262. router.With(checkPerm(dataprovider.PermAdminViewConnections)).
  263. Get(activeConnectionsPath, func(w http.ResponseWriter, r *http.Request) {
  264. render.JSON(w, r, common.Connections.GetStats())
  265. })
  266. router.With(checkPerm(dataprovider.PermAdminCloseConnections)).
  267. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  268. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanPath, getQuotaScans)
  269. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanPath, startQuotaScan)
  270. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanVFolderPath, getVFolderQuotaScans)
  271. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanVFolderPath, startVFolderQuotaScan)
  272. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  273. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  274. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername)
  275. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  276. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  277. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath, getFolders)
  278. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath+"/{name}", getFolderByName)
  279. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(folderPath, addFolder)
  280. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(folderPath+"/{name}", updateFolder)
  281. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(folderPath+"/{name}", deleteFolder)
  282. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(dumpDataPath, dumpData)
  283. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(loadDataPath, loadData)
  284. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(loadDataPath, loadDataFromRequest)
  285. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateUsedQuotaPath, updateUserQuotaUsage)
  286. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateFolderUsedQuotaPath, updateVFolderQuotaUsage)
  287. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderBanTime, getBanTime)
  288. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderScore, getScore)
  289. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Post(defenderUnban, unban)
  290. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
  291. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
  292. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
  293. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
  294. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
  295. })
  296. if s.enableWebAdmin {
  297. router.Get("/", func(w http.ResponseWriter, r *http.Request) {
  298. http.Redirect(w, r, webLoginPath, http.StatusMovedPermanently)
  299. })
  300. router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  301. http.Redirect(w, r, webLoginPath, http.StatusMovedPermanently)
  302. })
  303. router.Get(webLoginPath, handleWebLogin)
  304. router.Post(webLoginPath, s.handleWebLoginPost)
  305. router.Group(func(router chi.Router) {
  306. router.Use(jwtauth.Verify(s.tokenAuth, jwtauth.TokenFromCookie))
  307. router.Use(jwtAuthenticatorWeb)
  308. router.Get(webLogoutPath, handleWebLogout)
  309. router.With(s.refreshCookie).Get(webChangeAdminPwdPath, handleWebAdminChangePwd)
  310. router.Post(webChangeAdminPwdPath, handleWebAdminChangePwdPost)
  311. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  312. Get(webUsersPath, handleGetWebUsers)
  313. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  314. Get(webUserPath, handleWebAddUserGet)
  315. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  316. Get(webUserPath+"/{username}", handleWebUpdateUserGet)
  317. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, handleWebAddUserPost)
  318. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}", handleWebUpdateUserPost)
  319. router.With(checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  320. Get(webConnectionsPath, handleWebGetConnections)
  321. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  322. Get(webFoldersPath, handleWebGetFolders)
  323. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  324. Get(webFolderPath, handleWebAddFolderGet)
  325. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webFolderPath, handleWebAddFolderPost)
  326. router.With(checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  327. Get(webStatusPath, handleWebGetStatus)
  328. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  329. Get(webAdminsPath, handleGetWebAdmins)
  330. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  331. Get(webAdminPath, handleWebAddAdminGet)
  332. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  333. Get(webAdminPath+"/{username}", handleWebUpdateAdminGet)
  334. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, handleWebAddAdminPost)
  335. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}", handleWebUpdateAdminPost)
  336. router.With(checkPerm(dataprovider.PermAdminManageAdmins), verifyCSRFHeader).
  337. Delete(webAdminPath+"/{username}", deleteAdmin)
  338. router.With(checkPerm(dataprovider.PermAdminCloseConnections), verifyCSRFHeader).
  339. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  340. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  341. Get(webFolderPath+"/{name}", handleWebUpdateFolderGet)
  342. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webFolderPath+"/{name}", handleWebUpdateFolderPost)
  343. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  344. Delete(webFolderPath+"/{name}", deleteFolder)
  345. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  346. Post(webScanVFolderPath, startVFolderQuotaScan)
  347. router.With(checkPerm(dataprovider.PermAdminDeleteUsers), verifyCSRFHeader).
  348. Delete(webUserPath+"/{username}", deleteUser)
  349. router.With(checkPerm(dataprovider.PermAdminQuotaScans), verifyCSRFHeader).
  350. Post(webQuotaScanPath, startQuotaScan)
  351. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, handleWebMaintenance)
  352. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
  353. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, handleWebRestore)
  354. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  355. Get(webTemplateUser, handleWebTemplateUserGet)
  356. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, handleWebTemplateUserPost)
  357. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  358. Get(webTemplateFolder, handleWebTemplateFolderGet)
  359. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateFolder, handleWebTemplateFolderPost)
  360. })
  361. router.Group(func(router chi.Router) {
  362. router.Use(compressor.Handler)
  363. fileServer(router, webStaticFilesPath, http.Dir(s.staticFilesPath))
  364. })
  365. }
  366. })
  367. }