api_utils.go 23 KB

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