api_utils.go 28 KB

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