api_utils.go 12 KB

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