api_utils.go 23 KB

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