api_utils.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. package httpd
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/go-chi/chi/v5"
  17. "github.com/go-chi/chi/v5/middleware"
  18. "github.com/go-chi/render"
  19. "github.com/klauspost/compress/zip"
  20. "github.com/drakkan/sftpgo/v2/common"
  21. "github.com/drakkan/sftpgo/v2/dataprovider"
  22. "github.com/drakkan/sftpgo/v2/logger"
  23. "github.com/drakkan/sftpgo/v2/metric"
  24. "github.com/drakkan/sftpgo/v2/sdk/plugin"
  25. "github.com/drakkan/sftpgo/v2/smtp"
  26. "github.com/drakkan/sftpgo/v2/util"
  27. )
  28. type pwdChange struct {
  29. CurrentPassword string `json:"current_password"`
  30. NewPassword string `json:"new_password"`
  31. }
  32. type pwdReset struct {
  33. Code string `json:"code"`
  34. Password string `json:"password"`
  35. }
  36. type baseProfile struct {
  37. Email string `json:"email,omitempty"`
  38. Description string `json:"description,omitempty"`
  39. AllowAPIKeyAuth bool `json:"allow_api_key_auth"`
  40. }
  41. type adminProfile struct {
  42. baseProfile
  43. }
  44. type userProfile struct {
  45. baseProfile
  46. PublicKeys []string `json:"public_keys,omitempty"`
  47. }
  48. func sendAPIResponse(w http.ResponseWriter, r *http.Request, err error, message string, code int) {
  49. var errorString string
  50. if _, ok := err.(*util.RecordNotFoundError); ok {
  51. errorString = http.StatusText(http.StatusNotFound)
  52. } else if err != nil {
  53. errorString = err.Error()
  54. }
  55. resp := apiResponse{
  56. Error: errorString,
  57. Message: message,
  58. }
  59. ctx := context.WithValue(r.Context(), render.StatusCtxKey, code)
  60. render.JSON(w, r.WithContext(ctx), resp)
  61. }
  62. func getRespStatus(err error) int {
  63. if _, ok := err.(*util.ValidationError); ok {
  64. return http.StatusBadRequest
  65. }
  66. if _, ok := err.(*util.MethodDisabledError); ok {
  67. return http.StatusForbidden
  68. }
  69. if _, ok := err.(*util.RecordNotFoundError); ok {
  70. return http.StatusNotFound
  71. }
  72. if os.IsNotExist(err) {
  73. return http.StatusBadRequest
  74. }
  75. if os.IsPermission(err) {
  76. return http.StatusForbidden
  77. }
  78. if errors.Is(err, plugin.ErrNoSearcher) || errors.Is(err, dataprovider.ErrNotImplemented) {
  79. return http.StatusNotImplemented
  80. }
  81. return http.StatusInternalServerError
  82. }
  83. // mappig between fs errors for HTTP protocol and HTTP response status codes
  84. func getMappedStatusCode(err error) int {
  85. var statusCode int
  86. switch {
  87. case errors.Is(err, os.ErrPermission):
  88. statusCode = http.StatusForbidden
  89. case errors.Is(err, os.ErrNotExist):
  90. statusCode = http.StatusNotFound
  91. case errors.Is(err, common.ErrQuotaExceeded):
  92. statusCode = http.StatusRequestEntityTooLarge
  93. case errors.Is(err, common.ErrOpUnsupported):
  94. statusCode = http.StatusBadRequest
  95. default:
  96. statusCode = http.StatusInternalServerError
  97. }
  98. return statusCode
  99. }
  100. func getURLParam(r *http.Request, key string) string {
  101. v := chi.URLParam(r, key)
  102. unescaped, err := url.PathUnescape(v)
  103. if err != nil {
  104. return v
  105. }
  106. return unescaped
  107. }
  108. func getCommaSeparatedQueryParam(r *http.Request, key string) []string {
  109. var result []string
  110. for _, val := range strings.Split(r.URL.Query().Get(key), ",") {
  111. val = strings.TrimSpace(val)
  112. if val != "" {
  113. result = append(result, val)
  114. }
  115. }
  116. return util.RemoveDuplicates(result)
  117. }
  118. func getBoolQueryParam(r *http.Request, param string) bool {
  119. return r.URL.Query().Get(param) == "true"
  120. }
  121. func handleCloseConnection(w http.ResponseWriter, r *http.Request) {
  122. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  123. connectionID := getURLParam(r, "connectionID")
  124. if connectionID == "" {
  125. sendAPIResponse(w, r, nil, "connectionID is mandatory", http.StatusBadRequest)
  126. return
  127. }
  128. if common.Connections.Close(connectionID) {
  129. sendAPIResponse(w, r, nil, "Connection closed", http.StatusOK)
  130. } else {
  131. sendAPIResponse(w, r, nil, "Not Found", http.StatusNotFound)
  132. }
  133. }
  134. func getSearchFilters(w http.ResponseWriter, r *http.Request) (int, int, string, error) {
  135. var err error
  136. limit := 100
  137. offset := 0
  138. order := dataprovider.OrderASC
  139. if _, ok := r.URL.Query()["limit"]; ok {
  140. limit, err = strconv.Atoi(r.URL.Query().Get("limit"))
  141. if err != nil {
  142. err = errors.New("invalid limit")
  143. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  144. return limit, offset, order, err
  145. }
  146. if limit > 500 {
  147. limit = 500
  148. }
  149. }
  150. if _, ok := r.URL.Query()["offset"]; ok {
  151. offset, err = strconv.Atoi(r.URL.Query().Get("offset"))
  152. if err != nil {
  153. err = errors.New("invalid offset")
  154. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  155. return limit, offset, order, err
  156. }
  157. }
  158. if _, ok := r.URL.Query()["order"]; ok {
  159. order = r.URL.Query().Get("order")
  160. if order != dataprovider.OrderASC && order != dataprovider.OrderDESC {
  161. err = errors.New("invalid order")
  162. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  163. return limit, offset, order, err
  164. }
  165. }
  166. return limit, offset, order, err
  167. }
  168. func renderCompressedFiles(w http.ResponseWriter, conn *Connection, baseDir string, files []string,
  169. share *dataprovider.Share,
  170. ) {
  171. w.Header().Set("Content-Type", "application/zip")
  172. w.Header().Set("Accept-Ranges", "none")
  173. w.Header().Set("Content-Transfer-Encoding", "binary")
  174. w.WriteHeader(http.StatusOK)
  175. wr := zip.NewWriter(w)
  176. for _, file := range files {
  177. fullPath := path.Join(baseDir, file)
  178. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  179. if share != nil {
  180. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  181. }
  182. panic(http.ErrAbortHandler)
  183. }
  184. }
  185. if err := wr.Close(); err != nil {
  186. conn.Log(logger.LevelError, "unable to close zip file: %v", err)
  187. if share != nil {
  188. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  189. }
  190. panic(http.ErrAbortHandler)
  191. }
  192. }
  193. func addZipEntry(wr *zip.Writer, conn *Connection, entryPath, baseDir string) error {
  194. info, err := conn.Stat(entryPath, 1)
  195. if err != nil {
  196. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, stat error: %v", entryPath, err)
  197. return err
  198. }
  199. if info.IsDir() {
  200. _, err := wr.Create(getZipEntryName(entryPath, baseDir) + "/")
  201. if err != nil {
  202. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  203. return err
  204. }
  205. contents, err := conn.ReadDir(entryPath)
  206. if err != nil {
  207. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, read dir error: %v", entryPath, err)
  208. return err
  209. }
  210. for _, info := range contents {
  211. fullPath := path.Join(entryPath, info.Name())
  212. if err := addZipEntry(wr, conn, fullPath, baseDir); err != nil {
  213. return err
  214. }
  215. }
  216. return nil
  217. }
  218. if !info.Mode().IsRegular() {
  219. // we only allow regular files
  220. conn.Log(logger.LevelDebug, "skipping zip entry for non regular file %#v", entryPath)
  221. return nil
  222. }
  223. reader, err := conn.getFileReader(entryPath, 0, http.MethodGet)
  224. if err != nil {
  225. conn.Log(logger.LevelDebug, "unable to add zip entry %#v, cannot open file: %v", entryPath, err)
  226. return err
  227. }
  228. defer reader.Close()
  229. f, err := wr.Create(getZipEntryName(entryPath, baseDir))
  230. if err != nil {
  231. conn.Log(logger.LevelDebug, "unable to create zip entry %#v: %v", entryPath, err)
  232. return err
  233. }
  234. _, err = io.Copy(f, reader)
  235. return err
  236. }
  237. func getZipEntryName(entryPath, baseDir string) string {
  238. entryPath = strings.TrimPrefix(entryPath, baseDir)
  239. return strings.TrimPrefix(entryPath, "/")
  240. }
  241. func downloadFile(w http.ResponseWriter, r *http.Request, connection *Connection, name string,
  242. info os.FileInfo, inline bool,
  243. ) (int, error) {
  244. var err error
  245. rangeHeader := r.Header.Get("Range")
  246. if rangeHeader != "" && checkIfRange(r, info.ModTime()) == condFalse {
  247. rangeHeader = ""
  248. }
  249. offset := int64(0)
  250. size := info.Size()
  251. responseStatus := http.StatusOK
  252. if strings.HasPrefix(rangeHeader, "bytes=") {
  253. if strings.Contains(rangeHeader, ",") {
  254. return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("unsupported range %#v", rangeHeader)
  255. }
  256. offset, size, err = parseRangeRequest(rangeHeader[6:], size)
  257. if err != nil {
  258. return http.StatusRequestedRangeNotSatisfiable, err
  259. }
  260. responseStatus = http.StatusPartialContent
  261. }
  262. reader, err := connection.getFileReader(name, offset, r.Method)
  263. if err != nil {
  264. return getMappedStatusCode(err), fmt.Errorf("unable to read file %#v: %v", name, err)
  265. }
  266. defer reader.Close()
  267. w.Header().Set("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
  268. if checkPreconditions(w, r, info.ModTime()) {
  269. return 0, fmt.Errorf("%v", http.StatusText(http.StatusPreconditionFailed))
  270. }
  271. ctype := mime.TypeByExtension(path.Ext(name))
  272. if ctype == "" {
  273. ctype = "application/octet-stream"
  274. }
  275. if responseStatus == http.StatusPartialContent {
  276. w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, info.Size()))
  277. }
  278. w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
  279. w.Header().Set("Content-Type", ctype)
  280. if !inline {
  281. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%#v", path.Base(name)))
  282. }
  283. w.Header().Set("Accept-Ranges", "bytes")
  284. w.WriteHeader(responseStatus)
  285. if r.Method != http.MethodHead {
  286. io.CopyN(w, reader, size) //nolint:errcheck
  287. }
  288. return http.StatusOK, nil
  289. }
  290. func checkPreconditions(w http.ResponseWriter, r *http.Request, modtime time.Time) bool {
  291. if checkIfUnmodifiedSince(r, modtime) == condFalse {
  292. w.WriteHeader(http.StatusPreconditionFailed)
  293. return true
  294. }
  295. if checkIfModifiedSince(r, modtime) == condFalse {
  296. w.WriteHeader(http.StatusNotModified)
  297. return true
  298. }
  299. return false
  300. }
  301. func checkIfUnmodifiedSince(r *http.Request, modtime time.Time) condResult {
  302. ius := r.Header.Get("If-Unmodified-Since")
  303. if ius == "" || isZeroTime(modtime) {
  304. return condNone
  305. }
  306. t, err := http.ParseTime(ius)
  307. if err != nil {
  308. return condNone
  309. }
  310. // The Last-Modified header truncates sub-second precision so
  311. // the modtime needs to be truncated too.
  312. modtime = modtime.Truncate(time.Second)
  313. if modtime.Before(t) || modtime.Equal(t) {
  314. return condTrue
  315. }
  316. return condFalse
  317. }
  318. func checkIfModifiedSince(r *http.Request, modtime time.Time) condResult {
  319. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  320. return condNone
  321. }
  322. ims := r.Header.Get("If-Modified-Since")
  323. if ims == "" || isZeroTime(modtime) {
  324. return condNone
  325. }
  326. t, err := http.ParseTime(ims)
  327. if err != nil {
  328. return condNone
  329. }
  330. // The Last-Modified header truncates sub-second precision so
  331. // the modtime needs to be truncated too.
  332. modtime = modtime.Truncate(time.Second)
  333. if modtime.Before(t) || modtime.Equal(t) {
  334. return condFalse
  335. }
  336. return condTrue
  337. }
  338. func checkIfRange(r *http.Request, modtime time.Time) condResult {
  339. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  340. return condNone
  341. }
  342. ir := r.Header.Get("If-Range")
  343. if ir == "" {
  344. return condNone
  345. }
  346. if modtime.IsZero() {
  347. return condFalse
  348. }
  349. t, err := http.ParseTime(ir)
  350. if err != nil {
  351. return condFalse
  352. }
  353. if modtime.Add(60 * time.Second).Before(t) {
  354. return condTrue
  355. }
  356. return condFalse
  357. }
  358. func parseRangeRequest(bytesRange string, size int64) (int64, int64, error) {
  359. var start, end int64
  360. var err error
  361. values := strings.Split(bytesRange, "-")
  362. if values[0] == "" {
  363. start = -1
  364. } else {
  365. start, err = strconv.ParseInt(values[0], 10, 64)
  366. if err != nil {
  367. return start, size, err
  368. }
  369. }
  370. if len(values) >= 2 {
  371. if values[1] != "" {
  372. end, err = strconv.ParseInt(values[1], 10, 64)
  373. if err != nil {
  374. return start, size, err
  375. }
  376. if end >= size {
  377. end = size - 1
  378. }
  379. }
  380. }
  381. if start == -1 && end == 0 {
  382. return 0, 0, fmt.Errorf("unsupported range %#v", bytesRange)
  383. }
  384. if end > 0 {
  385. if start == -1 {
  386. // we have something like -500
  387. start = size - end
  388. size = end
  389. // start cannit be < 0 here, we did end = size -1 above
  390. } else {
  391. // we have something like 500-600
  392. size = end - start + 1
  393. if size < 0 {
  394. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  395. }
  396. }
  397. return start, size, nil
  398. }
  399. // we have something like 500-
  400. size -= start
  401. if size < 0 {
  402. return 0, 0, fmt.Errorf("unacceptable range %#v", bytesRange)
  403. }
  404. return start, size, err
  405. }
  406. func updateLoginMetrics(user *dataprovider.User, ip string, err error) {
  407. metric.AddLoginAttempt(dataprovider.LoginMethodPassword)
  408. if err != nil && err != common.ErrInternalFailure && err != common.ErrNoCredentials {
  409. logger.ConnectionFailedLog(user.Username, ip, dataprovider.LoginMethodPassword, common.ProtocolHTTP, err.Error())
  410. event := common.HostEventLoginFailed
  411. if _, ok := err.(*util.RecordNotFoundError); ok {
  412. event = common.HostEventUserNotFound
  413. }
  414. common.AddDefenderEvent(ip, event)
  415. }
  416. metric.AddLoginResult(dataprovider.LoginMethodPassword, err)
  417. dataprovider.ExecutePostLoginHook(user, dataprovider.LoginMethodPassword, ip, common.ProtocolHTTP, err)
  418. }
  419. func checkHTTPClientUser(user *dataprovider.User, r *http.Request, connectionID string) error {
  420. if util.IsStringInSlice(common.ProtocolHTTP, user.Filters.DeniedProtocols) {
  421. logger.Info(logSender, connectionID, "cannot login user %#v, protocol HTTP is not allowed", user.Username)
  422. return fmt.Errorf("protocol HTTP is not allowed for user %#v", user.Username)
  423. }
  424. if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, nil) {
  425. logger.Info(logSender, connectionID, "cannot login user %#v, password login method is not allowed", user.Username)
  426. return fmt.Errorf("login method password is not allowed for user %#v", user.Username)
  427. }
  428. if user.MaxSessions > 0 {
  429. activeSessions := common.Connections.GetActiveSessions(user.Username)
  430. if activeSessions >= user.MaxSessions {
  431. logger.Info(logSender, connectionID, "authentication refused for user: %#v, too many open sessions: %v/%v", user.Username,
  432. activeSessions, user.MaxSessions)
  433. return fmt.Errorf("too many open sessions: %v", activeSessions)
  434. }
  435. }
  436. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  437. logger.Info(logSender, connectionID, "cannot login user %#v, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  438. return fmt.Errorf("login for user %#v is not allowed from this address: %v", user.Username, r.RemoteAddr)
  439. }
  440. return nil
  441. }
  442. func handleForgotPassword(r *http.Request, username string, isAdmin bool) error {
  443. var email, subject string
  444. var err error
  445. var admin dataprovider.Admin
  446. var user dataprovider.User
  447. if username == "" {
  448. return util.NewValidationError("Username is mandatory")
  449. }
  450. if isAdmin {
  451. admin, err = dataprovider.AdminExists(username)
  452. email = admin.Email
  453. subject = fmt.Sprintf("Email Verification Code for admin %#v", username)
  454. } else {
  455. user, err = dataprovider.UserExists(username)
  456. email = user.Email
  457. subject = fmt.Sprintf("Email Verification Code for user %#v", username)
  458. if err == nil {
  459. if !isUserAllowedToResetPassword(r, &user) {
  460. return util.NewValidationError("You are not allowed to reset your password")
  461. }
  462. }
  463. }
  464. if err != nil {
  465. if _, ok := err.(*util.RecordNotFoundError); ok {
  466. logger.Debug(logSender, middleware.GetReqID(r.Context()), "username %#v does not exists, reset password request silently ignored, is admin? %v",
  467. username, isAdmin)
  468. return nil
  469. }
  470. return util.NewGenericError("Error retrieving your account, please try again later")
  471. }
  472. if email == "" {
  473. return util.NewValidationError("Your account does not have an email address, it is not possible to reset your password by sending an email verification code")
  474. }
  475. c := newResetCode(username, isAdmin)
  476. body := new(bytes.Buffer)
  477. data := make(map[string]string)
  478. data["Code"] = c.Code
  479. if err := smtp.RenderPasswordResetTemplate(body, data); err != nil {
  480. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to render password reset template: %v", err)
  481. return util.NewGenericError("Unable to render password reset template")
  482. }
  483. startTime := time.Now()
  484. if err := smtp.SendEmail(email, subject, body.String(), smtp.EmailContentTypeTextHTML); err != nil {
  485. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to send password reset code via email: %v, elapsed: %v",
  486. err, time.Since(startTime))
  487. return util.NewGenericError(fmt.Sprintf("Unable to send confirmation code via email: %v", err))
  488. }
  489. logger.Debug(logSender, middleware.GetReqID(r.Context()), "reset code sent via email to %#v, email: %#v, is admin? %v, elapsed: %v",
  490. username, email, isAdmin, time.Since(startTime))
  491. resetCodes.Store(c.Code, c)
  492. return nil
  493. }
  494. func handleResetPassword(r *http.Request, code, newPassword string, isAdmin bool) (
  495. *dataprovider.Admin, *dataprovider.User, error,
  496. ) {
  497. var admin dataprovider.Admin
  498. var user dataprovider.User
  499. var err error
  500. if newPassword == "" {
  501. return &admin, &user, util.NewValidationError("Please set a password")
  502. }
  503. if code == "" {
  504. return &admin, &user, util.NewValidationError("Please set a confirmation code")
  505. }
  506. c, ok := resetCodes.Load(code)
  507. if !ok {
  508. return &admin, &user, util.NewValidationError("Confirmation code not found")
  509. }
  510. resetCode := c.(*resetCode)
  511. if resetCode.IsAdmin != isAdmin {
  512. return &admin, &user, util.NewValidationError("Invalid confirmation code")
  513. }
  514. if isAdmin {
  515. admin, err = dataprovider.AdminExists(resetCode.Username)
  516. if err != nil {
  517. return &admin, &user, util.NewValidationError("Unable to associate the confirmation code with an existing admin")
  518. }
  519. admin.Password = newPassword
  520. err = dataprovider.UpdateAdmin(&admin, admin.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  521. if err != nil {
  522. return &admin, &user, util.NewGenericError(fmt.Sprintf("Unable to set the new password: %v", err))
  523. }
  524. } else {
  525. user, err = dataprovider.UserExists(resetCode.Username)
  526. if err != nil {
  527. return &admin, &user, util.NewValidationError("Unable to associate the confirmation code with an existing user")
  528. }
  529. if err == nil {
  530. if !isUserAllowedToResetPassword(r, &user) {
  531. return &admin, &user, util.NewValidationError("You are not allowed to reset your password")
  532. }
  533. }
  534. user.Password = newPassword
  535. err = dataprovider.UpdateUser(&user, user.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  536. if err != nil {
  537. return &admin, &user, util.NewGenericError(fmt.Sprintf("Unable to set the new password: %v", err))
  538. }
  539. }
  540. resetCodes.Delete(code)
  541. return &admin, &user, nil
  542. }
  543. func isUserAllowedToResetPassword(r *http.Request, user *dataprovider.User) bool {
  544. if !user.CanResetPassword() {
  545. return false
  546. }
  547. if util.IsStringInSlice(common.ProtocolHTTP, user.Filters.DeniedProtocols) {
  548. return false
  549. }
  550. if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, nil) {
  551. return false
  552. }
  553. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  554. return false
  555. }
  556. return true
  557. }