server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. admin, err := dataprovider.CheckAdminAndPass(username, password, utils.GetIPFromRemoteAddress(r.RemoteAddr))
  103. if err != nil {
  104. renderLoginPage(w, err.Error())
  105. return
  106. }
  107. if connAddr, ok := r.Context().Value(connAddrKey).(string); ok {
  108. if connAddr != r.RemoteAddr {
  109. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(connAddr)) {
  110. renderLoginPage(w, fmt.Sprintf("Login from IP %v is not allowed", connAddr))
  111. return
  112. }
  113. }
  114. }
  115. c := jwtTokenClaims{
  116. Username: admin.Username,
  117. Permissions: admin.Permissions,
  118. Signature: admin.GetSignature(),
  119. }
  120. err = c.createAndSetCookie(w, r, s.tokenAuth)
  121. if err != nil {
  122. renderLoginPage(w, err.Error())
  123. return
  124. }
  125. http.Redirect(w, r, webUsersPath, http.StatusFound)
  126. }
  127. func (s *httpdServer) logout(w http.ResponseWriter, r *http.Request) {
  128. invalidateToken(r)
  129. sendAPIResponse(w, r, nil, "Your token has been invalidated", http.StatusOK)
  130. }
  131. func (s *httpdServer) getToken(w http.ResponseWriter, r *http.Request) {
  132. username, password, ok := r.BasicAuth()
  133. if !ok {
  134. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  135. sendAPIResponse(w, r, nil, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  136. return
  137. }
  138. admin, err := dataprovider.CheckAdminAndPass(username, password, utils.GetIPFromRemoteAddress(r.RemoteAddr))
  139. if err != nil {
  140. w.Header().Set(common.HTTPAuthenticationHeader, basicRealm)
  141. sendAPIResponse(w, r, err, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  142. return
  143. }
  144. s.checkAddrAndSendToken(w, r, admin)
  145. }
  146. func (s *httpdServer) checkAddrAndSendToken(w http.ResponseWriter, r *http.Request, admin dataprovider.Admin) {
  147. if connAddr, ok := r.Context().Value(connAddrKey).(string); ok {
  148. if connAddr != r.RemoteAddr {
  149. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(connAddr)) {
  150. sendAPIResponse(w, r, nil, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  151. return
  152. }
  153. }
  154. }
  155. c := jwtTokenClaims{
  156. Username: admin.Username,
  157. Permissions: admin.Permissions,
  158. Signature: admin.GetSignature(),
  159. }
  160. resp, err := c.createTokenResponse(s.tokenAuth)
  161. if err != nil {
  162. sendAPIResponse(w, r, err, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  163. return
  164. }
  165. render.JSON(w, r, resp)
  166. }
  167. func (s *httpdServer) checkCookieExpiration(w http.ResponseWriter, r *http.Request) {
  168. token, claims, err := jwtauth.FromContext(r.Context())
  169. if err != nil {
  170. return
  171. }
  172. tokenClaims := jwtTokenClaims{}
  173. tokenClaims.Decode(claims)
  174. if tokenClaims.Username == "" || tokenClaims.Signature == "" {
  175. return
  176. }
  177. if time.Until(token.Expiration()) > tokenRefreshMin {
  178. return
  179. }
  180. admin, err := dataprovider.AdminExists(tokenClaims.Username)
  181. if err != nil {
  182. return
  183. }
  184. if admin.Status != 1 {
  185. logger.Debug(logSender, "", "admin %#v is disabled, unable to refresh cookie", admin.Username)
  186. return
  187. }
  188. if admin.GetSignature() != tokenClaims.Signature {
  189. logger.Debug(logSender, "", "signature mismatch for admin %#v, unable to refresh cookie", admin.Username)
  190. return
  191. }
  192. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(r.RemoteAddr)) {
  193. logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie", admin.Username, r.RemoteAddr)
  194. return
  195. }
  196. if connAddr, ok := r.Context().Value(connAddrKey).(string); ok {
  197. if connAddr != r.RemoteAddr {
  198. if !admin.CanLoginFromIP(utils.GetIPFromRemoteAddress(connAddr)) {
  199. logger.Debug(logSender, "", "admin %#v cannot login from %v, unable to refresh cookie",
  200. admin.Username, connAddr)
  201. return
  202. }
  203. }
  204. }
  205. logger.Debug(logSender, "", "cookie refreshed for admin %#v", admin.Username)
  206. tokenClaims.createAndSetCookie(w, r, s.tokenAuth) //nolint:errcheck
  207. }
  208. func (s *httpdServer) updateContextFromCookie(r *http.Request) *http.Request {
  209. token, _, err := jwtauth.FromContext(r.Context())
  210. if token == nil || err != nil {
  211. _, err = r.Cookie("jwt")
  212. if err != nil {
  213. return r
  214. }
  215. token, err = jwtauth.VerifyRequest(s.tokenAuth, r, jwtauth.TokenFromCookie)
  216. ctx := jwtauth.NewContext(r.Context(), token, err)
  217. return r.WithContext(ctx)
  218. }
  219. return r
  220. }
  221. func (s *httpdServer) initializeRouter() {
  222. s.tokenAuth = jwtauth.New("HS256", utils.GenerateRandomBytes(32), nil)
  223. s.router = chi.NewRouter()
  224. s.router.Use(saveConnectionAddress)
  225. s.router.Use(middleware.GetHead)
  226. s.router.Group(func(r chi.Router) {
  227. r.Get(healthzPath, func(w http.ResponseWriter, r *http.Request) {
  228. render.PlainText(w, r, "ok")
  229. })
  230. })
  231. s.router.Group(func(router chi.Router) {
  232. router.Use(middleware.RequestID)
  233. router.Use(middleware.RealIP)
  234. router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  235. router.Use(middleware.Recoverer)
  236. router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  237. if s.enableWebAdmin && isWebAdminRequest(r) {
  238. r = s.updateContextFromCookie(r)
  239. renderNotFoundPage(w, r, nil)
  240. return
  241. }
  242. sendAPIResponse(w, r, nil, "Not Found", http.StatusNotFound)
  243. }))
  244. router.Get(tokenPath, s.getToken)
  245. router.Group(func(router chi.Router) {
  246. router.Use(jwtauth.Verifier(s.tokenAuth))
  247. router.Use(jwtAuthenticator)
  248. router.Get(versionPath, func(w http.ResponseWriter, r *http.Request) {
  249. render.JSON(w, r, version.Get())
  250. })
  251. router.Get(logoutPath, s.logout)
  252. router.Put(adminPwdPath, changeAdminPassword)
  253. router.With(checkPerm(dataprovider.PermAdminViewServerStatus)).
  254. Get(serverStatusPath, func(w http.ResponseWriter, r *http.Request) {
  255. render.JSON(w, r, getServicesStatus())
  256. })
  257. router.With(checkPerm(dataprovider.PermAdminViewConnections)).
  258. Get(activeConnectionsPath, func(w http.ResponseWriter, r *http.Request) {
  259. render.JSON(w, r, common.Connections.GetStats())
  260. })
  261. router.With(checkPerm(dataprovider.PermAdminCloseConnections)).
  262. Delete(activeConnectionsPath+"/{connectionID}", handleCloseConnection)
  263. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanPath, getQuotaScans)
  264. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanPath, startQuotaScan)
  265. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Get(quotaScanVFolderPath, getVFolderQuotaScans)
  266. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(quotaScanVFolderPath, startVFolderQuotaScan)
  267. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath, getUsers)
  268. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(userPath, addUser)
  269. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(userPath+"/{username}", getUserByUsername)
  270. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(userPath+"/{username}", updateUser)
  271. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(userPath+"/{username}", deleteUser)
  272. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath, getFolders)
  273. router.With(checkPerm(dataprovider.PermAdminViewUsers)).Get(folderPath+"/{name}", getFolderByName)
  274. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(folderPath, addFolder)
  275. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(folderPath+"/{name}", updateFolder)
  276. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(folderPath+"/{name}", deleteFolder)
  277. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(dumpDataPath, dumpData)
  278. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(loadDataPath, loadData)
  279. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(loadDataPath, loadDataFromRequest)
  280. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateUsedQuotaPath, updateUserQuotaUsage)
  281. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Put(updateFolderUsedQuotaPath, updateVFolderQuotaUsage)
  282. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderBanTime, getBanTime)
  283. router.With(checkPerm(dataprovider.PermAdminViewDefender)).Get(defenderScore, getScore)
  284. router.With(checkPerm(dataprovider.PermAdminManageDefender)).Post(defenderUnban, unban)
  285. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath, getAdmins)
  286. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(adminPath, addAdmin)
  287. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Get(adminPath+"/{username}", getAdminByUsername)
  288. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Put(adminPath+"/{username}", updateAdmin)
  289. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(adminPath+"/{username}", deleteAdmin)
  290. })
  291. if s.enableWebAdmin {
  292. router.Get("/", func(w http.ResponseWriter, r *http.Request) {
  293. http.Redirect(w, r, webLoginPath, http.StatusMovedPermanently)
  294. })
  295. router.Get(webBasePath, func(w http.ResponseWriter, r *http.Request) {
  296. http.Redirect(w, r, webLoginPath, http.StatusMovedPermanently)
  297. })
  298. router.Get(webLoginPath, handleWebLogin)
  299. router.Post(webLoginPath, s.handleWebLoginPost)
  300. router.Group(func(router chi.Router) {
  301. router.Use(jwtauth.Verifier(s.tokenAuth))
  302. router.Use(jwtAuthenticatorWeb)
  303. router.Get(webLogoutPath, handleWebLogout)
  304. router.With(s.refreshCookie).Get(webChangeAdminPwdPath, handleWebAdminChangePwd)
  305. router.Post(webChangeAdminPwdPath, handleWebAdminChangePwdPost)
  306. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  307. Get(webUsersPath, handleGetWebUsers)
  308. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  309. Get(webUserPath, handleWebAddUserGet)
  310. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  311. Get(webUserPath+"/{username}", handleWebUpdateUserGet)
  312. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webUserPath, handleWebAddUserPost)
  313. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webUserPath+"/{username}", handleWebUpdateUserPost)
  314. router.With(checkPerm(dataprovider.PermAdminViewConnections), s.refreshCookie).
  315. Get(webConnectionsPath, handleWebGetConnections)
  316. router.With(checkPerm(dataprovider.PermAdminViewUsers), s.refreshCookie).
  317. Get(webFoldersPath, handleWebGetFolders)
  318. router.With(checkPerm(dataprovider.PermAdminAddUsers), s.refreshCookie).
  319. Get(webFolderPath, handleWebAddFolderGet)
  320. router.With(checkPerm(dataprovider.PermAdminAddUsers)).Post(webFolderPath, handleWebAddFolderPost)
  321. router.With(checkPerm(dataprovider.PermAdminViewServerStatus), s.refreshCookie).
  322. Get(webStatusPath, handleWebGetStatus)
  323. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  324. Get(webAdminsPath, handleGetWebAdmins)
  325. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  326. Get(webAdminPath, handleWebAddAdminGet)
  327. router.With(checkPerm(dataprovider.PermAdminManageAdmins), s.refreshCookie).
  328. Get(webAdminPath+"/{username}", handleWebUpdateAdminGet)
  329. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath, handleWebAddAdminPost)
  330. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Post(webAdminPath+"/{username}", handleWebUpdateAdminPost)
  331. router.With(checkPerm(dataprovider.PermAdminManageAdmins)).Delete(webAdminPath+"/{username}", deleteAdmin)
  332. router.With(checkPerm(dataprovider.PermAdminCloseConnections)).
  333. Delete(webConnectionsPath+"/{connectionID}", handleCloseConnection)
  334. router.With(checkPerm(dataprovider.PermAdminChangeUsers), s.refreshCookie).
  335. Get(webFolderPath+"/{name}", handleWebUpdateFolderGet)
  336. router.With(checkPerm(dataprovider.PermAdminChangeUsers)).Post(webFolderPath+"/{name}", handleWebUpdateFolderPost)
  337. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(webFolderPath+"/{name}", deleteFolder)
  338. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(webScanVFolderPath, startVFolderQuotaScan)
  339. router.With(checkPerm(dataprovider.PermAdminDeleteUsers)).Delete(webUserPath+"/{username}", deleteUser)
  340. router.With(checkPerm(dataprovider.PermAdminQuotaScans)).Post(webQuotaScanPath, startQuotaScan)
  341. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webMaintenancePath, handleWebMaintenance)
  342. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Get(webBackupPath, dumpData)
  343. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webRestorePath, handleWebRestore)
  344. router.With(checkPerm(dataprovider.PermAdminManageSystem), s.refreshCookie).
  345. Get(webTemplateUser, handleWebTemplateUserGet)
  346. router.With(checkPerm(dataprovider.PermAdminManageSystem)).Post(webTemplateUser, handleWebTemplateUserPost)
  347. })
  348. router.Group(func(router chi.Router) {
  349. compressor := middleware.NewCompressor(5)
  350. router.Use(compressor.Handler)
  351. fileServer(router, webStaticFilesPath, http.Dir(s.staticFilesPath))
  352. })
  353. }
  354. })
  355. }