api_utils.go 18 KB

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