user.go 25 KB

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