user.go 38 KB

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