api_utils.go 12 KB

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