api_utils.go 13 KB

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