api_utils.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  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.SplitSeq(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, nil, 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, info os.FileInfo, 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. var err error
  382. if info == nil {
  383. info, err = conn.Stat(entryPath, 1)
  384. if err != nil {
  385. conn.Log(logger.LevelDebug, "unable to add zip entry %q, stat error: %v", entryPath, err)
  386. return err
  387. }
  388. }
  389. entryName, err := getZipEntryName(entryPath, baseDir)
  390. if err != nil {
  391. conn.Log(logger.LevelError, "unable to get zip entry name: %v", err)
  392. return err
  393. }
  394. if info.IsDir() {
  395. _, err = wr.CreateHeader(&zip.FileHeader{
  396. Name: entryName + "/",
  397. Method: zip.Deflate,
  398. Modified: info.ModTime(),
  399. })
  400. if err != nil {
  401. conn.Log(logger.LevelError, "unable to create zip entry %q: %v", entryPath, err)
  402. return err
  403. }
  404. lister, err := conn.ReadDir(entryPath)
  405. if err != nil {
  406. conn.Log(logger.LevelDebug, "unable to add zip entry %q, get list dir error: %v", entryPath, err)
  407. return err
  408. }
  409. defer lister.Close()
  410. for {
  411. contents, err := lister.Next(vfs.ListerBatchSize)
  412. finished := errors.Is(err, io.EOF)
  413. if err != nil && !finished {
  414. return err
  415. }
  416. for _, info := range contents {
  417. fullPath := util.CleanPath(path.Join(entryPath, info.Name()))
  418. if err := addZipEntry(wr, conn, fullPath, baseDir, info, recursion); err != nil {
  419. return err
  420. }
  421. }
  422. if finished {
  423. return nil
  424. }
  425. }
  426. }
  427. if !info.Mode().IsRegular() {
  428. // we only allow regular files
  429. conn.Log(logger.LevelInfo, "skipping zip entry for non regular file %q", entryPath)
  430. return nil
  431. }
  432. return addFileToZipEntry(wr, conn, entryPath, entryName, info)
  433. }
  434. func addFileToZipEntry(wr *zip.Writer, conn *Connection, entryPath, entryName string, info os.FileInfo) error {
  435. reader, err := conn.getFileReader(entryPath, 0, http.MethodGet)
  436. if err != nil {
  437. conn.Log(logger.LevelDebug, "unable to add zip entry %q, cannot open file: %v", entryPath, err)
  438. return err
  439. }
  440. defer reader.Close()
  441. f, err := wr.CreateHeader(&zip.FileHeader{
  442. Name: entryName,
  443. Method: zip.Deflate,
  444. Modified: info.ModTime(),
  445. })
  446. if err != nil {
  447. conn.Log(logger.LevelError, "unable to create zip entry %q: %v", entryPath, err)
  448. return err
  449. }
  450. _, err = io.Copy(f, reader)
  451. return err
  452. }
  453. func getZipEntryName(entryPath, baseDir string) (string, error) {
  454. if !strings.HasPrefix(entryPath, baseDir) {
  455. return "", fmt.Errorf("entry path %q is outside base dir %q", entryPath, baseDir)
  456. }
  457. entryPath = strings.TrimPrefix(entryPath, baseDir)
  458. return strings.TrimPrefix(entryPath, "/"), nil
  459. }
  460. func checkDownloadFileFromShare(share *dataprovider.Share, info os.FileInfo) error {
  461. if share != nil && !info.Mode().IsRegular() {
  462. return util.NewValidationError("non regular files are not supported for shares")
  463. }
  464. return nil
  465. }
  466. func downloadFile(w http.ResponseWriter, r *http.Request, connection *Connection, name string,
  467. info os.FileInfo, inline bool, share *dataprovider.Share,
  468. ) (int, error) {
  469. connection.User.CheckFsRoot(connection.ID) //nolint:errcheck
  470. err := checkDownloadFileFromShare(share, info)
  471. if err != nil {
  472. return http.StatusBadRequest, err
  473. }
  474. rangeHeader := r.Header.Get("Range")
  475. if rangeHeader != "" && checkIfRange(r, info.ModTime()) == condFalse {
  476. rangeHeader = ""
  477. }
  478. offset := int64(0)
  479. size := info.Size()
  480. responseStatus := http.StatusOK
  481. if strings.HasPrefix(rangeHeader, "bytes=") {
  482. if strings.Contains(rangeHeader, ",") {
  483. return http.StatusRequestedRangeNotSatisfiable, fmt.Errorf("unsupported range %q", rangeHeader)
  484. }
  485. offset, size, err = parseRangeRequest(rangeHeader[6:], size)
  486. if err != nil {
  487. return http.StatusRequestedRangeNotSatisfiable, err
  488. }
  489. responseStatus = http.StatusPartialContent
  490. }
  491. reader, err := connection.getFileReader(name, offset, r.Method)
  492. if err != nil {
  493. return getMappedStatusCode(err), fmt.Errorf("unable to read file %q: %v", name, err)
  494. }
  495. defer reader.Close()
  496. w.Header().Set("Last-Modified", info.ModTime().UTC().Format(http.TimeFormat))
  497. if checkPreconditions(w, r, info.ModTime()) {
  498. return 0, fmt.Errorf("%v", http.StatusText(http.StatusPreconditionFailed))
  499. }
  500. ctype := mime.TypeByExtension(path.Ext(name))
  501. if ctype == "" {
  502. ctype = "application/octet-stream"
  503. }
  504. if responseStatus == http.StatusPartialContent {
  505. w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, offset+size-1, info.Size()))
  506. }
  507. w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
  508. w.Header().Set("Content-Type", ctype)
  509. if !inline {
  510. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", path.Base(name)))
  511. }
  512. w.Header().Set("Accept-Ranges", "bytes")
  513. w.WriteHeader(responseStatus)
  514. if r.Method != http.MethodHead {
  515. _, err = io.CopyN(w, reader, size)
  516. if err != nil {
  517. if share != nil {
  518. dataprovider.UpdateShareLastUse(share, -1) //nolint:errcheck
  519. }
  520. connection.Log(logger.LevelDebug, "error reading file to download: %v", err)
  521. panic(http.ErrAbortHandler)
  522. }
  523. }
  524. return http.StatusOK, nil
  525. }
  526. func checkPreconditions(w http.ResponseWriter, r *http.Request, modtime time.Time) bool {
  527. if checkIfUnmodifiedSince(r, modtime) == condFalse {
  528. w.WriteHeader(http.StatusPreconditionFailed)
  529. return true
  530. }
  531. if checkIfModifiedSince(r, modtime) == condFalse {
  532. w.WriteHeader(http.StatusNotModified)
  533. return true
  534. }
  535. return false
  536. }
  537. func checkIfUnmodifiedSince(r *http.Request, modtime time.Time) condResult {
  538. ius := r.Header.Get("If-Unmodified-Since")
  539. if ius == "" || isZeroTime(modtime) {
  540. return condNone
  541. }
  542. t, err := http.ParseTime(ius)
  543. if err != nil {
  544. return condNone
  545. }
  546. // The Last-Modified header truncates sub-second precision so
  547. // the modtime needs to be truncated too.
  548. modtime = modtime.Truncate(time.Second)
  549. if modtime.Before(t) || modtime.Equal(t) {
  550. return condTrue
  551. }
  552. return condFalse
  553. }
  554. func checkIfModifiedSince(r *http.Request, modtime time.Time) condResult {
  555. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  556. return condNone
  557. }
  558. ims := r.Header.Get("If-Modified-Since")
  559. if ims == "" || isZeroTime(modtime) {
  560. return condNone
  561. }
  562. t, err := http.ParseTime(ims)
  563. if err != nil {
  564. return condNone
  565. }
  566. // The Last-Modified header truncates sub-second precision so
  567. // the modtime needs to be truncated too.
  568. modtime = modtime.Truncate(time.Second)
  569. if modtime.Before(t) || modtime.Equal(t) {
  570. return condFalse
  571. }
  572. return condTrue
  573. }
  574. func checkIfRange(r *http.Request, modtime time.Time) condResult {
  575. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  576. return condNone
  577. }
  578. ir := r.Header.Get("If-Range")
  579. if ir == "" {
  580. return condNone
  581. }
  582. if modtime.IsZero() {
  583. return condFalse
  584. }
  585. t, err := http.ParseTime(ir)
  586. if err != nil {
  587. return condFalse
  588. }
  589. if modtime.Unix() == t.Unix() {
  590. return condTrue
  591. }
  592. return condFalse
  593. }
  594. func parseRangeRequest(bytesRange string, size int64) (int64, int64, error) {
  595. var start, end int64
  596. var err error
  597. values := strings.Split(bytesRange, "-")
  598. if values[0] == "" {
  599. start = -1
  600. } else {
  601. start, err = strconv.ParseInt(values[0], 10, 64)
  602. if err != nil {
  603. return start, size, err
  604. }
  605. }
  606. if len(values) >= 2 {
  607. if values[1] != "" {
  608. end, err = strconv.ParseInt(values[1], 10, 64)
  609. if err != nil {
  610. return start, size, err
  611. }
  612. if end >= size {
  613. end = size - 1
  614. }
  615. }
  616. }
  617. if start == -1 && end == 0 {
  618. return 0, 0, fmt.Errorf("unsupported range %q", bytesRange)
  619. }
  620. if end > 0 {
  621. if start == -1 {
  622. // we have something like -500
  623. start = size - end
  624. size = end
  625. // start cannot be < 0 here, we did end = size -1 above
  626. } else {
  627. // we have something like 500-600
  628. size = end - start + 1
  629. if size < 0 {
  630. return 0, 0, fmt.Errorf("unacceptable range %q", bytesRange)
  631. }
  632. }
  633. return start, size, nil
  634. }
  635. // we have something like 500-
  636. size -= start
  637. if size < 0 {
  638. return 0, 0, fmt.Errorf("unacceptable range %q", bytesRange)
  639. }
  640. return start, size, err
  641. }
  642. func handleDefenderEventLoginFailed(ipAddr string, err error) error {
  643. event := common.HostEventLoginFailed
  644. if errors.Is(err, util.ErrNotFound) {
  645. event = common.HostEventUserNotFound
  646. err = dataprovider.ErrInvalidCredentials
  647. }
  648. common.AddDefenderEvent(ipAddr, common.ProtocolHTTP, event)
  649. common.DelayLogin(err)
  650. return err
  651. }
  652. func updateLoginMetrics(user *dataprovider.User, loginMethod, ip string, err error, r *http.Request) {
  653. metric.AddLoginAttempt(loginMethod)
  654. var protocol string
  655. switch loginMethod {
  656. case dataprovider.LoginMethodIDP:
  657. protocol = common.ProtocolOIDC
  658. default:
  659. protocol = common.ProtocolHTTP
  660. }
  661. if err == nil {
  662. logger.LoginLog(user.Username, ip, loginMethod, protocol, "", r.UserAgent(), r.TLS != nil, "")
  663. plugin.Handler.NotifyLogEvent(notifier.LogEventTypeLoginOK, protocol, user.Username, ip, "", nil)
  664. common.DelayLogin(nil)
  665. } else if err != common.ErrInternalFailure && err != common.ErrNoCredentials {
  666. logger.ConnectionFailedLog(user.Username, ip, loginMethod, protocol, err.Error())
  667. err = handleDefenderEventLoginFailed(ip, err)
  668. logEv := notifier.LogEventTypeLoginFailed
  669. if errors.Is(err, util.ErrNotFound) {
  670. logEv = notifier.LogEventTypeLoginNoUser
  671. }
  672. plugin.Handler.NotifyLogEvent(logEv, protocol, user.Username, ip, "", err)
  673. }
  674. metric.AddLoginResult(loginMethod, err)
  675. dataprovider.ExecutePostLoginHook(user, loginMethod, ip, protocol, err)
  676. }
  677. func checkHTTPClientUser(user *dataprovider.User, r *http.Request, connectionID string, checkSessions, isOIDCLogin bool) error {
  678. if slices.Contains(user.Filters.DeniedProtocols, common.ProtocolHTTP) {
  679. logger.Info(logSender, connectionID, "cannot login user %q, protocol HTTP is not allowed", user.Username)
  680. return util.NewI18nError(
  681. fmt.Errorf("protocol HTTP is not allowed for user %q", user.Username),
  682. util.I18nErrorProtocolForbidden,
  683. )
  684. }
  685. if !isLoggedInWithOIDC(r) && !isOIDCLogin && !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, common.ProtocolHTTP) {
  686. logger.Info(logSender, connectionID, "cannot login user %q, password login method is not allowed", user.Username)
  687. return util.NewI18nError(
  688. fmt.Errorf("login method password is not allowed for user %q", user.Username),
  689. util.I18nErrorPwdLoginForbidden,
  690. )
  691. }
  692. if checkSessions && user.MaxSessions > 0 {
  693. activeSessions := common.Connections.GetActiveSessions(user.Username)
  694. if activeSessions >= user.MaxSessions {
  695. logger.Info(logSender, connectionID, "authentication refused for user: %q, too many open sessions: %v/%v", user.Username,
  696. activeSessions, user.MaxSessions)
  697. return util.NewI18nError(fmt.Errorf("too many open sessions: %v", activeSessions), util.I18nError429Message)
  698. }
  699. }
  700. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  701. logger.Info(logSender, connectionID, "cannot login user %q, remote address is not allowed: %v", user.Username, r.RemoteAddr)
  702. return util.NewI18nError(
  703. fmt.Errorf("login for user %q is not allowed from this address: %v", user.Username, r.RemoteAddr),
  704. util.I18nErrorIPForbidden,
  705. )
  706. }
  707. return nil
  708. }
  709. func getActiveAdmin(username, ipAddr string) (dataprovider.Admin, error) {
  710. admin, err := dataprovider.AdminExists(username)
  711. if err != nil {
  712. return admin, err
  713. }
  714. if err := admin.CanLogin(ipAddr); err != nil {
  715. return admin, util.NewRecordNotFoundError(fmt.Sprintf("admin %q cannot login: %v", username, err))
  716. }
  717. return admin, nil
  718. }
  719. func getActiveUser(username string, r *http.Request) (dataprovider.User, error) {
  720. user, err := dataprovider.GetUserWithGroupSettings(username, "")
  721. if err != nil {
  722. return user, err
  723. }
  724. if err := user.CheckLoginConditions(); err != nil {
  725. return user, util.NewRecordNotFoundError(fmt.Sprintf("user %q cannot login: %v", username, err))
  726. }
  727. if err := checkHTTPClientUser(&user, r, xid.New().String(), false, false); err != nil {
  728. return user, util.NewRecordNotFoundError(fmt.Sprintf("user %q cannot login: %v", username, err))
  729. }
  730. return user, nil
  731. }
  732. func handleForgotPassword(r *http.Request, username string, isAdmin bool) error {
  733. var emails []string
  734. var subject string
  735. var err error
  736. var admin dataprovider.Admin
  737. var user dataprovider.User
  738. if username == "" {
  739. return util.NewI18nError(util.NewValidationError("username is mandatory"), util.I18nErrorUsernameRequired)
  740. }
  741. if isAdmin {
  742. admin, err = getActiveAdmin(username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  743. if admin.Email != "" {
  744. emails = []string{admin.Email}
  745. }
  746. subject = fmt.Sprintf("Email Verification Code for admin %q", username)
  747. } else {
  748. user, err = getActiveUser(username, r)
  749. emails = user.GetEmailAddresses()
  750. subject = fmt.Sprintf("Email Verification Code for user %q", username)
  751. if err == nil {
  752. if !isUserAllowedToResetPassword(r, &user) {
  753. return util.NewI18nError(
  754. util.NewValidationError("you are not allowed to reset your password"),
  755. util.I18nErrorPwdResetForbidded,
  756. )
  757. }
  758. }
  759. }
  760. if err != nil {
  761. if errors.Is(err, util.ErrNotFound) {
  762. handleDefenderEventLoginFailed(util.GetIPFromRemoteAddress(r.RemoteAddr), err) //nolint:errcheck
  763. logger.Debug(logSender, middleware.GetReqID(r.Context()),
  764. "username %q does not exists or cannot login, reset password request silently ignored, is admin? %t, err: %v",
  765. username, isAdmin, err)
  766. return nil
  767. }
  768. return util.NewI18nError(util.NewGenericError("Error retrieving your account, please try again later"), util.I18nErrorGetUser)
  769. }
  770. if len(emails) == 0 {
  771. return util.NewI18nError(
  772. util.NewValidationError("Your account does not have an email address, it is not possible to reset your password by sending an email verification code"),
  773. util.I18nErrorPwdResetNoEmail,
  774. )
  775. }
  776. c := newResetCode(username, isAdmin)
  777. body := new(bytes.Buffer)
  778. data := make(map[string]string)
  779. data["Code"] = c.Code
  780. if err := smtp.RenderPasswordResetTemplate(body, data); err != nil {
  781. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to render password reset template: %v", err)
  782. return util.NewGenericError("Unable to render password reset template")
  783. }
  784. startTime := time.Now()
  785. if err := smtp.SendEmail(emails, nil, subject, body.String(), smtp.EmailContentTypeTextHTML); err != nil {
  786. logger.Warn(logSender, middleware.GetReqID(r.Context()), "unable to send password reset code via email: %v, elapsed: %v",
  787. err, time.Since(startTime))
  788. return util.NewI18nError(
  789. util.NewGenericError(fmt.Sprintf("Error sending confirmation code via email: %v", err)),
  790. util.I18nErrorPwdResetSendEmail,
  791. )
  792. }
  793. logger.Debug(logSender, middleware.GetReqID(r.Context()), "reset code sent via email to %q, emails: %+v, is admin? %v, elapsed: %v",
  794. username, emails, isAdmin, time.Since(startTime))
  795. return resetCodesMgr.Add(c)
  796. }
  797. func handleResetPassword(r *http.Request, code, newPassword, confirmPassword string, isAdmin bool) (
  798. *dataprovider.Admin, *dataprovider.User, error,
  799. ) {
  800. var admin dataprovider.Admin
  801. var user dataprovider.User
  802. var err error
  803. if newPassword == "" {
  804. return &admin, &user, util.NewValidationError("please set a password")
  805. }
  806. if code == "" {
  807. return &admin, &user, util.NewValidationError("please set a confirmation code")
  808. }
  809. if newPassword != confirmPassword {
  810. return &admin, &user, util.NewI18nError(errors.New("the two password fields do not match"), util.I18nErrorChangePwdNoMatch)
  811. }
  812. ipAddr := util.GetIPFromRemoteAddress(r.RemoteAddr)
  813. resetCode, err := resetCodesMgr.Get(code)
  814. if err != nil {
  815. handleDefenderEventLoginFailed(ipAddr, dataprovider.ErrInvalidCredentials) //nolint:errcheck
  816. return &admin, &user, util.NewValidationError("confirmation code not found")
  817. }
  818. if resetCode.IsAdmin != isAdmin {
  819. return &admin, &user, util.NewValidationError("invalid confirmation code")
  820. }
  821. if isAdmin {
  822. admin, err = getActiveAdmin(resetCode.Username, ipAddr)
  823. if err != nil {
  824. return &admin, &user, util.NewValidationError("unable to associate the confirmation code with an existing admin")
  825. }
  826. admin.Password = newPassword
  827. admin.Filters.RequirePasswordChange = false
  828. err = dataprovider.UpdateAdmin(&admin, dataprovider.ActionExecutorSelf, ipAddr, admin.Role)
  829. if err != nil {
  830. return &admin, &user, util.NewGenericError(fmt.Sprintf("unable to set the new password: %v", err))
  831. }
  832. err = resetCodesMgr.Delete(code)
  833. return &admin, &user, err
  834. }
  835. user, err = getActiveUser(resetCode.Username, r)
  836. if err != nil {
  837. return &admin, &user, util.NewValidationError("Unable to associate the confirmation code with an existing user")
  838. }
  839. if !isUserAllowedToResetPassword(r, &user) {
  840. return &admin, &user, util.NewI18nError(
  841. util.NewValidationError("you are not allowed to reset your password"),
  842. util.I18nErrorPwdResetForbidded,
  843. )
  844. }
  845. err = dataprovider.UpdateUserPassword(user.Username, newPassword, dataprovider.ActionExecutorSelf,
  846. util.GetIPFromRemoteAddress(r.RemoteAddr), user.Role)
  847. if err == nil {
  848. err = resetCodesMgr.Delete(code)
  849. }
  850. user.LastPasswordChange = util.GetTimeAsMsSinceEpoch(time.Now())
  851. user.Filters.RequirePasswordChange = false
  852. return &admin, &user, err
  853. }
  854. func isUserAllowedToResetPassword(r *http.Request, user *dataprovider.User) bool {
  855. if !user.CanResetPassword() {
  856. return false
  857. }
  858. if slices.Contains(user.Filters.DeniedProtocols, common.ProtocolHTTP) {
  859. return false
  860. }
  861. if !user.IsLoginMethodAllowed(dataprovider.LoginMethodPassword, common.ProtocolHTTP) {
  862. return false
  863. }
  864. if !user.IsLoginFromAddrAllowed(r.RemoteAddr) {
  865. return false
  866. }
  867. return true
  868. }
  869. func getProtocolFromRequest(r *http.Request) string {
  870. if isLoggedInWithOIDC(r) {
  871. return common.ProtocolOIDC
  872. }
  873. return common.ProtocolHTTP
  874. }
  875. func hideConfidentialData(claims *jwtTokenClaims, r *http.Request) bool {
  876. if !claims.hasPerm(dataprovider.PermAdminAny) {
  877. return true
  878. }
  879. return r.URL.Query().Get("confidential_data") != "1"
  880. }
  881. func responseControllerDeadlines(rc *http.ResponseController, read, write time.Time) {
  882. if err := rc.SetReadDeadline(read); err != nil {
  883. logger.Error(logSender, "", "unable to set read timeout to %s: %v", read, err)
  884. }
  885. if err := rc.SetWriteDeadline(write); err != nil {
  886. logger.Error(logSender, "", "unable to set write timeout to %s: %v", write, err)
  887. }
  888. }