api_utils.go 21 KB

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