api_utils.go 18 KB

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