api_utils.go 12 KB

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