api_utils.go 25 KB

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