api_utils.go 23 KB

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