api_utils.go 26 KB

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