api_utils.go 27 KB

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