api_utils.go 28 KB

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