api_utils.go 27 KB

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