user.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. package dataprovider
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/drakkan/sftpgo/logger"
  14. "github.com/drakkan/sftpgo/utils"
  15. "github.com/drakkan/sftpgo/vfs"
  16. )
  17. // Available permissions for SFTP users
  18. const (
  19. // All permissions are granted
  20. PermAny = "*"
  21. // List items such as files and directories is allowed
  22. PermListItems = "list"
  23. // download files is allowed
  24. PermDownload = "download"
  25. // upload files is allowed
  26. PermUpload = "upload"
  27. // overwrite an existing file, while uploading, is allowed
  28. // upload permission is required to allow file overwrite
  29. PermOverwrite = "overwrite"
  30. // delete files or directories is allowed
  31. PermDelete = "delete"
  32. // rename files or directories is allowed
  33. PermRename = "rename"
  34. // create directories is allowed
  35. PermCreateDirs = "create_dirs"
  36. // create symbolic links is allowed
  37. PermCreateSymlinks = "create_symlinks"
  38. // changing file or directory permissions is allowed
  39. PermChmod = "chmod"
  40. // changing file or directory owner and group is allowed
  41. PermChown = "chown"
  42. // changing file or directory access and modification time is allowed
  43. PermChtimes = "chtimes"
  44. )
  45. // Available login methods
  46. const (
  47. LoginMethodNoAuthTryed = "no_auth_tryed"
  48. LoginMethodPassword = "password"
  49. SSHLoginMethodPublicKey = "publickey"
  50. SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
  51. SSHLoginMethodKeyAndPassword = "publickey+password"
  52. SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive"
  53. )
  54. var (
  55. errNoMatchingVirtualFolder = errors.New("no matching virtual folder found")
  56. )
  57. // CachedUser adds fields useful for caching to a SFTPGo user
  58. type CachedUser struct {
  59. User User
  60. Expiration time.Time
  61. Password string
  62. }
  63. // IsExpired returns true if the cached user is expired
  64. func (c CachedUser) IsExpired() bool {
  65. if c.Expiration.IsZero() {
  66. return false
  67. }
  68. return c.Expiration.Before(time.Now())
  69. }
  70. // ExtensionsFilter defines filters based on file extensions.
  71. // These restrictions do not apply to files listing for performance reasons, so
  72. // a denied file cannot be downloaded/overwritten/renamed but will still be
  73. // it will still be listed in the list of files.
  74. // System commands such as Git and rsync interacts with the filesystem directly
  75. // and they are not aware about these restrictions so they are not allowed
  76. // inside paths with extensions filters
  77. type ExtensionsFilter struct {
  78. // SFTP/SCP path, if no other specific filter is defined, the filter apply for
  79. // sub directories too.
  80. // For example if filters are defined for the paths "/" and "/sub" then the
  81. // filters for "/" are applied for any file outside the "/sub" directory
  82. Path string `json:"path"`
  83. // only files with these, case insensitive, extensions are allowed.
  84. // Shell like expansion is not supported so you have to specify ".jpg" and
  85. // not "*.jpg"
  86. AllowedExtensions []string `json:"allowed_extensions,omitempty"`
  87. // files with these, case insensitive, extensions are not allowed.
  88. // Denied file extensions are evaluated before the allowed ones
  89. DeniedExtensions []string `json:"denied_extensions,omitempty"`
  90. }
  91. // UserFilters defines additional restrictions for a user
  92. type UserFilters struct {
  93. // only clients connecting from these IP/Mask are allowed.
  94. // IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291
  95. // for example "192.0.2.0/24" or "2001:db8::/32"
  96. AllowedIP []string `json:"allowed_ip,omitempty"`
  97. // clients connecting from these IP/Mask are not allowed.
  98. // Denied rules will be evaluated before allowed ones
  99. DeniedIP []string `json:"denied_ip,omitempty"`
  100. // these login methods are not allowed.
  101. // If null or empty any available login method is allowed
  102. DeniedLoginMethods []string `json:"denied_login_methods,omitempty"`
  103. // these protocols are not allowed.
  104. // If null or empty any available protocol is allowed
  105. DeniedProtocols []string `json:"denied_protocols,omitempty"`
  106. // filters based on file extensions.
  107. // Please note that these restrictions can be easily bypassed.
  108. FileExtensions []ExtensionsFilter `json:"file_extensions,omitempty"`
  109. // max size allowed for a single upload, 0 means unlimited
  110. MaxUploadFileSize int64 `json:"max_upload_file_size,omitempty"`
  111. }
  112. // Filesystem defines cloud storage filesystem details
  113. type Filesystem struct {
  114. // 0 local filesystem, 1 Amazon S3 compatible, 2 Google Cloud Storage
  115. Provider int `json:"provider"`
  116. S3Config vfs.S3FsConfig `json:"s3config,omitempty"`
  117. GCSConfig vfs.GCSFsConfig `json:"gcsconfig,omitempty"`
  118. }
  119. // User defines a SFTPGo user
  120. type User struct {
  121. // Database unique identifier
  122. ID int64 `json:"id"`
  123. // 1 enabled, 0 disabled (login is not allowed)
  124. Status int `json:"status"`
  125. // Username
  126. Username string `json:"username"`
  127. // Account expiration date as unix timestamp in milliseconds. An expired account cannot login.
  128. // 0 means no expiration
  129. ExpirationDate int64 `json:"expiration_date"`
  130. // Password used for password authentication.
  131. // For users created using SFTPGo REST API the password is be stored using argon2id hashing algo.
  132. // Checking passwords stored with bcrypt, pbkdf2, md5crypt and sha512crypt is supported too.
  133. Password string `json:"password,omitempty"`
  134. // PublicKeys used for public key authentication. At least one between password and a public key is mandatory
  135. PublicKeys []string `json:"public_keys,omitempty"`
  136. // The user cannot upload or download files outside this directory. Must be an absolute path
  137. HomeDir string `json:"home_dir"`
  138. // Mapping between virtual paths and filesystem paths outside the home directory.
  139. // Supported for local filesystem only
  140. VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
  141. // If sftpgo runs as root system user then the created files and directories will be assigned to this system UID
  142. UID int `json:"uid"`
  143. // If sftpgo runs as root system user then the created files and directories will be assigned to this system GID
  144. GID int `json:"gid"`
  145. // Maximum concurrent sessions. 0 means unlimited
  146. MaxSessions int `json:"max_sessions"`
  147. // Maximum size allowed as bytes. 0 means unlimited
  148. QuotaSize int64 `json:"quota_size"`
  149. // Maximum number of files allowed. 0 means unlimited
  150. QuotaFiles int `json:"quota_files"`
  151. // List of the granted permissions
  152. Permissions map[string][]string `json:"permissions"`
  153. // Used quota as bytes
  154. UsedQuotaSize int64 `json:"used_quota_size"`
  155. // Used quota as number of files
  156. UsedQuotaFiles int `json:"used_quota_files"`
  157. // Last quota update as unix timestamp in milliseconds
  158. LastQuotaUpdate int64 `json:"last_quota_update"`
  159. // Maximum upload bandwidth as KB/s, 0 means unlimited
  160. UploadBandwidth int64 `json:"upload_bandwidth"`
  161. // Maximum download bandwidth as KB/s, 0 means unlimited
  162. DownloadBandwidth int64 `json:"download_bandwidth"`
  163. // Last login as unix timestamp in milliseconds
  164. LastLogin int64 `json:"last_login"`
  165. // Additional restrictions
  166. Filters UserFilters `json:"filters"`
  167. // Filesystem configuration details
  168. FsConfig Filesystem `json:"filesystem"`
  169. }
  170. // GetFilesystem returns the filesystem for this user
  171. func (u *User) GetFilesystem(connectionID string) (vfs.Fs, error) {
  172. if u.FsConfig.Provider == 1 {
  173. return vfs.NewS3Fs(connectionID, u.GetHomeDir(), u.FsConfig.S3Config)
  174. } else if u.FsConfig.Provider == 2 {
  175. config := u.FsConfig.GCSConfig
  176. config.CredentialFile = u.getGCSCredentialsFilePath()
  177. return vfs.NewGCSFs(connectionID, u.GetHomeDir(), config)
  178. }
  179. return vfs.NewOsFs(connectionID, u.GetHomeDir(), u.VirtualFolders), nil
  180. }
  181. // GetPermissionsForPath returns the permissions for the given path.
  182. // The path must be an SFTP path
  183. func (u *User) GetPermissionsForPath(p string) []string {
  184. permissions := []string{}
  185. if perms, ok := u.Permissions["/"]; ok {
  186. // if only root permissions are defined returns them unconditionally
  187. if len(u.Permissions) == 1 {
  188. return perms
  189. }
  190. // fallback permissions
  191. permissions = perms
  192. }
  193. dirsForPath := utils.GetDirsForSFTPPath(p)
  194. // dirsForPath contains all the dirs for a given path in reverse order
  195. // for example if the path is: /1/2/3/4 it contains:
  196. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  197. // so the first match is the one we are interested to
  198. for _, val := range dirsForPath {
  199. if perms, ok := u.Permissions[val]; ok {
  200. permissions = perms
  201. break
  202. }
  203. }
  204. return permissions
  205. }
  206. // GetVirtualFolderForPath returns the virtual folder containing the specified sftp path.
  207. // If the path is not inside a virtual folder an error is returned
  208. func (u *User) GetVirtualFolderForPath(sftpPath string) (vfs.VirtualFolder, error) {
  209. var folder vfs.VirtualFolder
  210. if len(u.VirtualFolders) == 0 || u.FsConfig.Provider != 0 {
  211. return folder, errNoMatchingVirtualFolder
  212. }
  213. dirsForPath := utils.GetDirsForSFTPPath(sftpPath)
  214. for _, val := range dirsForPath {
  215. for _, v := range u.VirtualFolders {
  216. if v.VirtualPath == val {
  217. return v, nil
  218. }
  219. }
  220. }
  221. return folder, errNoMatchingVirtualFolder
  222. }
  223. // AddVirtualDirs adds virtual folders, if defined, to the given files list
  224. func (u *User) AddVirtualDirs(list []os.FileInfo, sftpPath string) []os.FileInfo {
  225. if len(u.VirtualFolders) == 0 {
  226. return list
  227. }
  228. for _, v := range u.VirtualFolders {
  229. if path.Dir(v.VirtualPath) == sftpPath {
  230. fi := vfs.NewFileInfo(v.VirtualPath, true, 0, time.Now(), false)
  231. found := false
  232. for index, f := range list {
  233. if f.Name() == fi.Name() {
  234. list[index] = fi
  235. found = true
  236. break
  237. }
  238. }
  239. if !found {
  240. list = append(list, fi)
  241. }
  242. }
  243. }
  244. return list
  245. }
  246. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  247. // The filesystem path must be cleaned before calling this method
  248. func (u *User) IsMappedPath(fsPath string) bool {
  249. for _, v := range u.VirtualFolders {
  250. if fsPath == v.MappedPath {
  251. return true
  252. }
  253. }
  254. return false
  255. }
  256. // IsVirtualFolder returns true if the specified sftp path is a virtual folder
  257. func (u *User) IsVirtualFolder(sftpPath string) bool {
  258. for _, v := range u.VirtualFolders {
  259. if sftpPath == v.VirtualPath {
  260. return true
  261. }
  262. }
  263. return false
  264. }
  265. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  266. // specified SFTP path. We assume that path are cleaned
  267. func (u *User) HasVirtualFoldersInside(sftpPath string) bool {
  268. if sftpPath == "/" && len(u.VirtualFolders) > 0 {
  269. return true
  270. }
  271. for _, v := range u.VirtualFolders {
  272. if len(v.VirtualPath) > len(sftpPath) {
  273. if strings.HasPrefix(v.VirtualPath, sftpPath+"/") {
  274. return true
  275. }
  276. }
  277. }
  278. return false
  279. }
  280. // HasPermissionsInside returns true if the specified sftpPath has no permissions itself and
  281. // no subdirs with defined permissions
  282. func (u *User) HasPermissionsInside(sftpPath string) bool {
  283. for dir := range u.Permissions {
  284. if dir == sftpPath {
  285. return true
  286. } else if len(dir) > len(sftpPath) {
  287. if strings.HasPrefix(dir, sftpPath+"/") {
  288. return true
  289. }
  290. }
  291. }
  292. return false
  293. }
  294. // HasOverlappedMappedPaths returns true if this user has virtual folders with overlapped mapped paths
  295. func (u *User) HasOverlappedMappedPaths() bool {
  296. if len(u.VirtualFolders) <= 1 {
  297. return false
  298. }
  299. for _, v1 := range u.VirtualFolders {
  300. for _, v2 := range u.VirtualFolders {
  301. if v1.VirtualPath == v2.VirtualPath {
  302. continue
  303. }
  304. if isMappedDirOverlapped(v1.MappedPath, v2.MappedPath) {
  305. return true
  306. }
  307. }
  308. }
  309. return false
  310. }
  311. // HasPerm returns true if the user has the given permission or any permission
  312. func (u *User) HasPerm(permission, path string) bool {
  313. perms := u.GetPermissionsForPath(path)
  314. if utils.IsStringInSlice(PermAny, perms) {
  315. return true
  316. }
  317. return utils.IsStringInSlice(permission, perms)
  318. }
  319. // HasPerms return true if the user has all the given permissions
  320. func (u *User) HasPerms(permissions []string, path string) bool {
  321. perms := u.GetPermissionsForPath(path)
  322. if utils.IsStringInSlice(PermAny, perms) {
  323. return true
  324. }
  325. for _, permission := range permissions {
  326. if !utils.IsStringInSlice(permission, perms) {
  327. return false
  328. }
  329. }
  330. return true
  331. }
  332. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  333. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  334. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  335. return true
  336. }
  337. return false
  338. }
  339. // IsLoginMethodAllowed returns true if the specified login method is allowed
  340. func (u *User) IsLoginMethodAllowed(loginMethod string, partialSuccessMethods []string) bool {
  341. if len(u.Filters.DeniedLoginMethods) == 0 {
  342. return true
  343. }
  344. if len(partialSuccessMethods) == 1 {
  345. for _, method := range u.GetNextAuthMethods(partialSuccessMethods, true) {
  346. if method == loginMethod {
  347. return true
  348. }
  349. }
  350. }
  351. if utils.IsStringInSlice(loginMethod, u.Filters.DeniedLoginMethods) {
  352. return false
  353. }
  354. return true
  355. }
  356. // GetNextAuthMethods returns the list of authentications methods that
  357. // can continue for multi-step authentication
  358. func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string {
  359. var methods []string
  360. if len(partialSuccessMethods) != 1 {
  361. return methods
  362. }
  363. if partialSuccessMethods[0] != SSHLoginMethodPublicKey {
  364. return methods
  365. }
  366. for _, method := range u.GetAllowedLoginMethods() {
  367. if method == SSHLoginMethodKeyAndPassword && isPasswordAuthEnabled {
  368. methods = append(methods, LoginMethodPassword)
  369. }
  370. if method == SSHLoginMethodKeyAndKeyboardInt {
  371. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  372. }
  373. }
  374. return methods
  375. }
  376. // IsPartialAuth returns true if the specified login method is a step for
  377. // a multi-step Authentication.
  378. // We support publickey+password and publickey+keyboard-interactive, so
  379. // only publickey can returns partial success.
  380. // We can have partial success if only multi-step Auth methods are enabled
  381. func (u *User) IsPartialAuth(loginMethod string) bool {
  382. if loginMethod != SSHLoginMethodPublicKey {
  383. return false
  384. }
  385. for _, method := range u.GetAllowedLoginMethods() {
  386. if !utils.IsStringInSlice(method, SSHMultiStepsLoginMethods) {
  387. return false
  388. }
  389. }
  390. return true
  391. }
  392. // GetAllowedLoginMethods returns the allowed login methods
  393. func (u *User) GetAllowedLoginMethods() []string {
  394. var allowedMethods []string
  395. for _, method := range ValidSSHLoginMethods {
  396. if !utils.IsStringInSlice(method, u.Filters.DeniedLoginMethods) {
  397. allowedMethods = append(allowedMethods, method)
  398. }
  399. }
  400. return allowedMethods
  401. }
  402. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters
  403. func (u *User) IsFileAllowed(sftpPath string) bool {
  404. if len(u.Filters.FileExtensions) == 0 {
  405. return true
  406. }
  407. dirsForPath := utils.GetDirsForSFTPPath(path.Dir(sftpPath))
  408. var filter ExtensionsFilter
  409. for _, dir := range dirsForPath {
  410. for _, f := range u.Filters.FileExtensions {
  411. if f.Path == dir {
  412. filter = f
  413. break
  414. }
  415. }
  416. if len(filter.Path) > 0 {
  417. break
  418. }
  419. }
  420. if len(filter.Path) > 0 {
  421. toMatch := strings.ToLower(sftpPath)
  422. for _, denied := range filter.DeniedExtensions {
  423. if strings.HasSuffix(toMatch, denied) {
  424. return false
  425. }
  426. }
  427. for _, allowed := range filter.AllowedExtensions {
  428. if strings.HasSuffix(toMatch, allowed) {
  429. return true
  430. }
  431. }
  432. return len(filter.AllowedExtensions) == 0
  433. }
  434. return true
  435. }
  436. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  437. // If AllowedIP is defined only the specified IP/Mask can login.
  438. // If DeniedIP is defined the specified IP/Mask cannot login.
  439. // If an IP is both allowed and denied then login will be denied
  440. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  441. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  442. return true
  443. }
  444. remoteIP := net.ParseIP(utils.GetIPFromRemoteAddress(remoteAddr))
  445. // if remoteIP is invalid we allow login, this should never happen
  446. if remoteIP == nil {
  447. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %#v", remoteAddr)
  448. return true
  449. }
  450. for _, IPMask := range u.Filters.DeniedIP {
  451. _, IPNet, err := net.ParseCIDR(IPMask)
  452. if err != nil {
  453. return false
  454. }
  455. if IPNet.Contains(remoteIP) {
  456. return false
  457. }
  458. }
  459. for _, IPMask := range u.Filters.AllowedIP {
  460. _, IPNet, err := net.ParseCIDR(IPMask)
  461. if err != nil {
  462. return false
  463. }
  464. if IPNet.Contains(remoteIP) {
  465. return true
  466. }
  467. }
  468. return len(u.Filters.AllowedIP) == 0
  469. }
  470. // GetPermissionsAsJSON returns the permissions as json byte array
  471. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  472. return json.Marshal(u.Permissions)
  473. }
  474. // GetPublicKeysAsJSON returns the public keys as json byte array
  475. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  476. return json.Marshal(u.PublicKeys)
  477. }
  478. // GetFiltersAsJSON returns the filters as json byte array
  479. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  480. return json.Marshal(u.Filters)
  481. }
  482. // GetFsConfigAsJSON returns the filesystem config as json byte array
  483. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  484. return json.Marshal(u.FsConfig)
  485. }
  486. // GetUID returns a validate uid, suitable for use with os.Chown
  487. func (u *User) GetUID() int {
  488. if u.UID <= 0 || u.UID > 65535 {
  489. return -1
  490. }
  491. return u.UID
  492. }
  493. // GetGID returns a validate gid, suitable for use with os.Chown
  494. func (u *User) GetGID() int {
  495. if u.GID <= 0 || u.GID > 65535 {
  496. return -1
  497. }
  498. return u.GID
  499. }
  500. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  501. func (u *User) GetHomeDir() string {
  502. return filepath.Clean(u.HomeDir)
  503. }
  504. // HasQuotaRestrictions returns true if there is a quota restriction on number of files or size or both
  505. func (u *User) HasQuotaRestrictions() bool {
  506. return u.QuotaFiles > 0 || u.QuotaSize > 0
  507. }
  508. // GetQuotaSummary returns used quota and limits if defined
  509. func (u *User) GetQuotaSummary() string {
  510. var result string
  511. result = "Files: " + strconv.Itoa(u.UsedQuotaFiles)
  512. if u.QuotaFiles > 0 {
  513. result += "/" + strconv.Itoa(u.QuotaFiles)
  514. }
  515. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  516. result += ". Size: " + utils.ByteCountSI(u.UsedQuotaSize)
  517. if u.QuotaSize > 0 {
  518. result += "/" + utils.ByteCountSI(u.QuotaSize)
  519. }
  520. }
  521. return result
  522. }
  523. // GetPermissionsAsString returns the user's permissions as comma separated string
  524. func (u *User) GetPermissionsAsString() string {
  525. result := ""
  526. for dir, perms := range u.Permissions {
  527. var dirPerms string
  528. for _, p := range perms {
  529. if len(dirPerms) > 0 {
  530. dirPerms += ", "
  531. }
  532. dirPerms += p
  533. }
  534. dp := fmt.Sprintf("%#v: %#v", dir, dirPerms)
  535. if dir == "/" {
  536. if len(result) > 0 {
  537. result = dp + ", " + result
  538. } else {
  539. result = dp
  540. }
  541. } else {
  542. if len(result) > 0 {
  543. result += ", "
  544. }
  545. result += dp
  546. }
  547. }
  548. return result
  549. }
  550. // GetBandwidthAsString returns bandwidth limits if defines
  551. func (u *User) GetBandwidthAsString() string {
  552. result := "Download: "
  553. if u.DownloadBandwidth > 0 {
  554. result += utils.ByteCountSI(u.DownloadBandwidth*1000) + "/s."
  555. } else {
  556. result += "unlimited."
  557. }
  558. result += " Upload: "
  559. if u.UploadBandwidth > 0 {
  560. result += utils.ByteCountSI(u.UploadBandwidth*1000) + "/s."
  561. } else {
  562. result += "unlimited."
  563. }
  564. return result
  565. }
  566. // GetInfoString returns user's info as string.
  567. // Storage provider, number of public keys, max sessions, uid,
  568. // gid, denied and allowed IP/Mask are returned
  569. func (u *User) GetInfoString() string {
  570. var result string
  571. if u.LastLogin > 0 {
  572. t := utils.GetTimeFromMsecSinceEpoch(u.LastLogin)
  573. result += fmt.Sprintf("Last login: %v ", t.Format("2006-01-02 15:04:05")) // YYYY-MM-DD HH:MM:SS
  574. }
  575. if u.FsConfig.Provider == 1 {
  576. result += "Storage: S3 "
  577. } else if u.FsConfig.Provider == 2 {
  578. result += "Storage: GCS "
  579. }
  580. if len(u.PublicKeys) > 0 {
  581. result += fmt.Sprintf("Public keys: %v ", len(u.PublicKeys))
  582. }
  583. if u.MaxSessions > 0 {
  584. result += fmt.Sprintf("Max sessions: %v ", u.MaxSessions)
  585. }
  586. if u.UID > 0 {
  587. result += fmt.Sprintf("UID: %v ", u.UID)
  588. }
  589. if u.GID > 0 {
  590. result += fmt.Sprintf("GID: %v ", u.GID)
  591. }
  592. if len(u.Filters.DeniedIP) > 0 {
  593. result += fmt.Sprintf("Denied IP/Mask: %v ", len(u.Filters.DeniedIP))
  594. }
  595. if len(u.Filters.AllowedIP) > 0 {
  596. result += fmt.Sprintf("Allowed IP/Mask: %v ", len(u.Filters.AllowedIP))
  597. }
  598. return result
  599. }
  600. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  601. func (u *User) GetExpirationDateAsString() string {
  602. if u.ExpirationDate > 0 {
  603. t := utils.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  604. return t.Format("2006-01-02")
  605. }
  606. return ""
  607. }
  608. // GetAllowedIPAsString returns the allowed IP as comma separated string
  609. func (u User) GetAllowedIPAsString() string {
  610. result := ""
  611. for _, IPMask := range u.Filters.AllowedIP {
  612. if len(result) > 0 {
  613. result += ","
  614. }
  615. result += IPMask
  616. }
  617. return result
  618. }
  619. // GetDeniedIPAsString returns the denied IP as comma separated string
  620. func (u User) GetDeniedIPAsString() string {
  621. result := ""
  622. for _, IPMask := range u.Filters.DeniedIP {
  623. if len(result) > 0 {
  624. result += ","
  625. }
  626. result += IPMask
  627. }
  628. return result
  629. }
  630. func (u *User) getACopy() User {
  631. pubKeys := make([]string, len(u.PublicKeys))
  632. copy(pubKeys, u.PublicKeys)
  633. virtualFolders := make([]vfs.VirtualFolder, len(u.VirtualFolders))
  634. copy(virtualFolders, u.VirtualFolders)
  635. permissions := make(map[string][]string)
  636. for k, v := range u.Permissions {
  637. perms := make([]string, len(v))
  638. copy(perms, v)
  639. permissions[k] = perms
  640. }
  641. filters := UserFilters{}
  642. filters.MaxUploadFileSize = u.Filters.MaxUploadFileSize
  643. filters.AllowedIP = make([]string, len(u.Filters.AllowedIP))
  644. copy(filters.AllowedIP, u.Filters.AllowedIP)
  645. filters.DeniedIP = make([]string, len(u.Filters.DeniedIP))
  646. copy(filters.DeniedIP, u.Filters.DeniedIP)
  647. filters.DeniedLoginMethods = make([]string, len(u.Filters.DeniedLoginMethods))
  648. copy(filters.DeniedLoginMethods, u.Filters.DeniedLoginMethods)
  649. filters.FileExtensions = make([]ExtensionsFilter, len(u.Filters.FileExtensions))
  650. copy(filters.FileExtensions, u.Filters.FileExtensions)
  651. filters.DeniedProtocols = make([]string, len(u.Filters.DeniedProtocols))
  652. copy(filters.DeniedProtocols, u.Filters.DeniedProtocols)
  653. fsConfig := Filesystem{
  654. Provider: u.FsConfig.Provider,
  655. S3Config: vfs.S3FsConfig{
  656. Bucket: u.FsConfig.S3Config.Bucket,
  657. Region: u.FsConfig.S3Config.Region,
  658. AccessKey: u.FsConfig.S3Config.AccessKey,
  659. AccessSecret: u.FsConfig.S3Config.AccessSecret,
  660. Endpoint: u.FsConfig.S3Config.Endpoint,
  661. StorageClass: u.FsConfig.S3Config.StorageClass,
  662. KeyPrefix: u.FsConfig.S3Config.KeyPrefix,
  663. UploadPartSize: u.FsConfig.S3Config.UploadPartSize,
  664. UploadConcurrency: u.FsConfig.S3Config.UploadConcurrency,
  665. },
  666. GCSConfig: vfs.GCSFsConfig{
  667. Bucket: u.FsConfig.GCSConfig.Bucket,
  668. CredentialFile: u.FsConfig.GCSConfig.CredentialFile,
  669. AutomaticCredentials: u.FsConfig.GCSConfig.AutomaticCredentials,
  670. StorageClass: u.FsConfig.GCSConfig.StorageClass,
  671. KeyPrefix: u.FsConfig.GCSConfig.KeyPrefix,
  672. },
  673. }
  674. return User{
  675. ID: u.ID,
  676. Username: u.Username,
  677. Password: u.Password,
  678. PublicKeys: pubKeys,
  679. HomeDir: u.HomeDir,
  680. VirtualFolders: virtualFolders,
  681. UID: u.UID,
  682. GID: u.GID,
  683. MaxSessions: u.MaxSessions,
  684. QuotaSize: u.QuotaSize,
  685. QuotaFiles: u.QuotaFiles,
  686. Permissions: permissions,
  687. UsedQuotaSize: u.UsedQuotaSize,
  688. UsedQuotaFiles: u.UsedQuotaFiles,
  689. LastQuotaUpdate: u.LastQuotaUpdate,
  690. UploadBandwidth: u.UploadBandwidth,
  691. DownloadBandwidth: u.DownloadBandwidth,
  692. Status: u.Status,
  693. ExpirationDate: u.ExpirationDate,
  694. LastLogin: u.LastLogin,
  695. Filters: filters,
  696. FsConfig: fsConfig,
  697. }
  698. }
  699. func (u *User) getNotificationFieldsAsSlice(action string) []string {
  700. return []string{action, u.Username,
  701. strconv.FormatInt(u.ID, 10),
  702. strconv.FormatInt(int64(u.Status), 10),
  703. strconv.FormatInt(u.ExpirationDate, 10),
  704. u.HomeDir,
  705. strconv.FormatInt(int64(u.UID), 10),
  706. strconv.FormatInt(int64(u.GID), 10),
  707. }
  708. }
  709. func (u *User) getNotificationFieldsAsEnvVars(action string) []string {
  710. return []string{fmt.Sprintf("SFTPGO_USER_ACTION=%v", action),
  711. fmt.Sprintf("SFTPGO_USER_USERNAME=%v", u.Username),
  712. fmt.Sprintf("SFTPGO_USER_PASSWORD=%v", u.Password),
  713. fmt.Sprintf("SFTPGO_USER_ID=%v", u.ID),
  714. fmt.Sprintf("SFTPGO_USER_STATUS=%v", u.Status),
  715. fmt.Sprintf("SFTPGO_USER_EXPIRATION_DATE=%v", u.ExpirationDate),
  716. fmt.Sprintf("SFTPGO_USER_HOME_DIR=%v", u.HomeDir),
  717. fmt.Sprintf("SFTPGO_USER_UID=%v", u.UID),
  718. fmt.Sprintf("SFTPGO_USER_GID=%v", u.GID),
  719. fmt.Sprintf("SFTPGO_USER_QUOTA_FILES=%v", u.QuotaFiles),
  720. fmt.Sprintf("SFTPGO_USER_QUOTA_SIZE=%v", u.QuotaSize),
  721. fmt.Sprintf("SFTPGO_USER_UPLOAD_BANDWIDTH=%v", u.UploadBandwidth),
  722. fmt.Sprintf("SFTPGO_USER_DOWNLOAD_BANDWIDTH=%v", u.DownloadBandwidth),
  723. fmt.Sprintf("SFTPGO_USER_MAX_SESSIONS=%v", u.MaxSessions),
  724. fmt.Sprintf("SFTPGO_USER_FS_PROVIDER=%v", u.FsConfig.Provider)}
  725. }
  726. func (u *User) getGCSCredentialsFilePath() string {
  727. return filepath.Join(credentialsDirPath, fmt.Sprintf("%v_gcs_credentials.json", u.Username))
  728. }