user.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. package dataprovider
  2. import (
  3. "crypto/sha256"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "math"
  9. "net"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/sftpgo/sdk"
  17. "github.com/drakkan/sftpgo/v2/kms"
  18. "github.com/drakkan/sftpgo/v2/logger"
  19. "github.com/drakkan/sftpgo/v2/mfa"
  20. "github.com/drakkan/sftpgo/v2/util"
  21. "github.com/drakkan/sftpgo/v2/vfs"
  22. )
  23. // Available permissions for SFTPGo users
  24. const (
  25. // All permissions are granted
  26. PermAny = "*"
  27. // List items such as files and directories is allowed
  28. PermListItems = "list"
  29. // download files is allowed
  30. PermDownload = "download"
  31. // upload files is allowed
  32. PermUpload = "upload"
  33. // overwrite an existing file, while uploading, is allowed
  34. // upload permission is required to allow file overwrite
  35. PermOverwrite = "overwrite"
  36. // delete files or directories is allowed
  37. PermDelete = "delete"
  38. // delete files is allowed
  39. PermDeleteFiles = "delete_files"
  40. // delete directories is allowed
  41. PermDeleteDirs = "delete_dirs"
  42. // rename files or directories is allowed
  43. PermRename = "rename"
  44. // rename files is allowed
  45. PermRenameFiles = "rename_files"
  46. // rename directories is allowed
  47. PermRenameDirs = "rename_dirs"
  48. // create directories is allowed
  49. PermCreateDirs = "create_dirs"
  50. // create symbolic links is allowed
  51. PermCreateSymlinks = "create_symlinks"
  52. // changing file or directory permissions is allowed
  53. PermChmod = "chmod"
  54. // changing file or directory owner and group is allowed
  55. PermChown = "chown"
  56. // changing file or directory access and modification time is allowed
  57. PermChtimes = "chtimes"
  58. )
  59. // Available login methods
  60. const (
  61. LoginMethodNoAuthTryed = "no_auth_tryed"
  62. LoginMethodPassword = "password"
  63. SSHLoginMethodPublicKey = "publickey"
  64. SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
  65. SSHLoginMethodKeyAndPassword = "publickey+password"
  66. SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive"
  67. LoginMethodTLSCertificate = "TLSCertificate"
  68. LoginMethodTLSCertificateAndPwd = "TLSCertificate+password"
  69. )
  70. var (
  71. errNoMatchingVirtualFolder = errors.New("no matching virtual folder found")
  72. permsRenameAny = []string{PermRename, PermRenameDirs, PermRenameFiles}
  73. permsDeleteAny = []string{PermDelete, PermDeleteDirs, PermDeleteFiles}
  74. permsCreateAny = []string{PermUpload, PermCreateDirs}
  75. )
  76. // RecoveryCode defines a 2FA recovery code
  77. type RecoveryCode struct {
  78. Secret *kms.Secret `json:"secret"`
  79. Used bool `json:"used,omitempty"`
  80. }
  81. // UserTOTPConfig defines the time-based one time password configuration
  82. type UserTOTPConfig struct {
  83. Enabled bool `json:"enabled,omitempty"`
  84. ConfigName string `json:"config_name,omitempty"`
  85. Secret *kms.Secret `json:"secret,omitempty"`
  86. // TOTP will be required for the specified protocols.
  87. // SSH protocol (SFTP/SCP/SSH commands) will ask for the TOTP passcode if the client uses keyboard interactive
  88. // authentication.
  89. // FTP have no standard way to support two factor authentication, if you
  90. // enable the support for this protocol you have to add the TOTP passcode after the password.
  91. // For example if your password is "password" and your one time passcode is
  92. // "123456" you have to use "password123456" as password.
  93. Protocols []string `json:"protocols,omitempty"`
  94. }
  95. // UserFilters defines additional restrictions for a user
  96. // TODO: rename to UserOptions in v3
  97. type UserFilters struct {
  98. sdk.BaseUserFilters
  99. // Time-based one time passwords configuration
  100. TOTPConfig UserTOTPConfig `json:"totp_config,omitempty"`
  101. // Recovery codes to use if the user loses access to their second factor auth device.
  102. // Each code can only be used once, you should use these codes to login and disable or
  103. // reset 2FA for your account
  104. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  105. }
  106. // User defines a SFTPGo user
  107. type User struct {
  108. sdk.BaseUser
  109. // Additional restrictions
  110. Filters UserFilters `json:"filters"`
  111. // Mapping between virtual paths and virtual folders
  112. VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
  113. // Filesystem configuration details
  114. FsConfig vfs.Filesystem `json:"filesystem"`
  115. // we store the filesystem here using the base path as key.
  116. fsCache map[string]vfs.Fs `json:"-"`
  117. }
  118. // GetFilesystem returns the base filesystem for this user
  119. func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error) {
  120. fs, err = u.getRootFs(connectionID)
  121. if err != nil {
  122. return fs, err
  123. }
  124. u.fsCache = make(map[string]vfs.Fs)
  125. u.fsCache["/"] = fs
  126. return fs, err
  127. }
  128. func (u *User) getRootFs(connectionID string) (fs vfs.Fs, err error) {
  129. switch u.FsConfig.Provider {
  130. case sdk.S3FilesystemProvider:
  131. return vfs.NewS3Fs(connectionID, u.GetHomeDir(), "", u.FsConfig.S3Config)
  132. case sdk.GCSFilesystemProvider:
  133. config := u.FsConfig.GCSConfig
  134. config.CredentialFile = u.GetGCSCredentialsFilePath()
  135. return vfs.NewGCSFs(connectionID, u.GetHomeDir(), "", config)
  136. case sdk.AzureBlobFilesystemProvider:
  137. return vfs.NewAzBlobFs(connectionID, u.GetHomeDir(), "", u.FsConfig.AzBlobConfig)
  138. case sdk.CryptedFilesystemProvider:
  139. return vfs.NewCryptFs(connectionID, u.GetHomeDir(), "", u.FsConfig.CryptConfig)
  140. case sdk.SFTPFilesystemProvider:
  141. forbiddenSelfUsers, err := u.getForbiddenSFTPSelfUsers(u.FsConfig.SFTPConfig.Username)
  142. if err != nil {
  143. return nil, err
  144. }
  145. forbiddenSelfUsers = append(forbiddenSelfUsers, u.Username)
  146. return vfs.NewSFTPFs(connectionID, "", u.GetHomeDir(), forbiddenSelfUsers, u.FsConfig.SFTPConfig)
  147. default:
  148. return vfs.NewOsFs(connectionID, u.GetHomeDir(), ""), nil
  149. }
  150. }
  151. // CheckFsRoot check the root directory for the main fs and the virtual folders.
  152. // It returns an error if the main filesystem cannot be created
  153. func (u *User) CheckFsRoot(connectionID string) error {
  154. if u.Filters.DisableFsChecks {
  155. return nil
  156. }
  157. fs, err := u.GetFilesystemForPath("/", connectionID)
  158. if err != nil {
  159. logger.Warn(logSender, connectionID, "could not create main filesystem for user %#v err: %v", u.Username, err)
  160. return err
  161. }
  162. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  163. for idx := range u.VirtualFolders {
  164. v := &u.VirtualFolders[idx]
  165. fs, err = u.GetFilesystemForPath(v.VirtualPath, connectionID)
  166. if err == nil {
  167. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  168. }
  169. // now check intermediary folders
  170. fs, err = u.GetFilesystemForPath(path.Dir(v.VirtualPath), connectionID)
  171. if err == nil && !fs.HasVirtualFolders() {
  172. fsPath, err := fs.ResolvePath(v.VirtualPath)
  173. if err != nil {
  174. continue
  175. }
  176. err = fs.MkdirAll(fsPath, u.GetUID(), u.GetGID())
  177. logger.Debug(logSender, connectionID, "create intermediary dir to %#v, path %#v, err: %v",
  178. v.VirtualPath, fsPath, err)
  179. }
  180. }
  181. return nil
  182. }
  183. // isFsEqual returns true if the fs has the same configuration
  184. func (u *User) isFsEqual(other *User) bool {
  185. if u.FsConfig.Provider == sdk.LocalFilesystemProvider && u.GetHomeDir() != other.GetHomeDir() {
  186. return false
  187. }
  188. if !u.FsConfig.IsEqual(&other.FsConfig) {
  189. return false
  190. }
  191. if len(u.VirtualFolders) != len(other.VirtualFolders) {
  192. return false
  193. }
  194. for idx := range u.VirtualFolders {
  195. f := &u.VirtualFolders[idx]
  196. found := false
  197. for idx1 := range other.VirtualFolders {
  198. f1 := &other.VirtualFolders[idx1]
  199. if f.VirtualPath == f1.VirtualPath {
  200. found = true
  201. if f.FsConfig.Provider == sdk.LocalFilesystemProvider && f.MappedPath != f1.MappedPath {
  202. return false
  203. }
  204. if !f.FsConfig.IsEqual(&f1.FsConfig) {
  205. return false
  206. }
  207. }
  208. }
  209. if !found {
  210. return false
  211. }
  212. }
  213. return true
  214. }
  215. // CheckLoginConditions checks if the user is active and not expired
  216. func (u *User) CheckLoginConditions() error {
  217. if u.Status < 1 {
  218. return fmt.Errorf("user %#v is disabled", u.Username)
  219. }
  220. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  221. return fmt.Errorf("user %#v is expired, expiration timestamp: %v current timestamp: %v", u.Username,
  222. u.ExpirationDate, util.GetTimeAsMsSinceEpoch(time.Now()))
  223. }
  224. return nil
  225. }
  226. // hideConfidentialData hides user confidential data
  227. func (u *User) hideConfidentialData() {
  228. u.Password = ""
  229. u.FsConfig.HideConfidentialData()
  230. if u.Filters.TOTPConfig.Secret != nil {
  231. u.Filters.TOTPConfig.Secret.Hide()
  232. }
  233. for _, code := range u.Filters.RecoveryCodes {
  234. if code.Secret != nil {
  235. code.Secret.Hide()
  236. }
  237. }
  238. }
  239. // GetSubDirPermissions returns permissions for sub directories
  240. func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions {
  241. var result []sdk.DirectoryPermissions
  242. for k, v := range u.Permissions {
  243. if k == "/" {
  244. continue
  245. }
  246. dirPerms := sdk.DirectoryPermissions{
  247. Path: k,
  248. Permissions: v,
  249. }
  250. result = append(result, dirPerms)
  251. }
  252. return result
  253. }
  254. // RenderAsJSON implements the renderer interface used within plugins
  255. func (u *User) RenderAsJSON(reload bool) ([]byte, error) {
  256. if reload {
  257. user, err := provider.userExists(u.Username)
  258. if err != nil {
  259. providerLog(logger.LevelError, "unable to reload user before rendering as json: %v", err)
  260. return nil, err
  261. }
  262. user.PrepareForRendering()
  263. return json.Marshal(user)
  264. }
  265. u.PrepareForRendering()
  266. return json.Marshal(u)
  267. }
  268. // PrepareForRendering prepares a user for rendering.
  269. // It hides confidential data and set to nil the empty secrets
  270. // so they are not serialized
  271. func (u *User) PrepareForRendering() {
  272. u.hideConfidentialData()
  273. u.FsConfig.SetNilSecretsIfEmpty()
  274. for idx := range u.VirtualFolders {
  275. folder := &u.VirtualFolders[idx]
  276. folder.PrepareForRendering()
  277. }
  278. }
  279. // HasRedactedSecret returns true if the user has a redacted secret
  280. func (u *User) hasRedactedSecret() bool {
  281. if u.FsConfig.HasRedactedSecret() {
  282. return true
  283. }
  284. for idx := range u.VirtualFolders {
  285. folder := &u.VirtualFolders[idx]
  286. if folder.HasRedactedSecret() {
  287. return true
  288. }
  289. }
  290. return u.Filters.TOTPConfig.Secret.IsRedacted()
  291. }
  292. // CloseFs closes the underlying filesystems
  293. func (u *User) CloseFs() error {
  294. if u.fsCache == nil {
  295. return nil
  296. }
  297. var err error
  298. for _, fs := range u.fsCache {
  299. errClose := fs.Close()
  300. if err == nil {
  301. err = errClose
  302. }
  303. }
  304. return err
  305. }
  306. // IsPasswordHashed returns true if the password is hashed
  307. func (u *User) IsPasswordHashed() bool {
  308. return util.IsStringPrefixInSlice(u.Password, hashPwdPrefixes)
  309. }
  310. // IsTLSUsernameVerificationEnabled returns true if we need to extract the username
  311. // from the client TLS certificate
  312. func (u *User) IsTLSUsernameVerificationEnabled() bool {
  313. if u.Filters.TLSUsername != "" {
  314. return u.Filters.TLSUsername != sdk.TLSUsernameNone
  315. }
  316. return false
  317. }
  318. // SetEmptySecrets sets to empty any user secret
  319. func (u *User) SetEmptySecrets() {
  320. u.FsConfig.S3Config.AccessSecret = kms.NewEmptySecret()
  321. u.FsConfig.GCSConfig.Credentials = kms.NewEmptySecret()
  322. u.FsConfig.AzBlobConfig.AccountKey = kms.NewEmptySecret()
  323. u.FsConfig.AzBlobConfig.SASURL = kms.NewEmptySecret()
  324. u.FsConfig.CryptConfig.Passphrase = kms.NewEmptySecret()
  325. u.FsConfig.SFTPConfig.Password = kms.NewEmptySecret()
  326. u.FsConfig.SFTPConfig.PrivateKey = kms.NewEmptySecret()
  327. for idx := range u.VirtualFolders {
  328. folder := &u.VirtualFolders[idx]
  329. folder.FsConfig.SetEmptySecretsIfNil()
  330. }
  331. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  332. }
  333. // GetPermissionsForPath returns the permissions for the given path.
  334. // The path must be a SFTPGo exposed path
  335. func (u *User) GetPermissionsForPath(p string) []string {
  336. permissions := []string{}
  337. if perms, ok := u.Permissions["/"]; ok {
  338. // if only root permissions are defined returns them unconditionally
  339. if len(u.Permissions) == 1 {
  340. return perms
  341. }
  342. // fallback permissions
  343. permissions = perms
  344. }
  345. dirsForPath := util.GetDirsForVirtualPath(p)
  346. // dirsForPath contains all the dirs for a given path in reverse order
  347. // for example if the path is: /1/2/3/4 it contains:
  348. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  349. // so the first match is the one we are interested to
  350. for idx := range dirsForPath {
  351. if perms, ok := u.Permissions[dirsForPath[idx]]; ok {
  352. permissions = perms
  353. break
  354. }
  355. }
  356. return permissions
  357. }
  358. // HasBufferedSFTP returns true if the user has a SFTP filesystem with buffering enabled
  359. func (u *User) HasBufferedSFTP(name string) bool {
  360. fs := u.GetFsConfigForPath(name)
  361. if fs.Provider == sdk.SFTPFilesystemProvider {
  362. return fs.SFTPConfig.BufferSize > 0
  363. }
  364. return false
  365. }
  366. func (u *User) getForbiddenSFTPSelfUsers(username string) ([]string, error) {
  367. sftpUser, err := UserExists(username)
  368. if err == nil {
  369. // we don't allow local nested SFTP folders
  370. var forbiddens []string
  371. if sftpUser.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  372. forbiddens = append(forbiddens, sftpUser.Username)
  373. return forbiddens, nil
  374. }
  375. for idx := range sftpUser.VirtualFolders {
  376. v := &sftpUser.VirtualFolders[idx]
  377. if v.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  378. forbiddens = append(forbiddens, sftpUser.Username)
  379. return forbiddens, nil
  380. }
  381. }
  382. return forbiddens, nil
  383. }
  384. if _, ok := err.(*util.RecordNotFoundError); !ok {
  385. return nil, err
  386. }
  387. return nil, nil
  388. }
  389. // GetFsConfigForPath returns the file system configuration for the specified virtual path
  390. func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem {
  391. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  392. folder, err := u.GetVirtualFolderForPath(virtualPath)
  393. if err == nil {
  394. return folder.FsConfig
  395. }
  396. }
  397. return u.FsConfig
  398. }
  399. // GetFilesystemForPath returns the filesystem for the given path
  400. func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error) {
  401. if u.fsCache == nil {
  402. u.fsCache = make(map[string]vfs.Fs)
  403. }
  404. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  405. folder, err := u.GetVirtualFolderForPath(virtualPath)
  406. if err == nil {
  407. if fs, ok := u.fsCache[folder.VirtualPath]; ok {
  408. return fs, nil
  409. }
  410. forbiddenSelfUsers := []string{u.Username}
  411. if folder.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  412. forbiddens, err := u.getForbiddenSFTPSelfUsers(folder.FsConfig.SFTPConfig.Username)
  413. if err != nil {
  414. return nil, err
  415. }
  416. forbiddenSelfUsers = append(forbiddenSelfUsers, forbiddens...)
  417. }
  418. fs, err := folder.GetFilesystem(connectionID, forbiddenSelfUsers)
  419. if err == nil {
  420. u.fsCache[folder.VirtualPath] = fs
  421. }
  422. return fs, err
  423. }
  424. }
  425. if val, ok := u.fsCache["/"]; ok {
  426. return val, nil
  427. }
  428. return u.GetFilesystem(connectionID)
  429. }
  430. // GetVirtualFolderForPath returns the virtual folder containing the specified virtual path.
  431. // If the path is not inside a virtual folder an error is returned
  432. func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error) {
  433. var folder vfs.VirtualFolder
  434. if len(u.VirtualFolders) == 0 {
  435. return folder, errNoMatchingVirtualFolder
  436. }
  437. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  438. for index := range dirsForPath {
  439. for idx := range u.VirtualFolders {
  440. v := &u.VirtualFolders[idx]
  441. if v.VirtualPath == dirsForPath[index] {
  442. return *v, nil
  443. }
  444. }
  445. }
  446. return folder, errNoMatchingVirtualFolder
  447. }
  448. // CheckMetadataConsistency checks the consistency between the metadata stored
  449. // in the configured metadata plugin and the filesystem
  450. func (u *User) CheckMetadataConsistency() error {
  451. fs, err := u.getRootFs("")
  452. if err != nil {
  453. return err
  454. }
  455. defer fs.Close()
  456. if err = fs.CheckMetadata(); err != nil {
  457. return err
  458. }
  459. for idx := range u.VirtualFolders {
  460. v := &u.VirtualFolders[idx]
  461. if err = v.CheckMetadataConsistency(); err != nil {
  462. return err
  463. }
  464. }
  465. return nil
  466. }
  467. // ScanQuota scans the user home dir and virtual folders, included in its quota,
  468. // and returns the number of files and their size
  469. func (u *User) ScanQuota() (int, int64, error) {
  470. fs, err := u.getRootFs("")
  471. if err != nil {
  472. return 0, 0, err
  473. }
  474. defer fs.Close()
  475. numFiles, size, err := fs.ScanRootDirContents()
  476. if err != nil {
  477. return numFiles, size, err
  478. }
  479. for idx := range u.VirtualFolders {
  480. v := &u.VirtualFolders[idx]
  481. if !v.IsIncludedInUserQuota() {
  482. continue
  483. }
  484. num, s, err := v.ScanQuota()
  485. if err != nil {
  486. return numFiles, size, err
  487. }
  488. numFiles += num
  489. size += s
  490. }
  491. return numFiles, size, nil
  492. }
  493. // GetVirtualFoldersInPath returns the virtual folders inside virtualPath including
  494. // any parents
  495. func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool {
  496. result := make(map[string]bool)
  497. for idx := range u.VirtualFolders {
  498. v := &u.VirtualFolders[idx]
  499. dirsForPath := util.GetDirsForVirtualPath(v.VirtualPath)
  500. for index := range dirsForPath {
  501. d := dirsForPath[index]
  502. if d == "/" {
  503. continue
  504. }
  505. if path.Dir(d) == virtualPath {
  506. result[d] = true
  507. }
  508. }
  509. }
  510. return result
  511. }
  512. // AddVirtualDirs adds virtual folders, if defined, to the given files list
  513. func (u *User) AddVirtualDirs(list []os.FileInfo, virtualPath string) []os.FileInfo {
  514. if len(u.VirtualFolders) == 0 {
  515. return list
  516. }
  517. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  518. fi := vfs.NewFileInfo(dir, true, 0, time.Now(), false)
  519. found := false
  520. for index := range list {
  521. if list[index].Name() == fi.Name() {
  522. list[index] = fi
  523. found = true
  524. break
  525. }
  526. }
  527. if !found {
  528. list = append(list, fi)
  529. }
  530. }
  531. return list
  532. }
  533. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  534. // The filesystem path must be cleaned before calling this method
  535. func (u *User) IsMappedPath(fsPath string) bool {
  536. for idx := range u.VirtualFolders {
  537. v := &u.VirtualFolders[idx]
  538. if fsPath == v.MappedPath {
  539. return true
  540. }
  541. }
  542. return false
  543. }
  544. // IsVirtualFolder returns true if the specified virtual path is a virtual folder
  545. func (u *User) IsVirtualFolder(virtualPath string) bool {
  546. for idx := range u.VirtualFolders {
  547. v := &u.VirtualFolders[idx]
  548. if virtualPath == v.VirtualPath {
  549. return true
  550. }
  551. }
  552. return false
  553. }
  554. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  555. // specified virtual path. We assume that path are cleaned
  556. func (u *User) HasVirtualFoldersInside(virtualPath string) bool {
  557. if virtualPath == "/" && len(u.VirtualFolders) > 0 {
  558. return true
  559. }
  560. for idx := range u.VirtualFolders {
  561. v := &u.VirtualFolders[idx]
  562. if len(v.VirtualPath) > len(virtualPath) {
  563. if strings.HasPrefix(v.VirtualPath, virtualPath+"/") {
  564. return true
  565. }
  566. }
  567. }
  568. return false
  569. }
  570. // HasPermissionsInside returns true if the specified virtualPath has no permissions itself and
  571. // no subdirs with defined permissions
  572. func (u *User) HasPermissionsInside(virtualPath string) bool {
  573. for dir := range u.Permissions {
  574. if dir == virtualPath {
  575. return true
  576. } else if len(dir) > len(virtualPath) {
  577. if strings.HasPrefix(dir, virtualPath+"/") {
  578. return true
  579. }
  580. }
  581. }
  582. return false
  583. }
  584. // HasPerm returns true if the user has the given permission or any permission
  585. func (u *User) HasPerm(permission, path string) bool {
  586. perms := u.GetPermissionsForPath(path)
  587. if util.IsStringInSlice(PermAny, perms) {
  588. return true
  589. }
  590. return util.IsStringInSlice(permission, perms)
  591. }
  592. // HasAnyPerm returns true if the user has at least one of the given permissions
  593. func (u *User) HasAnyPerm(permissions []string, path string) bool {
  594. perms := u.GetPermissionsForPath(path)
  595. if util.IsStringInSlice(PermAny, perms) {
  596. return true
  597. }
  598. for _, permission := range permissions {
  599. if util.IsStringInSlice(permission, perms) {
  600. return true
  601. }
  602. }
  603. return false
  604. }
  605. // HasPerms returns true if the user has all the given permissions
  606. func (u *User) HasPerms(permissions []string, path string) bool {
  607. perms := u.GetPermissionsForPath(path)
  608. if util.IsStringInSlice(PermAny, perms) {
  609. return true
  610. }
  611. for _, permission := range permissions {
  612. if !util.IsStringInSlice(permission, perms) {
  613. return false
  614. }
  615. }
  616. return true
  617. }
  618. // HasPermsDeleteAll returns true if the user can delete both files and directories
  619. // for the given path
  620. func (u *User) HasPermsDeleteAll(path string) bool {
  621. perms := u.GetPermissionsForPath(path)
  622. canDeleteFiles := false
  623. canDeleteDirs := false
  624. for _, permission := range perms {
  625. if permission == PermAny || permission == PermDelete {
  626. return true
  627. }
  628. if permission == PermDeleteFiles {
  629. canDeleteFiles = true
  630. }
  631. if permission == PermDeleteDirs {
  632. canDeleteDirs = true
  633. }
  634. }
  635. return canDeleteFiles && canDeleteDirs
  636. }
  637. // HasPermsRenameAll returns true if the user can rename both files and directories
  638. // for the given path
  639. func (u *User) HasPermsRenameAll(path string) bool {
  640. perms := u.GetPermissionsForPath(path)
  641. canRenameFiles := false
  642. canRenameDirs := false
  643. for _, permission := range perms {
  644. if permission == PermAny || permission == PermRename {
  645. return true
  646. }
  647. if permission == PermRenameFiles {
  648. canRenameFiles = true
  649. }
  650. if permission == PermRenameDirs {
  651. canRenameDirs = true
  652. }
  653. }
  654. return canRenameFiles && canRenameDirs
  655. }
  656. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  657. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  658. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  659. return true
  660. }
  661. return false
  662. }
  663. // IsLoginMethodAllowed returns true if the specified login method is allowed
  664. func (u *User) IsLoginMethodAllowed(loginMethod string, partialSuccessMethods []string) bool {
  665. if len(u.Filters.DeniedLoginMethods) == 0 {
  666. return true
  667. }
  668. if len(partialSuccessMethods) == 1 {
  669. for _, method := range u.GetNextAuthMethods(partialSuccessMethods, true) {
  670. if method == loginMethod {
  671. return true
  672. }
  673. }
  674. }
  675. if util.IsStringInSlice(loginMethod, u.Filters.DeniedLoginMethods) {
  676. return false
  677. }
  678. return true
  679. }
  680. // GetNextAuthMethods returns the list of authentications methods that
  681. // can continue for multi-step authentication
  682. func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string {
  683. var methods []string
  684. if len(partialSuccessMethods) != 1 {
  685. return methods
  686. }
  687. if partialSuccessMethods[0] != SSHLoginMethodPublicKey {
  688. return methods
  689. }
  690. for _, method := range u.GetAllowedLoginMethods() {
  691. if method == SSHLoginMethodKeyAndPassword && isPasswordAuthEnabled {
  692. methods = append(methods, LoginMethodPassword)
  693. }
  694. if method == SSHLoginMethodKeyAndKeyboardInt {
  695. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  696. }
  697. }
  698. return methods
  699. }
  700. // IsPartialAuth returns true if the specified login method is a step for
  701. // a multi-step Authentication.
  702. // We support publickey+password and publickey+keyboard-interactive, so
  703. // only publickey can returns partial success.
  704. // We can have partial success if only multi-step Auth methods are enabled
  705. func (u *User) IsPartialAuth(loginMethod string) bool {
  706. if loginMethod != SSHLoginMethodPublicKey {
  707. return false
  708. }
  709. for _, method := range u.GetAllowedLoginMethods() {
  710. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd {
  711. continue
  712. }
  713. if !util.IsStringInSlice(method, SSHMultiStepsLoginMethods) {
  714. return false
  715. }
  716. }
  717. return true
  718. }
  719. // GetAllowedLoginMethods returns the allowed login methods
  720. func (u *User) GetAllowedLoginMethods() []string {
  721. var allowedMethods []string
  722. for _, method := range ValidLoginMethods {
  723. if !util.IsStringInSlice(method, u.Filters.DeniedLoginMethods) {
  724. allowedMethods = append(allowedMethods, method)
  725. }
  726. }
  727. return allowedMethods
  728. }
  729. // GetFlatFilePatterns returns file patterns as flat list
  730. // duplicating a path if it has both allowed and denied patterns
  731. func (u *User) GetFlatFilePatterns() []sdk.PatternsFilter {
  732. var result []sdk.PatternsFilter
  733. for _, pattern := range u.Filters.FilePatterns {
  734. if len(pattern.AllowedPatterns) > 0 {
  735. result = append(result, sdk.PatternsFilter{
  736. Path: pattern.Path,
  737. AllowedPatterns: pattern.AllowedPatterns,
  738. })
  739. }
  740. if len(pattern.DeniedPatterns) > 0 {
  741. result = append(result, sdk.PatternsFilter{
  742. Path: pattern.Path,
  743. DeniedPatterns: pattern.DeniedPatterns,
  744. })
  745. }
  746. }
  747. return result
  748. }
  749. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters
  750. func (u *User) IsFileAllowed(virtualPath string) bool {
  751. return u.isFilePatternAllowed(virtualPath)
  752. }
  753. func (u *User) isFilePatternAllowed(virtualPath string) bool {
  754. if len(u.Filters.FilePatterns) == 0 {
  755. return true
  756. }
  757. dirsForPath := util.GetDirsForVirtualPath(path.Dir(virtualPath))
  758. var filter sdk.PatternsFilter
  759. for _, dir := range dirsForPath {
  760. for _, f := range u.Filters.FilePatterns {
  761. if f.Path == dir {
  762. filter = f
  763. break
  764. }
  765. }
  766. if filter.Path != "" {
  767. break
  768. }
  769. }
  770. if filter.Path != "" {
  771. toMatch := strings.ToLower(path.Base(virtualPath))
  772. for _, denied := range filter.DeniedPatterns {
  773. matched, err := path.Match(denied, toMatch)
  774. if err != nil || matched {
  775. return false
  776. }
  777. }
  778. for _, allowed := range filter.AllowedPatterns {
  779. matched, err := path.Match(allowed, toMatch)
  780. if err == nil && matched {
  781. return true
  782. }
  783. }
  784. return len(filter.AllowedPatterns) == 0
  785. }
  786. return true
  787. }
  788. // CanManageMFA returns true if the user can add a multi-factor authentication configuration
  789. func (u *User) CanManageMFA() bool {
  790. if util.IsStringInSlice(sdk.WebClientMFADisabled, u.Filters.WebClient) {
  791. return false
  792. }
  793. return len(mfa.GetAvailableTOTPConfigs()) > 0
  794. }
  795. // CanManageShares returns true if the user can add, update and list shares
  796. func (u *User) CanManageShares() bool {
  797. return !util.IsStringInSlice(sdk.WebClientSharesDisabled, u.Filters.WebClient)
  798. }
  799. // CanResetPassword returns true if this user is allowed to reset its password
  800. func (u *User) CanResetPassword() bool {
  801. return !util.IsStringInSlice(sdk.WebClientPasswordResetDisabled, u.Filters.WebClient)
  802. }
  803. // CanChangePassword returns true if this user is allowed to change its password
  804. func (u *User) CanChangePassword() bool {
  805. return !util.IsStringInSlice(sdk.WebClientPasswordChangeDisabled, u.Filters.WebClient)
  806. }
  807. // CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
  808. func (u *User) CanChangeAPIKeyAuth() bool {
  809. return !util.IsStringInSlice(sdk.WebClientAPIKeyAuthChangeDisabled, u.Filters.WebClient)
  810. }
  811. // CanChangeInfo returns true if this user is allowed to change its info such as email and description
  812. func (u *User) CanChangeInfo() bool {
  813. return !util.IsStringInSlice(sdk.WebClientInfoChangeDisabled, u.Filters.WebClient)
  814. }
  815. // CanManagePublicKeys returns true if this user is allowed to manage public keys
  816. // from the web client. Used in web client UI
  817. func (u *User) CanManagePublicKeys() bool {
  818. return !util.IsStringInSlice(sdk.WebClientPubKeyChangeDisabled, u.Filters.WebClient)
  819. }
  820. // CanAddFilesFromWeb returns true if the client can add files from the web UI.
  821. // The specified target is the directory where the files must be uploaded
  822. func (u *User) CanAddFilesFromWeb(target string) bool {
  823. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  824. return false
  825. }
  826. return u.HasPerm(PermUpload, target) || u.HasPerm(PermOverwrite, target)
  827. }
  828. // CanAddDirsFromWeb returns true if the client can add directories from the web UI.
  829. // The specified target is the directory where the new directory must be created
  830. func (u *User) CanAddDirsFromWeb(target string) bool {
  831. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  832. return false
  833. }
  834. return u.HasPerm(PermCreateDirs, target)
  835. }
  836. // CanRenameFromWeb returns true if the client can rename objects from the web UI.
  837. // The specified src and dest are the source and target directories for the rename.
  838. func (u *User) CanRenameFromWeb(src, dest string) bool {
  839. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  840. return false
  841. }
  842. if u.HasAnyPerm(permsRenameAny, src) && u.HasAnyPerm(permsRenameAny, dest) {
  843. return true
  844. }
  845. if !u.HasAnyPerm(permsDeleteAny, src) {
  846. return false
  847. }
  848. return u.HasAnyPerm(permsCreateAny, dest)
  849. }
  850. // CanDeleteFromWeb returns true if the client can delete objects from the web UI.
  851. // The specified target is the parent directory for the object to delete
  852. func (u *User) CanDeleteFromWeb(target string) bool {
  853. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  854. return false
  855. }
  856. return u.HasAnyPerm(permsDeleteAny, target)
  857. }
  858. // GetSignature returns a signature for this admin.
  859. // It could change after an update
  860. func (u *User) GetSignature() string {
  861. data := []byte(fmt.Sprintf("%v_%v_%v", u.Username, u.Status, u.ExpirationDate))
  862. data = append(data, []byte(u.Password)...)
  863. signature := sha256.Sum256(data)
  864. return base64.StdEncoding.EncodeToString(signature[:])
  865. }
  866. // GetBandwidthForIP returns the upload and download bandwidth for the specified IP
  867. func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64) {
  868. if len(u.Filters.BandwidthLimits) > 0 {
  869. ip := net.ParseIP(clientIP)
  870. if ip != nil {
  871. for _, bwLimit := range u.Filters.BandwidthLimits {
  872. for _, source := range bwLimit.Sources {
  873. _, ipNet, err := net.ParseCIDR(source)
  874. if err == nil {
  875. if ipNet.Contains(ip) {
  876. logger.Debug(logSender, connectionID, "override bandwidth limit for ip %#v, upload limit: %v KB/s, download limit: %v KB/s",
  877. clientIP, bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth)
  878. return bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth
  879. }
  880. }
  881. }
  882. }
  883. }
  884. }
  885. return u.UploadBandwidth, u.DownloadBandwidth
  886. }
  887. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  888. // If AllowedIP is defined only the specified IP/Mask can login.
  889. // If DeniedIP is defined the specified IP/Mask cannot login.
  890. // If an IP is both allowed and denied then login will be denied
  891. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  892. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  893. return true
  894. }
  895. remoteIP := net.ParseIP(util.GetIPFromRemoteAddress(remoteAddr))
  896. // if remoteIP is invalid we allow login, this should never happen
  897. if remoteIP == nil {
  898. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %#v", remoteAddr)
  899. return true
  900. }
  901. for _, IPMask := range u.Filters.DeniedIP {
  902. _, IPNet, err := net.ParseCIDR(IPMask)
  903. if err != nil {
  904. return false
  905. }
  906. if IPNet.Contains(remoteIP) {
  907. return false
  908. }
  909. }
  910. for _, IPMask := range u.Filters.AllowedIP {
  911. _, IPNet, err := net.ParseCIDR(IPMask)
  912. if err != nil {
  913. return false
  914. }
  915. if IPNet.Contains(remoteIP) {
  916. return true
  917. }
  918. }
  919. return len(u.Filters.AllowedIP) == 0
  920. }
  921. // GetPermissionsAsJSON returns the permissions as json byte array
  922. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  923. return json.Marshal(u.Permissions)
  924. }
  925. // GetPublicKeysAsJSON returns the public keys as json byte array
  926. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  927. return json.Marshal(u.PublicKeys)
  928. }
  929. // GetFiltersAsJSON returns the filters as json byte array
  930. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  931. return json.Marshal(u.Filters)
  932. }
  933. // GetFsConfigAsJSON returns the filesystem config as json byte array
  934. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  935. return json.Marshal(u.FsConfig)
  936. }
  937. // GetUID returns a validate uid, suitable for use with os.Chown
  938. func (u *User) GetUID() int {
  939. if u.UID <= 0 || u.UID > math.MaxInt32 {
  940. return -1
  941. }
  942. return u.UID
  943. }
  944. // GetGID returns a validate gid, suitable for use with os.Chown
  945. func (u *User) GetGID() int {
  946. if u.GID <= 0 || u.GID > math.MaxInt32 {
  947. return -1
  948. }
  949. return u.GID
  950. }
  951. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  952. func (u *User) GetHomeDir() string {
  953. return filepath.Clean(u.HomeDir)
  954. }
  955. // HasQuotaRestrictions returns true if there is a quota restriction on number of files or size or both
  956. func (u *User) HasQuotaRestrictions() bool {
  957. return u.QuotaFiles > 0 || u.QuotaSize > 0
  958. }
  959. // GetQuotaSummary returns used quota and limits if defined
  960. func (u *User) GetQuotaSummary() string {
  961. var result string
  962. result = "Files: " + strconv.Itoa(u.UsedQuotaFiles)
  963. if u.QuotaFiles > 0 {
  964. result += "/" + strconv.Itoa(u.QuotaFiles)
  965. }
  966. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  967. result += ". Size: " + util.ByteCountIEC(u.UsedQuotaSize)
  968. if u.QuotaSize > 0 {
  969. result += "/" + util.ByteCountIEC(u.QuotaSize)
  970. }
  971. }
  972. if u.LastQuotaUpdate > 0 {
  973. t := util.GetTimeFromMsecSinceEpoch(u.LastQuotaUpdate)
  974. result += fmt.Sprintf(". Last update: %v ", t.Format("2006-01-02 15:04")) // YYYY-MM-DD HH:MM
  975. }
  976. return result
  977. }
  978. // GetPermissionsAsString returns the user's permissions as comma separated string
  979. func (u *User) GetPermissionsAsString() string {
  980. result := ""
  981. for dir, perms := range u.Permissions {
  982. dirPerms := strings.Join(perms, ", ")
  983. dp := fmt.Sprintf("%#v: %#v", dir, dirPerms)
  984. if dir == "/" {
  985. if result != "" {
  986. result = dp + ", " + result
  987. } else {
  988. result = dp
  989. }
  990. } else {
  991. if result != "" {
  992. result += ", "
  993. }
  994. result += dp
  995. }
  996. }
  997. return result
  998. }
  999. // GetBandwidthAsString returns bandwidth limits if defines
  1000. func (u *User) GetBandwidthAsString() string {
  1001. result := "DL: "
  1002. if u.DownloadBandwidth > 0 {
  1003. result += util.ByteCountIEC(u.DownloadBandwidth*1000) + "/s."
  1004. } else {
  1005. result += "unlimited."
  1006. }
  1007. result += " UL: "
  1008. if u.UploadBandwidth > 0 {
  1009. result += util.ByteCountIEC(u.UploadBandwidth*1000) + "/s."
  1010. } else {
  1011. result += "unlimited."
  1012. }
  1013. return result
  1014. }
  1015. // GetInfoString returns user's info as string.
  1016. // Storage provider, number of public keys, max sessions, uid,
  1017. // gid, denied and allowed IP/Mask are returned
  1018. func (u *User) GetInfoString() string {
  1019. var result strings.Builder
  1020. if u.LastLogin > 0 {
  1021. t := util.GetTimeFromMsecSinceEpoch(u.LastLogin)
  1022. result.WriteString(fmt.Sprintf("Last login: %v. ", t.Format("2006-01-02 15:04"))) // YYYY-MM-DD HH:MM
  1023. }
  1024. if u.FsConfig.Provider != sdk.LocalFilesystemProvider {
  1025. result.WriteString(fmt.Sprintf("Storage: %s. ", u.FsConfig.Provider.ShortInfo()))
  1026. }
  1027. if len(u.PublicKeys) > 0 {
  1028. result.WriteString(fmt.Sprintf("Public keys: %v. ", len(u.PublicKeys)))
  1029. }
  1030. if u.MaxSessions > 0 {
  1031. result.WriteString(fmt.Sprintf("Max sessions: %v. ", u.MaxSessions))
  1032. }
  1033. if u.UID > 0 {
  1034. result.WriteString(fmt.Sprintf("UID: %v. ", u.UID))
  1035. }
  1036. if u.GID > 0 {
  1037. result.WriteString(fmt.Sprintf("GID: %v. ", u.GID))
  1038. }
  1039. if len(u.Filters.DeniedIP) > 0 {
  1040. result.WriteString(fmt.Sprintf("Denied IP/Mask: %v. ", len(u.Filters.DeniedIP)))
  1041. }
  1042. if len(u.Filters.AllowedIP) > 0 {
  1043. result.WriteString(fmt.Sprintf("Allowed IP/Mask: %v", len(u.Filters.AllowedIP)))
  1044. }
  1045. return result.String()
  1046. }
  1047. // GetStatusAsString returns the user status as a string
  1048. func (u *User) GetStatusAsString() string {
  1049. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  1050. return "Expired"
  1051. }
  1052. if u.Status == 1 {
  1053. return "Active"
  1054. }
  1055. return "Inactive"
  1056. }
  1057. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  1058. func (u *User) GetExpirationDateAsString() string {
  1059. if u.ExpirationDate > 0 {
  1060. t := util.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  1061. return t.Format("2006-01-02")
  1062. }
  1063. return ""
  1064. }
  1065. // GetAllowedIPAsString returns the allowed IP as comma separated string
  1066. func (u *User) GetAllowedIPAsString() string {
  1067. return strings.Join(u.Filters.AllowedIP, ",")
  1068. }
  1069. // GetDeniedIPAsString returns the denied IP as comma separated string
  1070. func (u *User) GetDeniedIPAsString() string {
  1071. return strings.Join(u.Filters.DeniedIP, ",")
  1072. }
  1073. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  1074. func (u *User) CountUnusedRecoveryCodes() int {
  1075. unused := 0
  1076. for _, code := range u.Filters.RecoveryCodes {
  1077. if !code.Used {
  1078. unused++
  1079. }
  1080. }
  1081. return unused
  1082. }
  1083. // SetEmptySecretsIfNil sets the secrets to empty if nil
  1084. func (u *User) SetEmptySecretsIfNil() {
  1085. u.FsConfig.SetEmptySecretsIfNil()
  1086. for idx := range u.VirtualFolders {
  1087. vfolder := &u.VirtualFolders[idx]
  1088. vfolder.FsConfig.SetEmptySecretsIfNil()
  1089. }
  1090. if u.Filters.TOTPConfig.Secret == nil {
  1091. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  1092. }
  1093. }
  1094. func (u *User) getACopy() User {
  1095. u.SetEmptySecretsIfNil()
  1096. pubKeys := make([]string, len(u.PublicKeys))
  1097. copy(pubKeys, u.PublicKeys)
  1098. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  1099. for idx := range u.VirtualFolders {
  1100. vfolder := u.VirtualFolders[idx].GetACopy()
  1101. virtualFolders = append(virtualFolders, vfolder)
  1102. }
  1103. permissions := make(map[string][]string)
  1104. for k, v := range u.Permissions {
  1105. perms := make([]string, len(v))
  1106. copy(perms, v)
  1107. permissions[k] = perms
  1108. }
  1109. filters := UserFilters{}
  1110. filters.MaxUploadFileSize = u.Filters.MaxUploadFileSize
  1111. filters.TLSUsername = u.Filters.TLSUsername
  1112. filters.UserType = u.Filters.UserType
  1113. filters.TOTPConfig.Enabled = u.Filters.TOTPConfig.Enabled
  1114. filters.TOTPConfig.ConfigName = u.Filters.TOTPConfig.ConfigName
  1115. filters.TOTPConfig.Secret = u.Filters.TOTPConfig.Secret.Clone()
  1116. filters.TOTPConfig.Protocols = make([]string, len(u.Filters.TOTPConfig.Protocols))
  1117. copy(filters.TOTPConfig.Protocols, u.Filters.TOTPConfig.Protocols)
  1118. filters.AllowedIP = make([]string, len(u.Filters.AllowedIP))
  1119. copy(filters.AllowedIP, u.Filters.AllowedIP)
  1120. filters.DeniedIP = make([]string, len(u.Filters.DeniedIP))
  1121. copy(filters.DeniedIP, u.Filters.DeniedIP)
  1122. filters.DeniedLoginMethods = make([]string, len(u.Filters.DeniedLoginMethods))
  1123. copy(filters.DeniedLoginMethods, u.Filters.DeniedLoginMethods)
  1124. filters.FilePatterns = make([]sdk.PatternsFilter, len(u.Filters.FilePatterns))
  1125. copy(filters.FilePatterns, u.Filters.FilePatterns)
  1126. filters.DeniedProtocols = make([]string, len(u.Filters.DeniedProtocols))
  1127. copy(filters.DeniedProtocols, u.Filters.DeniedProtocols)
  1128. filters.Hooks.ExternalAuthDisabled = u.Filters.Hooks.ExternalAuthDisabled
  1129. filters.Hooks.PreLoginDisabled = u.Filters.Hooks.PreLoginDisabled
  1130. filters.Hooks.CheckPasswordDisabled = u.Filters.Hooks.CheckPasswordDisabled
  1131. filters.DisableFsChecks = u.Filters.DisableFsChecks
  1132. filters.AllowAPIKeyAuth = u.Filters.AllowAPIKeyAuth
  1133. filters.WebClient = make([]string, len(u.Filters.WebClient))
  1134. copy(filters.WebClient, u.Filters.WebClient)
  1135. filters.RecoveryCodes = make([]RecoveryCode, 0, len(u.Filters.RecoveryCodes))
  1136. for _, code := range u.Filters.RecoveryCodes {
  1137. if code.Secret == nil {
  1138. code.Secret = kms.NewEmptySecret()
  1139. }
  1140. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  1141. Secret: code.Secret.Clone(),
  1142. Used: code.Used,
  1143. })
  1144. }
  1145. filters.BandwidthLimits = make([]sdk.BandwidthLimit, 0, len(u.Filters.BandwidthLimits))
  1146. for _, limit := range u.Filters.BandwidthLimits {
  1147. bwLimit := sdk.BandwidthLimit{
  1148. UploadBandwidth: limit.UploadBandwidth,
  1149. DownloadBandwidth: limit.DownloadBandwidth,
  1150. Sources: make([]string, 0, len(limit.Sources)),
  1151. }
  1152. bwLimit.Sources = make([]string, len(limit.Sources))
  1153. copy(bwLimit.Sources, limit.Sources)
  1154. filters.BandwidthLimits = append(filters.BandwidthLimits, bwLimit)
  1155. }
  1156. return User{
  1157. BaseUser: sdk.BaseUser{
  1158. ID: u.ID,
  1159. Username: u.Username,
  1160. Email: u.Email,
  1161. Password: u.Password,
  1162. PublicKeys: pubKeys,
  1163. HomeDir: u.HomeDir,
  1164. UID: u.UID,
  1165. GID: u.GID,
  1166. MaxSessions: u.MaxSessions,
  1167. QuotaSize: u.QuotaSize,
  1168. QuotaFiles: u.QuotaFiles,
  1169. Permissions: permissions,
  1170. UsedQuotaSize: u.UsedQuotaSize,
  1171. UsedQuotaFiles: u.UsedQuotaFiles,
  1172. LastQuotaUpdate: u.LastQuotaUpdate,
  1173. UploadBandwidth: u.UploadBandwidth,
  1174. DownloadBandwidth: u.DownloadBandwidth,
  1175. Status: u.Status,
  1176. ExpirationDate: u.ExpirationDate,
  1177. LastLogin: u.LastLogin,
  1178. AdditionalInfo: u.AdditionalInfo,
  1179. Description: u.Description,
  1180. CreatedAt: u.CreatedAt,
  1181. UpdatedAt: u.UpdatedAt,
  1182. },
  1183. Filters: filters,
  1184. VirtualFolders: virtualFolders,
  1185. FsConfig: u.FsConfig.GetACopy(),
  1186. }
  1187. }
  1188. // GetEncryptionAdditionalData returns the additional data to use for AEAD
  1189. func (u *User) GetEncryptionAdditionalData() string {
  1190. return u.Username
  1191. }
  1192. // GetGCSCredentialsFilePath returns the path for GCS credentials
  1193. func (u *User) GetGCSCredentialsFilePath() string {
  1194. return filepath.Join(credentialsDirPath, fmt.Sprintf("%v_gcs_credentials.json", u.Username))
  1195. }