api_utils.go 29 KB

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