api_utils.go 27 KB

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