server.go 16 KB

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