api_utils.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. package httpd
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "mime"
  8. "net/http"
  9. "os"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/go-chi/render"
  15. "github.com/klauspost/compress/zip"
  16. "github.com/drakkan/sftpgo/v2/common"
  17. "github.com/drakkan/sftpgo/v2/dataprovider"
  18. "github.com/drakkan/sftpgo/v2/logger"
  19. "github.com/drakkan/sftpgo/v2/metric"
  20. "github.com/drakkan/sftpgo/v2/util"
  21. )
  22. type pwdChange struct {
  23. CurrentPassword string `json:"current_password"`
  24. NewPassword string `json:"new_password"`
  25. }
  26. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  27. var errorString string
  28. if err != nil {
  29. errorString = err.Error()
  30. }
  31. resp := apiResponse{
  32. Error: errorString,
  33. Message: message,
  34. }
  35. ctx := context.WithValue(r.Context(), render.StatusCtxKey, code)
  36. render.JSON(w, r.WithContext(ctx), resp)
  37. }
  38. func getRespStatus(err error) int {
  39. if _, ok := err.(*util.ValidationError); ok {
  40. return http.StatusBadRequest
  41. }
  42. if _, ok := err.(*util.MethodDisabledError); ok {
  43. return http.StatusForbidden
  44. }
  45. if _, ok := err.(*util.RecordNotFoundError); ok {
  46. return http.StatusNotFound
  47. }
  48. if os.IsNotExist(err) {
  49. return http.StatusBadRequest
  50. }
  51. return http.StatusInternalServerError
  52. }
  53. func getMappedStatusCode(err error) int {
  54. var statusCode int
  55. switch err {
  56. case os.ErrPermission:
  57. statusCode = http.StatusForbidden
  58. case os.ErrNotExist:
  59. statusCode = http.StatusNotFound
  60. default:
  61. statusCode = http.StatusInternalServerError
  62. }
  63. return statusCode
  64. }
  65. func handleCloseConnection(w http.ResponseWriter, r *http.Request) {
  66. connectionID := getURLParam(r, "connectionID")
  67. if connectionID == "" {
  68. sendAPIResponse(w, r, nil, "connectionID is mandatory", http.StatusBadRequest)
  69. return
  70. }
  71. if common.Connections.Close(connectionID) {
  72. sendAPIResponse(w, r, nil, "Connection closed", http.StatusOK)
  73. } else {
  74. sendAPIResponse(w, r, nil, "Not Found", http.StatusNotFound)
  75. }
  76. }
  77. func getSearchFilters(w http.ResponseWriter, r *http.Request) (int, int, string, error) {
  78. var err error
  79. limit := 100
  80. offset := 0
  81. order := dataprovider.OrderASC
  82. if _, ok := r.URL.Query()["limit"]; ok {
  83. limit, err = strconv.Atoi(r.URL.Query().Get("limit"))
  84. if err != nil {
  85. err = errors.New("invalid limit")
  86. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  87. return limit, offset, order, err
  88. }
  89. if limit > 500 {
  90. limit = 500
  91. }
  92. }
  93. if _, ok := r.URL.Query()["offset"]; ok {
  94. offset, err = strconv.Atoi(r.URL.Query().Get("offset"))
  95. if err != nil {
  96. err = errors.New("invalid offset")
  97. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  98. return limit, offset, order, err
  99. }
  100. }
  101. if _, ok := r.URL.Query()["order"]; ok {
  102. order = r.URL.Query().Get("order")
  103. if order != dataprovider.OrderASC && order != dataprovider.OrderDESC {
  104. err = errors.New("invalid order")
  105. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  106. return limit, offset, order, err
  107. }
  108. }
  109. return limit, offset, order, err
  110. }
  111. func renderCompressedFiles(w http.ResponseWriter, conn *Connection, baseDir string, files []string) {
  112. w.Header().Set("Content-Type", "application/zip")
  113. w.Header().Set("Accept-Ranges", "none")
  114. w.Header().Set("Content-Transfer-Encoding", "binary")
  115. w.WriteHeader(http.StatusOK)
  116. wr := zip.NewWriter(w)
  117. for _, file := range files {
  118. fullPath := path.Join(baseDir, file)
  119. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  120. panic(http.ErrAbortHandler)
  121. }
  122. }
  123. if err := wr.Close(); err != nil {
  124. conn.Log(logger.LevelWarn, "unable to close zip file: %v", err)
  125. panic(http.ErrAbortHandler)
  126. }
  127. }
  128. func addZipEntry(wr *zip.Writer, conn *Connection, entryPath, baseDir string) error {
  129. info, err := conn.Stat(entryPath, 1)
  130. if err != nil {
  131. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, stat error: %v", entryPath, err)
  132. return err
  133. }
  134. if info.IsDir() {
  135. _, err := wr.Create(getZipEntryName(entryPath, baseDir) + "/")
  136. if err != nil {
  137. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  138. return err
  139. }
  140. contents, err := conn.ReadDir(entryPath)
  141. if err != nil {
  142. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, read dir error: %v", entryPath, err)
  143. return err
  144. }
  145. for _, info := range contents {
  146. fullPath := path.Join(entryPath, info.Name())
  147. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  148. return err
  149. }
  150. }
  151. return nil
  152. }
  153. if !info.Mode().IsRegular() {
  154. // we only allow regular files
  155. conn.Log(logger.LevelDebug, "skipping zip entry for non regular file %#v", entryPath)
  156. return nil
  157. }
  158. reader, err := conn.getFileReader(entryPath, 0, http.MethodGet)
  159. if err != nil {
  160. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, cannot open file: %v", entryPath, err)
  161. return err
  162. }
  163. defer reader.Close()
  164. f, err := wr.Create(getZipEntryName(entryPath, baseDir))
  165. if err != nil {
  166. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  167. return err
  168. }
  169. _, err = io.Copy(f, reader)
  170. return err
  171. }
  172. func getZipEntryName(entryPath, baseDir string) string {
  173. entryPath = strings.TrimPrefix(entryPath, baseDir)
  174. return strings.TrimPrefix(entryPath, "/")
  175. }
  176. func downloadFile(w http.ResponseWriter, r *http.Request, connection *Connection, name string, info os.FileInfo) (int, error) {
  177. var err error
  178. rangeHeader := r.Header.Get("Range")
  179. if rangeHeader != "" && checkIfRange(r, info.ModTime()) == condFalse {
  180. rangeHeader = ""
  181. }
  182. offset := int64(0)
  183. size := info.Size()
  184. responseStatus := http.StatusOK
  185. if strings.HasPrefix(rangeHeader, "bytes=") {
  186. if strings.Contains(rangeHeader, ",") {
  187. return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("unsupported range %#v", rangeHeader)
  188. }
  189. offset, size, err = parseRangeRequest(rangeHeader[6:], size)
  190. if err != nil {
  191. return http.StatusRequestedRangeNotSatisfiable, err
  192. }
  193. responseStatus = http.StatusPartialContent
  194. }
  195. reader, err := connection.getFileReader(name, offset, r.Method)
  196. if err != nil {
  197. return getMappedStatusCode(err), fmt.Errorf("unable to read file %#v: %v", name, err)
  198. }
  199. defer reader.Close()
  200. w.Header().Set("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
  201. if checkPreconditions(w, r, info.ModTime()) {
  202. return 0, fmt.Errorf("%v", http.StatusText(http.StatusPreconditionFailed))
  203. }
  204. ctype := mime.TypeByExtension(path.Ext(name))
  205. if ctype == "" {
  206. ctype = "application/octet-stream"
  207. }
  208. if responseStatus == http.StatusPartialContent {
  209. w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, info.Size()))
  210. }
  211. w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
  212. w.Header().Set("Content-Type", ctype)
  213. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%#v", path.Base(name)))
  214. w.Header().Set("Accept-Ranges", "bytes")
  215. w.WriteHeader(responseStatus)
  216. if r.Method != http.MethodHead {
  217. io.CopyN(w, reader, size) //nolint:errcheck
  218. }
  219. return http.StatusOK, nil
  220. }
  221. func checkPreconditions(w http.ResponseWriter, r *http.Request, modtime time.Time) bool {
  222. if checkIfUnmodifiedSince(r, modtime) == condFalse {
  223. w.WriteHeader(http.StatusPreconditionFailed)
  224. return true
  225. }
  226. if checkIfModifiedSince(r, modtime) == condFalse {
  227. w.WriteHeader(http.StatusNotModified)
  228. return true
  229. }
  230. return false
  231. }
  232. func checkIfUnmodifiedSince(r *http.Request, modtime time.Time) condResult {
  233. ius := r.Header.Get("If-Unmodified-Since")
  234. if ius == "" || isZeroTime(modtime) {
  235. return condNone
  236. }
  237. t, err := http.ParseTime(ius)
  238. if err != nil {
  239. return condNone
  240. }
  241. // The Last-Modified header truncates sub-second precision so
  242. // the modtime needs to be truncated too.
  243. modtime = modtime.Truncate(time.Second)
  244. if modtime.Before(t) || modtime.Equal(t) {
  245. return condTrue
  246. }
  247. return condFalse
  248. }
  249. func checkIfModifiedSince(r *http.Request, modtime time.Time) condResult {
  250. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  251. return condNone
  252. }
  253. ims := r.Header.Get("If-Modified-Since")
  254. if ims == "" || isZeroTime(modtime) {
  255. return condNone
  256. }
  257. t, err := http.ParseTime(ims)
  258. if err != nil {
  259. return condNone
  260. }
  261. // The Last-Modified header truncates sub-second precision so
  262. // the modtime needs to be truncated too.
  263. modtime = modtime.Truncate(time.Second)
  264. if modtime.Before(t) || modtime.Equal(t) {
  265. return condFalse
  266. }
  267. return condTrue
  268. }
  269. func checkIfRange(r *http.Request, modtime time.Time) condResult {
  270. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  271. return condNone
  272. }
  273. ir := r.Header.Get("If-Range")
  274. if ir == "" {
  275. return condNone
  276. }
  277. if modtime.IsZero() {
  278. return condFalse
  279. }
  280. t, err := http.ParseTime(ir)
  281. if err != nil {
  282. return condFalse
  283. }
  284. if modtime.Add(60 * time.Second).Before(t) {
  285. return condTrue
  286. }
  287. return condFalse
  288. }
  289. func parseRangeRequest(bytesRange string, size int64) (int64, int64, error) {
  290. var start, end int64
  291. var err error
  292. values := strings.Split(bytesRange, "-")
  293. if values[0] == "" {
  294. start = -1
  295. } else {
  296. start, err = strconv.ParseInt(values[0], 10, 64)
  297. if err != nil {
  298. return start, size, err
  299. }
  300. }
  301. if len(values) >= 2 {
  302. if values[1] != "" {
  303. end, err = strconv.ParseInt(values[1], 10, 64)
  304. if err != nil {
  305. return start, size, err
  306. }
  307. if end >= size {
  308. end = size - 1
  309. }
  310. }
  311. }
  312. if start == -1 && end == 0 {
  313. return 0, 0, fmt.Errorf("unsupported range %#v", bytesRange)
  314. }
  315. if end > 0 {
  316. if start == -1 {
  317. // we have something like -500
  318. start = size - end
  319. size = end
  320. // start cannit be < 0 here, we did end = size -1 above
  321. } else {
  322. // we have something like 500-600
  323. size = end - start + 1
  324. if size < 0 {
  325. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  326. }
  327. }
  328. return start, size, nil
  329. }
  330. // we have something like 500-
  331. size -= start
  332. if size < 0 {
  333. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  334. }
  335. return start, size, err
  336. }
  337. func updateLoginMetrics(user *dataprovider.User, ip string, err error) {
  338. metric.AddLoginAttempt(dataprovider.LoginMethodPassword)
  339. if err != nil && err != common.ErrInternalFailure {
  340. logger.ConnectionFailedLog(user.Username, ip, dataprovider.LoginMethodPassword, common.ProtocolHTTP, err.Error())
  341. event := common.HostEventLoginFailed
  342. if _, ok := err.(*util.RecordNotFoundError); ok {
  343. event = common.HostEventUserNotFound
  344. }
  345. common.AddDefenderEvent(ip, event)
  346. }
  347. metric.AddLoginResult(dataprovider.LoginMethodPassword, err)
  348. dataprovider.ExecutePostLoginHook(user, dataprovider.LoginMethodPassword, ip, common.ProtocolHTTP, err)
  349. }
  350. func checkHTTPClientUser(user *dataprovider.User, r *http.Request, connectionID string) error {
  351. if util.IsStringInSlice(common.ProtocolHTTP, user.Filters.DeniedProtocols) {
  352. logger.Debug(logSender, connectionID, "cannot login user %#v, protocol HTTP is not allowed", user.Username)
  353. return fmt.Errorf("protocol HTTP is not allowed for user %#v", user.Username)
  354. }
  355. if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, nil) {
  356. logger.Debug(logSender, connectionID, "cannot login user %#v, password login method is not allowed", user.Username)
  357. return fmt.Errorf("login method password is not allowed for user %#v", user.Username)
  358. }
  359. if user.MaxSessions > 0 {
  360. activeSessions := common.Connections.GetActiveSessions(user.Username)
  361. if activeSessions >= user.MaxSessions {
  362. logger.Debug(logSender, connectionID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  363. activeSessions, user.MaxSessions)
  364. return fmt.Errorf("too many open sessions: %v", activeSessions)
  365. }
  366. }
  367. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  368. logger.Debug(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  369. return fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
  370. }
  371. return nil
  372. }