user.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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. "strings"
  14. "time"
  15. "github.com/sftpgo/sdk"
  16. "github.com/drakkan/sftpgo/v2/kms"
  17. "github.com/drakkan/sftpgo/v2/logger"
  18. "github.com/drakkan/sftpgo/v2/mfa"
  19. "github.com/drakkan/sftpgo/v2/plugin"
  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. SSHLoginMethodPassword = "password-over-SSH"
  64. SSHLoginMethodPublicKey = "publickey"
  65. SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
  66. SSHLoginMethodKeyAndPassword = "publickey+password"
  67. SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive"
  68. LoginMethodTLSCertificate = "TLSCertificate"
  69. LoginMethodTLSCertificateAndPwd = "TLSCertificate+password"
  70. LoginMethodIDP = "IDP"
  71. )
  72. var (
  73. errNoMatchingVirtualFolder = errors.New("no matching virtual folder found")
  74. permsRenameAny = []string{PermRename, PermRenameDirs, PermRenameFiles}
  75. permsDeleteAny = []string{PermDelete, PermDeleteDirs, PermDeleteFiles}
  76. )
  77. // RecoveryCode defines a 2FA recovery code
  78. type RecoveryCode struct {
  79. Secret *kms.Secret `json:"secret"`
  80. Used bool `json:"used,omitempty"`
  81. }
  82. // UserTOTPConfig defines the time-based one time password configuration
  83. type UserTOTPConfig struct {
  84. Enabled bool `json:"enabled,omitempty"`
  85. ConfigName string `json:"config_name,omitempty"`
  86. Secret *kms.Secret `json:"secret,omitempty"`
  87. // TOTP will be required for the specified protocols.
  88. // SSH protocol (SFTP/SCP/SSH commands) will ask for the TOTP passcode if the client uses keyboard interactive
  89. // authentication.
  90. // FTP have no standard way to support two factor authentication, if you
  91. // enable the support for this protocol you have to add the TOTP passcode after the password.
  92. // For example if your password is "password" and your one time passcode is
  93. // "123456" you have to use "password123456" as password.
  94. Protocols []string `json:"protocols,omitempty"`
  95. }
  96. // UserFilters defines additional restrictions for a user
  97. // TODO: rename to UserOptions in v3
  98. type UserFilters struct {
  99. sdk.BaseUserFilters
  100. // Time-based one time passwords configuration
  101. TOTPConfig UserTOTPConfig `json:"totp_config,omitempty"`
  102. // Recovery codes to use if the user loses access to their second factor auth device.
  103. // Each code can only be used once, you should use these codes to login and disable or
  104. // reset 2FA for your account
  105. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  106. }
  107. // User defines a SFTPGo user
  108. type User struct {
  109. sdk.BaseUser
  110. // Additional restrictions
  111. Filters UserFilters `json:"filters"`
  112. // Mapping between virtual paths and virtual folders
  113. VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
  114. // Filesystem configuration details
  115. FsConfig vfs.Filesystem `json:"filesystem"`
  116. // groups associated with this user
  117. Groups []sdk.GroupMapping `json:"groups,omitempty"`
  118. // we store the filesystem here using the base path as key.
  119. fsCache map[string]vfs.Fs `json:"-"`
  120. // true if group settings are already applied for this user
  121. groupSettingsApplied bool `json:"-"`
  122. }
  123. // GetFilesystem returns the base filesystem for this user
  124. func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error) {
  125. return u.GetFilesystemForPath("/", connectionID)
  126. }
  127. func (u *User) getRootFs(connectionID string) (fs vfs.Fs, err error) {
  128. switch u.FsConfig.Provider {
  129. case sdk.S3FilesystemProvider:
  130. return vfs.NewS3Fs(connectionID, u.GetHomeDir(), "", u.FsConfig.S3Config)
  131. case sdk.GCSFilesystemProvider:
  132. return vfs.NewGCSFs(connectionID, u.GetHomeDir(), "", u.FsConfig.GCSConfig)
  133. case sdk.AzureBlobFilesystemProvider:
  134. return vfs.NewAzBlobFs(connectionID, u.GetHomeDir(), "", u.FsConfig.AzBlobConfig)
  135. case sdk.CryptedFilesystemProvider:
  136. return vfs.NewCryptFs(connectionID, u.GetHomeDir(), "", u.FsConfig.CryptConfig)
  137. case sdk.SFTPFilesystemProvider:
  138. forbiddenSelfUsers, err := u.getForbiddenSFTPSelfUsers(u.FsConfig.SFTPConfig.Username)
  139. if err != nil {
  140. return nil, err
  141. }
  142. forbiddenSelfUsers = append(forbiddenSelfUsers, u.Username)
  143. return vfs.NewSFTPFs(connectionID, "", u.GetHomeDir(), forbiddenSelfUsers, u.FsConfig.SFTPConfig)
  144. default:
  145. return vfs.NewOsFs(connectionID, u.GetHomeDir(), ""), nil
  146. }
  147. }
  148. func (u *User) checkDirWithParents(virtualDirPath, connectionID string) error {
  149. dirs := util.GetDirsForVirtualPath(virtualDirPath)
  150. for idx := len(dirs) - 1; idx >= 0; idx-- {
  151. vPath := dirs[idx]
  152. if vPath == "/" {
  153. continue
  154. }
  155. fs, err := u.GetFilesystemForPath(vPath, connectionID)
  156. if err != nil {
  157. return fmt.Errorf("unable to get fs for path %#v: %w", vPath, err)
  158. }
  159. if fs.HasVirtualFolders() {
  160. continue
  161. }
  162. fsPath, err := fs.ResolvePath(vPath)
  163. if err != nil {
  164. return fmt.Errorf("unable to resolve path %#v: %w", vPath, err)
  165. }
  166. _, err = fs.Stat(fsPath)
  167. if err == nil {
  168. continue
  169. }
  170. if fs.IsNotExist(err) {
  171. err = fs.Mkdir(fsPath)
  172. if err != nil {
  173. return err
  174. }
  175. vfs.SetPathPermissions(fs, fsPath, u.GetUID(), u.GetGID())
  176. } else {
  177. return fmt.Errorf("unable to stat path %#v: %w", vPath, err)
  178. }
  179. }
  180. return nil
  181. }
  182. // CheckFsRoot check the root directory for the main fs and the virtual folders.
  183. // It returns an error if the main filesystem cannot be created
  184. func (u *User) CheckFsRoot(connectionID string) error {
  185. if u.Filters.DisableFsChecks {
  186. return nil
  187. }
  188. delay := lastLoginMinDelay
  189. if u.Filters.ExternalAuthCacheTime > 0 {
  190. cacheTime := time.Duration(u.Filters.ExternalAuthCacheTime) * time.Second
  191. if cacheTime > delay {
  192. delay = cacheTime
  193. }
  194. }
  195. if isLastActivityRecent(u.LastLogin, delay) {
  196. if u.LastLogin > u.UpdatedAt {
  197. return nil
  198. }
  199. }
  200. fs, err := u.GetFilesystemForPath("/", connectionID)
  201. if err != nil {
  202. logger.Warn(logSender, connectionID, "could not create main filesystem for user %#v err: %v", u.Username, err)
  203. return err
  204. }
  205. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  206. if u.Filters.StartDirectory != "" {
  207. err = u.checkDirWithParents(u.Filters.StartDirectory, connectionID)
  208. if err != nil {
  209. logger.Warn(logSender, connectionID, "could not create start directory %#v, err: %v",
  210. u.Filters.StartDirectory, err)
  211. }
  212. }
  213. for idx := range u.VirtualFolders {
  214. v := &u.VirtualFolders[idx]
  215. fs, err = u.GetFilesystemForPath(v.VirtualPath, connectionID)
  216. if err == nil {
  217. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  218. }
  219. // now check intermediary folders
  220. err = u.checkDirWithParents(path.Dir(v.VirtualPath), connectionID)
  221. if err != nil {
  222. logger.Warn(logSender, connectionID, "could not create intermediary dir to %#v, err: %v", v.VirtualPath, err)
  223. }
  224. }
  225. return nil
  226. }
  227. // GetCleanedPath returns a clean POSIX absolute path using the user start directory as base
  228. // if the provided rawVirtualPath is relative
  229. func (u *User) GetCleanedPath(rawVirtualPath string) string {
  230. if u.Filters.StartDirectory != "" {
  231. if !path.IsAbs(rawVirtualPath) {
  232. var b strings.Builder
  233. b.Grow(len(u.Filters.StartDirectory) + 1 + len(rawVirtualPath))
  234. b.WriteString(u.Filters.StartDirectory)
  235. b.WriteString("/")
  236. b.WriteString(rawVirtualPath)
  237. return util.CleanPath(b.String())
  238. }
  239. }
  240. return util.CleanPath(rawVirtualPath)
  241. }
  242. // isFsEqual returns true if the filesystem configurations are the same
  243. func (u *User) isFsEqual(other *User) bool {
  244. if u.FsConfig.Provider == sdk.LocalFilesystemProvider && u.GetHomeDir() != other.GetHomeDir() {
  245. return false
  246. }
  247. if !u.FsConfig.IsEqual(&other.FsConfig) {
  248. return false
  249. }
  250. if u.Filters.StartDirectory != other.Filters.StartDirectory {
  251. return false
  252. }
  253. if len(u.VirtualFolders) != len(other.VirtualFolders) {
  254. return false
  255. }
  256. for idx := range u.VirtualFolders {
  257. f := &u.VirtualFolders[idx]
  258. found := false
  259. for idx1 := range other.VirtualFolders {
  260. f1 := &other.VirtualFolders[idx1]
  261. if f.VirtualPath == f1.VirtualPath {
  262. found = true
  263. if f.FsConfig.Provider == sdk.LocalFilesystemProvider && f.MappedPath != f1.MappedPath {
  264. return false
  265. }
  266. if !f.FsConfig.IsEqual(&f1.FsConfig) {
  267. return false
  268. }
  269. }
  270. }
  271. if !found {
  272. return false
  273. }
  274. }
  275. return true
  276. }
  277. // CheckLoginConditions checks if the user is active and not expired
  278. func (u *User) CheckLoginConditions() error {
  279. if u.Status < 1 {
  280. return fmt.Errorf("user %#v is disabled", u.Username)
  281. }
  282. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  283. return fmt.Errorf("user %#v is expired, expiration timestamp: %v current timestamp: %v", u.Username,
  284. u.ExpirationDate, util.GetTimeAsMsSinceEpoch(time.Now()))
  285. }
  286. return nil
  287. }
  288. // hideConfidentialData hides user confidential data
  289. func (u *User) hideConfidentialData() {
  290. u.Password = ""
  291. u.FsConfig.HideConfidentialData()
  292. if u.Filters.TOTPConfig.Secret != nil {
  293. u.Filters.TOTPConfig.Secret.Hide()
  294. }
  295. for _, code := range u.Filters.RecoveryCodes {
  296. if code.Secret != nil {
  297. code.Secret.Hide()
  298. }
  299. }
  300. }
  301. // GetSubDirPermissions returns permissions for sub directories
  302. func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions {
  303. var result []sdk.DirectoryPermissions
  304. for k, v := range u.Permissions {
  305. if k == "/" {
  306. continue
  307. }
  308. dirPerms := sdk.DirectoryPermissions{
  309. Path: k,
  310. Permissions: v,
  311. }
  312. result = append(result, dirPerms)
  313. }
  314. return result
  315. }
  316. // RenderAsJSON implements the renderer interface used within plugins
  317. func (u *User) RenderAsJSON(reload bool) ([]byte, error) {
  318. if reload {
  319. user, err := provider.userExists(u.Username)
  320. if err != nil {
  321. providerLog(logger.LevelError, "unable to reload user before rendering as json: %v", err)
  322. return nil, err
  323. }
  324. user.PrepareForRendering()
  325. return json.Marshal(user)
  326. }
  327. u.PrepareForRendering()
  328. return json.Marshal(u)
  329. }
  330. // PrepareForRendering prepares a user for rendering.
  331. // It hides confidential data and set to nil the empty secrets
  332. // so they are not serialized
  333. func (u *User) PrepareForRendering() {
  334. u.hideConfidentialData()
  335. u.FsConfig.SetNilSecretsIfEmpty()
  336. for idx := range u.VirtualFolders {
  337. folder := &u.VirtualFolders[idx]
  338. folder.PrepareForRendering()
  339. }
  340. }
  341. // HasRedactedSecret returns true if the user has a redacted secret
  342. func (u *User) hasRedactedSecret() bool {
  343. if u.FsConfig.HasRedactedSecret() {
  344. return true
  345. }
  346. for idx := range u.VirtualFolders {
  347. folder := &u.VirtualFolders[idx]
  348. if folder.HasRedactedSecret() {
  349. return true
  350. }
  351. }
  352. return u.Filters.TOTPConfig.Secret.IsRedacted()
  353. }
  354. // CloseFs closes the underlying filesystems
  355. func (u *User) CloseFs() error {
  356. if u.fsCache == nil {
  357. return nil
  358. }
  359. var err error
  360. for _, fs := range u.fsCache {
  361. errClose := fs.Close()
  362. if err == nil {
  363. err = errClose
  364. }
  365. }
  366. return err
  367. }
  368. // IsPasswordHashed returns true if the password is hashed
  369. func (u *User) IsPasswordHashed() bool {
  370. return util.IsStringPrefixInSlice(u.Password, hashPwdPrefixes)
  371. }
  372. // IsTLSUsernameVerificationEnabled returns true if we need to extract the username
  373. // from the client TLS certificate
  374. func (u *User) IsTLSUsernameVerificationEnabled() bool {
  375. if u.Filters.TLSUsername != "" {
  376. return u.Filters.TLSUsername != sdk.TLSUsernameNone
  377. }
  378. return false
  379. }
  380. // SetEmptySecrets sets to empty any user secret
  381. func (u *User) SetEmptySecrets() {
  382. u.FsConfig.SetEmptySecrets()
  383. for idx := range u.VirtualFolders {
  384. folder := &u.VirtualFolders[idx]
  385. folder.FsConfig.SetEmptySecrets()
  386. }
  387. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  388. }
  389. // GetPermissionsForPath returns the permissions for the given path.
  390. // The path must be a SFTPGo exposed path
  391. func (u *User) GetPermissionsForPath(p string) []string {
  392. permissions := []string{}
  393. if perms, ok := u.Permissions["/"]; ok {
  394. // if only root permissions are defined returns them unconditionally
  395. if len(u.Permissions) == 1 {
  396. return perms
  397. }
  398. // fallback permissions
  399. permissions = perms
  400. }
  401. dirsForPath := util.GetDirsForVirtualPath(p)
  402. // dirsForPath contains all the dirs for a given path in reverse order
  403. // for example if the path is: /1/2/3/4 it contains:
  404. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  405. // so the first match is the one we are interested to
  406. for idx := range dirsForPath {
  407. if perms, ok := u.Permissions[dirsForPath[idx]]; ok {
  408. permissions = perms
  409. break
  410. }
  411. }
  412. return permissions
  413. }
  414. // HasBufferedSFTP returns true if the user has a SFTP filesystem with buffering enabled
  415. func (u *User) HasBufferedSFTP(name string) bool {
  416. fs := u.GetFsConfigForPath(name)
  417. if fs.Provider == sdk.SFTPFilesystemProvider {
  418. return fs.SFTPConfig.BufferSize > 0
  419. }
  420. return false
  421. }
  422. func (u *User) getForbiddenSFTPSelfUsers(username string) ([]string, error) {
  423. sftpUser, err := UserExists(username)
  424. if err == nil {
  425. err = sftpUser.LoadAndApplyGroupSettings()
  426. }
  427. if err == nil {
  428. // we don't allow local nested SFTP folders
  429. var forbiddens []string
  430. if sftpUser.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  431. forbiddens = append(forbiddens, sftpUser.Username)
  432. return forbiddens, nil
  433. }
  434. for idx := range sftpUser.VirtualFolders {
  435. v := &sftpUser.VirtualFolders[idx]
  436. if v.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  437. forbiddens = append(forbiddens, sftpUser.Username)
  438. return forbiddens, nil
  439. }
  440. }
  441. return forbiddens, nil
  442. }
  443. if _, ok := err.(*util.RecordNotFoundError); !ok {
  444. return nil, err
  445. }
  446. return nil, nil
  447. }
  448. // GetFsConfigForPath returns the file system configuration for the specified virtual path
  449. func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem {
  450. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  451. folder, err := u.GetVirtualFolderForPath(virtualPath)
  452. if err == nil {
  453. return folder.FsConfig
  454. }
  455. }
  456. return u.FsConfig
  457. }
  458. // GetFilesystemForPath returns the filesystem for the given path
  459. func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error) {
  460. if u.fsCache == nil {
  461. u.fsCache = make(map[string]vfs.Fs)
  462. }
  463. // allow to override the `/` path with a virtual folder
  464. if len(u.VirtualFolders) > 0 {
  465. folder, err := u.GetVirtualFolderForPath(virtualPath)
  466. if err == nil {
  467. if fs, ok := u.fsCache[folder.VirtualPath]; ok {
  468. return fs, nil
  469. }
  470. forbiddenSelfUsers := []string{u.Username}
  471. if folder.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  472. forbiddens, err := u.getForbiddenSFTPSelfUsers(folder.FsConfig.SFTPConfig.Username)
  473. if err != nil {
  474. return nil, err
  475. }
  476. forbiddenSelfUsers = append(forbiddenSelfUsers, forbiddens...)
  477. }
  478. fs, err := folder.GetFilesystem(connectionID, forbiddenSelfUsers)
  479. if err == nil {
  480. u.fsCache[folder.VirtualPath] = fs
  481. }
  482. return fs, err
  483. }
  484. }
  485. if val, ok := u.fsCache["/"]; ok {
  486. return val, nil
  487. }
  488. fs, err := u.getRootFs(connectionID)
  489. if err != nil {
  490. return fs, err
  491. }
  492. u.fsCache["/"] = fs
  493. return fs, err
  494. }
  495. // GetVirtualFolderForPath returns the virtual folder containing the specified virtual path.
  496. // If the path is not inside a virtual folder an error is returned
  497. func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error) {
  498. var folder vfs.VirtualFolder
  499. if len(u.VirtualFolders) == 0 {
  500. return folder, errNoMatchingVirtualFolder
  501. }
  502. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  503. for index := range dirsForPath {
  504. for idx := range u.VirtualFolders {
  505. v := &u.VirtualFolders[idx]
  506. if v.VirtualPath == dirsForPath[index] {
  507. return *v, nil
  508. }
  509. }
  510. }
  511. return folder, errNoMatchingVirtualFolder
  512. }
  513. // CheckMetadataConsistency checks the consistency between the metadata stored
  514. // in the configured metadata plugin and the filesystem
  515. func (u *User) CheckMetadataConsistency() error {
  516. fs, err := u.getRootFs("")
  517. if err != nil {
  518. return err
  519. }
  520. defer fs.Close()
  521. if err = fs.CheckMetadata(); err != nil {
  522. return err
  523. }
  524. for idx := range u.VirtualFolders {
  525. v := &u.VirtualFolders[idx]
  526. if err = v.CheckMetadataConsistency(); err != nil {
  527. return err
  528. }
  529. }
  530. return nil
  531. }
  532. // ScanQuota scans the user home dir and virtual folders, included in its quota,
  533. // and returns the number of files and their size
  534. func (u *User) ScanQuota() (int, int64, error) {
  535. fs, err := u.getRootFs("")
  536. if err != nil {
  537. return 0, 0, err
  538. }
  539. defer fs.Close()
  540. numFiles, size, err := fs.ScanRootDirContents()
  541. if err != nil {
  542. return numFiles, size, err
  543. }
  544. for idx := range u.VirtualFolders {
  545. v := &u.VirtualFolders[idx]
  546. if !v.IsIncludedInUserQuota() {
  547. continue
  548. }
  549. num, s, err := v.ScanQuota()
  550. if err != nil {
  551. return numFiles, size, err
  552. }
  553. numFiles += num
  554. size += s
  555. }
  556. return numFiles, size, nil
  557. }
  558. // GetVirtualFoldersInPath returns the virtual folders inside virtualPath including
  559. // any parents
  560. func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool {
  561. result := make(map[string]bool)
  562. for idx := range u.VirtualFolders {
  563. v := &u.VirtualFolders[idx]
  564. dirsForPath := util.GetDirsForVirtualPath(v.VirtualPath)
  565. for index := range dirsForPath {
  566. d := dirsForPath[index]
  567. if d == "/" {
  568. continue
  569. }
  570. if path.Dir(d) == virtualPath {
  571. result[d] = true
  572. }
  573. }
  574. }
  575. if u.Filters.StartDirectory != "" {
  576. dirsForPath := util.GetDirsForVirtualPath(u.Filters.StartDirectory)
  577. for index := range dirsForPath {
  578. d := dirsForPath[index]
  579. if d == "/" {
  580. continue
  581. }
  582. if path.Dir(d) == virtualPath {
  583. result[d] = true
  584. }
  585. }
  586. }
  587. return result
  588. }
  589. func (u *User) hasVirtualDirs() bool {
  590. if u.Filters.StartDirectory != "" {
  591. return true
  592. }
  593. numFolders := len(u.VirtualFolders)
  594. if numFolders == 1 {
  595. return u.VirtualFolders[0].VirtualPath != "/"
  596. }
  597. return numFolders > 0
  598. }
  599. // FilterListDir adds virtual folders and remove hidden items from the given files list
  600. func (u *User) FilterListDir(dirContents []os.FileInfo, virtualPath string) []os.FileInfo {
  601. filter := u.getPatternsFilterForPath(virtualPath)
  602. if !u.hasVirtualDirs() && filter.DenyPolicy != sdk.DenyPolicyHide {
  603. return dirContents
  604. }
  605. vdirs := make(map[string]bool)
  606. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  607. dirName := path.Base(dir)
  608. if filter.DenyPolicy == sdk.DenyPolicyHide {
  609. if !filter.CheckAllowed(dirName) {
  610. continue
  611. }
  612. }
  613. vdirs[dirName] = true
  614. }
  615. validIdx := 0
  616. for index, fi := range dirContents {
  617. for dir := range vdirs {
  618. if fi.Name() == dir {
  619. if !fi.IsDir() {
  620. fi = vfs.NewFileInfo(dir, true, 0, time.Now(), false)
  621. dirContents[index] = fi
  622. }
  623. delete(vdirs, dir)
  624. }
  625. }
  626. if filter.DenyPolicy == sdk.DenyPolicyHide {
  627. if filter.CheckAllowed(fi.Name()) {
  628. dirContents[validIdx] = fi
  629. validIdx++
  630. }
  631. }
  632. }
  633. if filter.DenyPolicy == sdk.DenyPolicyHide {
  634. for idx := validIdx; idx < len(dirContents); idx++ {
  635. dirContents[idx] = nil
  636. }
  637. dirContents = dirContents[:validIdx]
  638. }
  639. for dir := range vdirs {
  640. fi := vfs.NewFileInfo(dir, true, 0, time.Now(), false)
  641. dirContents = append(dirContents, fi)
  642. }
  643. return dirContents
  644. }
  645. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  646. // The filesystem path must be cleaned before calling this method
  647. func (u *User) IsMappedPath(fsPath string) bool {
  648. for idx := range u.VirtualFolders {
  649. v := &u.VirtualFolders[idx]
  650. if fsPath == v.MappedPath {
  651. return true
  652. }
  653. }
  654. return false
  655. }
  656. // IsVirtualFolder returns true if the specified virtual path is a virtual folder
  657. func (u *User) IsVirtualFolder(virtualPath string) bool {
  658. for idx := range u.VirtualFolders {
  659. v := &u.VirtualFolders[idx]
  660. if virtualPath == v.VirtualPath {
  661. return true
  662. }
  663. }
  664. return false
  665. }
  666. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  667. // specified virtual path. We assume that path are cleaned
  668. func (u *User) HasVirtualFoldersInside(virtualPath string) bool {
  669. if virtualPath == "/" && len(u.VirtualFolders) > 0 {
  670. return true
  671. }
  672. for idx := range u.VirtualFolders {
  673. v := &u.VirtualFolders[idx]
  674. if len(v.VirtualPath) > len(virtualPath) {
  675. if strings.HasPrefix(v.VirtualPath, virtualPath+"/") {
  676. return true
  677. }
  678. }
  679. }
  680. return false
  681. }
  682. // HasPermissionsInside returns true if the specified virtualPath has no permissions itself and
  683. // no subdirs with defined permissions
  684. func (u *User) HasPermissionsInside(virtualPath string) bool {
  685. for dir := range u.Permissions {
  686. if dir == virtualPath {
  687. return true
  688. } else if len(dir) > len(virtualPath) {
  689. if strings.HasPrefix(dir, virtualPath+"/") {
  690. return true
  691. }
  692. }
  693. }
  694. return false
  695. }
  696. // HasPerm returns true if the user has the given permission or any permission
  697. func (u *User) HasPerm(permission, path string) bool {
  698. perms := u.GetPermissionsForPath(path)
  699. if util.IsStringInSlice(PermAny, perms) {
  700. return true
  701. }
  702. return util.IsStringInSlice(permission, perms)
  703. }
  704. // HasAnyPerm returns true if the user has at least one of the given permissions
  705. func (u *User) HasAnyPerm(permissions []string, path string) bool {
  706. perms := u.GetPermissionsForPath(path)
  707. if util.IsStringInSlice(PermAny, perms) {
  708. return true
  709. }
  710. for _, permission := range permissions {
  711. if util.IsStringInSlice(permission, perms) {
  712. return true
  713. }
  714. }
  715. return false
  716. }
  717. // HasPerms returns true if the user has all the given permissions
  718. func (u *User) HasPerms(permissions []string, path string) bool {
  719. perms := u.GetPermissionsForPath(path)
  720. if util.IsStringInSlice(PermAny, perms) {
  721. return true
  722. }
  723. for _, permission := range permissions {
  724. if !util.IsStringInSlice(permission, perms) {
  725. return false
  726. }
  727. }
  728. return true
  729. }
  730. // HasPermsDeleteAll returns true if the user can delete both files and directories
  731. // for the given path
  732. func (u *User) HasPermsDeleteAll(path string) bool {
  733. perms := u.GetPermissionsForPath(path)
  734. canDeleteFiles := false
  735. canDeleteDirs := false
  736. for _, permission := range perms {
  737. if permission == PermAny || permission == PermDelete {
  738. return true
  739. }
  740. if permission == PermDeleteFiles {
  741. canDeleteFiles = true
  742. }
  743. if permission == PermDeleteDirs {
  744. canDeleteDirs = true
  745. }
  746. }
  747. return canDeleteFiles && canDeleteDirs
  748. }
  749. // HasPermsRenameAll returns true if the user can rename both files and directories
  750. // for the given path
  751. func (u *User) HasPermsRenameAll(path string) bool {
  752. perms := u.GetPermissionsForPath(path)
  753. canRenameFiles := false
  754. canRenameDirs := false
  755. for _, permission := range perms {
  756. if permission == PermAny || permission == PermRename {
  757. return true
  758. }
  759. if permission == PermRenameFiles {
  760. canRenameFiles = true
  761. }
  762. if permission == PermRenameDirs {
  763. canRenameDirs = true
  764. }
  765. }
  766. return canRenameFiles && canRenameDirs
  767. }
  768. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  769. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  770. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  771. return true
  772. }
  773. return false
  774. }
  775. // IsLoginMethodAllowed returns true if the specified login method is allowed
  776. func (u *User) IsLoginMethodAllowed(loginMethod, protocol string, partialSuccessMethods []string) bool {
  777. if len(u.Filters.DeniedLoginMethods) == 0 {
  778. return true
  779. }
  780. if len(partialSuccessMethods) == 1 {
  781. for _, method := range u.GetNextAuthMethods(partialSuccessMethods, true) {
  782. if method == loginMethod {
  783. return true
  784. }
  785. }
  786. }
  787. if util.IsStringInSlice(loginMethod, u.Filters.DeniedLoginMethods) {
  788. return false
  789. }
  790. if protocol == protocolSSH && loginMethod == LoginMethodPassword {
  791. if util.IsStringInSlice(SSHLoginMethodPassword, u.Filters.DeniedLoginMethods) {
  792. return false
  793. }
  794. }
  795. return true
  796. }
  797. // GetNextAuthMethods returns the list of authentications methods that
  798. // can continue for multi-step authentication
  799. func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string {
  800. var methods []string
  801. if len(partialSuccessMethods) != 1 {
  802. return methods
  803. }
  804. if partialSuccessMethods[0] != SSHLoginMethodPublicKey {
  805. return methods
  806. }
  807. for _, method := range u.GetAllowedLoginMethods() {
  808. if method == SSHLoginMethodKeyAndPassword && isPasswordAuthEnabled {
  809. methods = append(methods, LoginMethodPassword)
  810. }
  811. if method == SSHLoginMethodKeyAndKeyboardInt {
  812. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  813. }
  814. }
  815. return methods
  816. }
  817. // IsPartialAuth returns true if the specified login method is a step for
  818. // a multi-step Authentication.
  819. // We support publickey+password and publickey+keyboard-interactive, so
  820. // only publickey can returns partial success.
  821. // We can have partial success if only multi-step Auth methods are enabled
  822. func (u *User) IsPartialAuth(loginMethod string) bool {
  823. if loginMethod != SSHLoginMethodPublicKey {
  824. return false
  825. }
  826. for _, method := range u.GetAllowedLoginMethods() {
  827. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd ||
  828. method == SSHLoginMethodPassword {
  829. continue
  830. }
  831. if !util.IsStringInSlice(method, SSHMultiStepsLoginMethods) {
  832. return false
  833. }
  834. }
  835. return true
  836. }
  837. // GetAllowedLoginMethods returns the allowed login methods
  838. func (u *User) GetAllowedLoginMethods() []string {
  839. var allowedMethods []string
  840. for _, method := range ValidLoginMethods {
  841. if method == SSHLoginMethodPassword {
  842. continue
  843. }
  844. if !util.IsStringInSlice(method, u.Filters.DeniedLoginMethods) {
  845. allowedMethods = append(allowedMethods, method)
  846. }
  847. }
  848. return allowedMethods
  849. }
  850. func (u *User) getPatternsFilterForPath(virtualPath string) sdk.PatternsFilter {
  851. var filter sdk.PatternsFilter
  852. if len(u.Filters.FilePatterns) == 0 {
  853. return filter
  854. }
  855. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  856. for _, dir := range dirsForPath {
  857. for _, f := range u.Filters.FilePatterns {
  858. if f.Path == dir {
  859. filter = f
  860. break
  861. }
  862. }
  863. if filter.Path != "" {
  864. break
  865. }
  866. }
  867. return filter
  868. }
  869. func (u *User) isDirHidden(virtualPath string) bool {
  870. if len(u.Filters.FilePatterns) == 0 {
  871. return false
  872. }
  873. for _, dirPath := range util.GetDirsForVirtualPath(virtualPath) {
  874. if dirPath == "/" {
  875. return false
  876. }
  877. filter := u.getPatternsFilterForPath(dirPath)
  878. if filter.DenyPolicy == sdk.DenyPolicyHide {
  879. if !filter.CheckAllowed(path.Base(dirPath)) {
  880. return true
  881. }
  882. }
  883. }
  884. return false
  885. }
  886. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters.
  887. // The second parameter returned is the deny policy
  888. func (u *User) IsFileAllowed(virtualPath string) (bool, int) {
  889. dirPath := path.Dir(virtualPath)
  890. if u.isDirHidden(dirPath) {
  891. return false, sdk.DenyPolicyHide
  892. }
  893. filter := u.getPatternsFilterForPath(dirPath)
  894. return filter.CheckAllowed(path.Base(virtualPath)), filter.DenyPolicy
  895. }
  896. // CanManageMFA returns true if the user can add a multi-factor authentication configuration
  897. func (u *User) CanManageMFA() bool {
  898. if util.IsStringInSlice(sdk.WebClientMFADisabled, u.Filters.WebClient) {
  899. return false
  900. }
  901. return len(mfa.GetAvailableTOTPConfigs()) > 0
  902. }
  903. func (u *User) isExternalAuthCached() bool {
  904. if u.ID <= 0 {
  905. return false
  906. }
  907. if u.Filters.ExternalAuthCacheTime <= 0 {
  908. return false
  909. }
  910. return isLastActivityRecent(u.LastLogin, time.Duration(u.Filters.ExternalAuthCacheTime)*time.Second)
  911. }
  912. // CanManageShares returns true if the user can add, update and list shares
  913. func (u *User) CanManageShares() bool {
  914. return !util.IsStringInSlice(sdk.WebClientSharesDisabled, u.Filters.WebClient)
  915. }
  916. // CanResetPassword returns true if this user is allowed to reset its password
  917. func (u *User) CanResetPassword() bool {
  918. return !util.IsStringInSlice(sdk.WebClientPasswordResetDisabled, u.Filters.WebClient)
  919. }
  920. // CanChangePassword returns true if this user is allowed to change its password
  921. func (u *User) CanChangePassword() bool {
  922. return !util.IsStringInSlice(sdk.WebClientPasswordChangeDisabled, u.Filters.WebClient)
  923. }
  924. // CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
  925. func (u *User) CanChangeAPIKeyAuth() bool {
  926. return !util.IsStringInSlice(sdk.WebClientAPIKeyAuthChangeDisabled, u.Filters.WebClient)
  927. }
  928. // CanChangeInfo returns true if this user is allowed to change its info such as email and description
  929. func (u *User) CanChangeInfo() bool {
  930. return !util.IsStringInSlice(sdk.WebClientInfoChangeDisabled, u.Filters.WebClient)
  931. }
  932. // CanManagePublicKeys returns true if this user is allowed to manage public keys
  933. // from the web client. Used in web client UI
  934. func (u *User) CanManagePublicKeys() bool {
  935. return !util.IsStringInSlice(sdk.WebClientPubKeyChangeDisabled, u.Filters.WebClient)
  936. }
  937. // CanAddFilesFromWeb returns true if the client can add files from the web UI.
  938. // The specified target is the directory where the files must be uploaded
  939. func (u *User) CanAddFilesFromWeb(target string) bool {
  940. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  941. return false
  942. }
  943. return u.HasPerm(PermUpload, target) || u.HasPerm(PermOverwrite, target)
  944. }
  945. // CanAddDirsFromWeb returns true if the client can add directories from the web UI.
  946. // The specified target is the directory where the new directory must be created
  947. func (u *User) CanAddDirsFromWeb(target string) bool {
  948. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  949. return false
  950. }
  951. return u.HasPerm(PermCreateDirs, target)
  952. }
  953. // CanRenameFromWeb returns true if the client can rename objects from the web UI.
  954. // The specified src and dest are the source and target directories for the rename.
  955. func (u *User) CanRenameFromWeb(src, dest string) bool {
  956. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  957. return false
  958. }
  959. return u.HasAnyPerm(permsRenameAny, src) && u.HasAnyPerm(permsRenameAny, dest)
  960. }
  961. // CanDeleteFromWeb returns true if the client can delete objects from the web UI.
  962. // The specified target is the parent directory for the object to delete
  963. func (u *User) CanDeleteFromWeb(target string) bool {
  964. if util.IsStringInSlice(sdk.WebClientWriteDisabled, u.Filters.WebClient) {
  965. return false
  966. }
  967. return u.HasAnyPerm(permsDeleteAny, target)
  968. }
  969. // MustSetSecondFactor returns true if the user must set a second factor authentication
  970. func (u *User) MustSetSecondFactor() bool {
  971. if len(u.Filters.TwoFactorAuthProtocols) > 0 {
  972. if !u.Filters.TOTPConfig.Enabled {
  973. return true
  974. }
  975. for _, p := range u.Filters.TwoFactorAuthProtocols {
  976. if !util.IsStringInSlice(p, u.Filters.TOTPConfig.Protocols) {
  977. return true
  978. }
  979. }
  980. }
  981. return false
  982. }
  983. // MustSetSecondFactorForProtocol returns true if the user must set a second factor authentication
  984. // for the specified protocol
  985. func (u *User) MustSetSecondFactorForProtocol(protocol string) bool {
  986. if util.IsStringInSlice(protocol, u.Filters.TwoFactorAuthProtocols) {
  987. if !u.Filters.TOTPConfig.Enabled {
  988. return true
  989. }
  990. if !util.IsStringInSlice(protocol, u.Filters.TOTPConfig.Protocols) {
  991. return true
  992. }
  993. }
  994. return false
  995. }
  996. // GetSignature returns a signature for this admin.
  997. // It could change after an update
  998. func (u *User) GetSignature() string {
  999. data := []byte(fmt.Sprintf("%v_%v_%v", u.Username, u.Status, u.ExpirationDate))
  1000. data = append(data, []byte(u.Password)...)
  1001. signature := sha256.Sum256(data)
  1002. return base64.StdEncoding.EncodeToString(signature[:])
  1003. }
  1004. // GetBandwidthForIP returns the upload and download bandwidth for the specified IP
  1005. func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64) {
  1006. if len(u.Filters.BandwidthLimits) > 0 {
  1007. ip := net.ParseIP(clientIP)
  1008. if ip != nil {
  1009. for _, bwLimit := range u.Filters.BandwidthLimits {
  1010. for _, source := range bwLimit.Sources {
  1011. _, ipNet, err := net.ParseCIDR(source)
  1012. if err == nil {
  1013. if ipNet.Contains(ip) {
  1014. logger.Debug(logSender, connectionID, "override bandwidth limit for ip %#v, upload limit: %v KB/s, download limit: %v KB/s",
  1015. clientIP, bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth)
  1016. return bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. return u.UploadBandwidth, u.DownloadBandwidth
  1024. }
  1025. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  1026. // If AllowedIP is defined only the specified IP/Mask can login.
  1027. // If DeniedIP is defined the specified IP/Mask cannot login.
  1028. // If an IP is both allowed and denied then login will be denied
  1029. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  1030. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  1031. return true
  1032. }
  1033. remoteIP := net.ParseIP(util.GetIPFromRemoteAddress(remoteAddr))
  1034. // if remoteIP is invalid we allow login, this should never happen
  1035. if remoteIP == nil {
  1036. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %#v", remoteAddr)
  1037. return true
  1038. }
  1039. for _, IPMask := range u.Filters.DeniedIP {
  1040. _, IPNet, err := net.ParseCIDR(IPMask)
  1041. if err != nil {
  1042. return false
  1043. }
  1044. if IPNet.Contains(remoteIP) {
  1045. return false
  1046. }
  1047. }
  1048. for _, IPMask := range u.Filters.AllowedIP {
  1049. _, IPNet, err := net.ParseCIDR(IPMask)
  1050. if err != nil {
  1051. return false
  1052. }
  1053. if IPNet.Contains(remoteIP) {
  1054. return true
  1055. }
  1056. }
  1057. return len(u.Filters.AllowedIP) == 0
  1058. }
  1059. // GetPermissionsAsJSON returns the permissions as json byte array
  1060. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  1061. return json.Marshal(u.Permissions)
  1062. }
  1063. // GetPublicKeysAsJSON returns the public keys as json byte array
  1064. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  1065. return json.Marshal(u.PublicKeys)
  1066. }
  1067. // GetFiltersAsJSON returns the filters as json byte array
  1068. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  1069. return json.Marshal(u.Filters)
  1070. }
  1071. // GetFsConfigAsJSON returns the filesystem config as json byte array
  1072. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  1073. return json.Marshal(u.FsConfig)
  1074. }
  1075. // GetUID returns a validate uid, suitable for use with os.Chown
  1076. func (u *User) GetUID() int {
  1077. if u.UID <= 0 || u.UID > math.MaxInt32 {
  1078. return -1
  1079. }
  1080. return u.UID
  1081. }
  1082. // GetGID returns a validate gid, suitable for use with os.Chown
  1083. func (u *User) GetGID() int {
  1084. if u.GID <= 0 || u.GID > math.MaxInt32 {
  1085. return -1
  1086. }
  1087. return u.GID
  1088. }
  1089. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  1090. func (u *User) GetHomeDir() string {
  1091. return u.HomeDir
  1092. }
  1093. // HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
  1094. func (u *User) HasRecentActivity() bool {
  1095. return isLastActivityRecent(u.LastLogin, lastLoginMinDelay)
  1096. }
  1097. // HasQuotaRestrictions returns true if there are any disk quota restrictions
  1098. func (u *User) HasQuotaRestrictions() bool {
  1099. return u.QuotaFiles > 0 || u.QuotaSize > 0
  1100. }
  1101. // HasTransferQuotaRestrictions returns true if there are any data transfer restrictions
  1102. func (u *User) HasTransferQuotaRestrictions() bool {
  1103. if len(u.Filters.DataTransferLimits) > 0 {
  1104. return true
  1105. }
  1106. return u.UploadDataTransfer > 0 || u.TotalDataTransfer > 0 || u.DownloadDataTransfer > 0
  1107. }
  1108. // GetDataTransferLimits returns upload, download and total data transfer limits
  1109. func (u *User) GetDataTransferLimits(clientIP string) (int64, int64, int64) {
  1110. var total, ul, dl int64
  1111. if len(u.Filters.DataTransferLimits) > 0 {
  1112. ip := net.ParseIP(clientIP)
  1113. if ip != nil {
  1114. for _, limit := range u.Filters.DataTransferLimits {
  1115. for _, source := range limit.Sources {
  1116. _, ipNet, err := net.ParseCIDR(source)
  1117. if err == nil {
  1118. if ipNet.Contains(ip) {
  1119. if limit.TotalDataTransfer > 0 {
  1120. total = limit.TotalDataTransfer * 1048576
  1121. }
  1122. if limit.DownloadDataTransfer > 0 {
  1123. dl = limit.DownloadDataTransfer * 1048576
  1124. }
  1125. if limit.UploadDataTransfer > 0 {
  1126. ul = limit.UploadDataTransfer * 1048576
  1127. }
  1128. return ul, dl, total
  1129. }
  1130. }
  1131. }
  1132. }
  1133. }
  1134. }
  1135. if u.TotalDataTransfer > 0 {
  1136. total = u.TotalDataTransfer * 1048576
  1137. }
  1138. if u.DownloadDataTransfer > 0 {
  1139. dl = u.DownloadDataTransfer * 1048576
  1140. }
  1141. if u.UploadDataTransfer > 0 {
  1142. ul = u.UploadDataTransfer * 1048576
  1143. }
  1144. return ul, dl, total
  1145. }
  1146. // GetQuotaSummary returns used quota and limits if defined
  1147. func (u *User) GetQuotaSummary() string {
  1148. var sb strings.Builder
  1149. addSection := func() {
  1150. if sb.Len() > 0 {
  1151. sb.WriteString(". ")
  1152. }
  1153. }
  1154. if u.UsedQuotaFiles > 0 || u.QuotaFiles > 0 {
  1155. sb.WriteString(fmt.Sprintf("Files: %v", u.UsedQuotaFiles))
  1156. if u.QuotaFiles > 0 {
  1157. sb.WriteString(fmt.Sprintf("/%v", u.QuotaFiles))
  1158. }
  1159. }
  1160. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  1161. addSection()
  1162. sb.WriteString(fmt.Sprintf("Size: %v", util.ByteCountIEC(u.UsedQuotaSize)))
  1163. if u.QuotaSize > 0 {
  1164. sb.WriteString(fmt.Sprintf("/%v", util.ByteCountIEC(u.QuotaSize)))
  1165. }
  1166. }
  1167. if u.TotalDataTransfer > 0 {
  1168. addSection()
  1169. total := u.UsedDownloadDataTransfer + u.UsedUploadDataTransfer
  1170. sb.WriteString(fmt.Sprintf("Transfer: %v/%v", util.ByteCountIEC(total),
  1171. util.ByteCountIEC(u.TotalDataTransfer*1048576)))
  1172. }
  1173. if u.UploadDataTransfer > 0 {
  1174. addSection()
  1175. sb.WriteString(fmt.Sprintf("UL: %v/%v", util.ByteCountIEC(u.UsedUploadDataTransfer),
  1176. util.ByteCountIEC(u.UploadDataTransfer*1048576)))
  1177. }
  1178. if u.DownloadDataTransfer > 0 {
  1179. addSection()
  1180. sb.WriteString(fmt.Sprintf("DL: %v/%v", util.ByteCountIEC(u.UsedDownloadDataTransfer),
  1181. util.ByteCountIEC(u.DownloadDataTransfer*1048576)))
  1182. }
  1183. if u.LastQuotaUpdate > 0 {
  1184. addSection()
  1185. t := util.GetTimeFromMsecSinceEpoch(u.LastQuotaUpdate)
  1186. sb.WriteString(fmt.Sprintf("Last update: %v", t.Format("2006-01-02 15:04"))) // YYYY-MM-DD HH:MM
  1187. }
  1188. return sb.String()
  1189. }
  1190. // GetPermissionsAsString returns the user's permissions as comma separated string
  1191. func (u *User) GetPermissionsAsString() string {
  1192. result := ""
  1193. for dir, perms := range u.Permissions {
  1194. dirPerms := strings.Join(perms, ", ")
  1195. dp := fmt.Sprintf("%#v: %#v", dir, dirPerms)
  1196. if dir == "/" {
  1197. if result != "" {
  1198. result = dp + ", " + result
  1199. } else {
  1200. result = dp
  1201. }
  1202. } else {
  1203. if result != "" {
  1204. result += ", "
  1205. }
  1206. result += dp
  1207. }
  1208. }
  1209. return result
  1210. }
  1211. // GetBandwidthAsString returns bandwidth limits if defines
  1212. func (u *User) GetBandwidthAsString() string {
  1213. result := "DL: "
  1214. if u.DownloadBandwidth > 0 {
  1215. result += util.ByteCountIEC(u.DownloadBandwidth*1000) + "/s."
  1216. } else {
  1217. result += "unlimited."
  1218. }
  1219. result += " UL: "
  1220. if u.UploadBandwidth > 0 {
  1221. result += util.ByteCountIEC(u.UploadBandwidth*1000) + "/s."
  1222. } else {
  1223. result += "unlimited."
  1224. }
  1225. return result
  1226. }
  1227. // GetInfoString returns user's info as string.
  1228. // Storage provider, number of public keys, max sessions, uid,
  1229. // gid, denied and allowed IP/Mask are returned
  1230. func (u *User) GetInfoString() string {
  1231. var result strings.Builder
  1232. if u.LastLogin > 0 {
  1233. t := util.GetTimeFromMsecSinceEpoch(u.LastLogin)
  1234. result.WriteString(fmt.Sprintf("Last login: %v. ", t.Format("2006-01-02 15:04"))) // YYYY-MM-DD HH:MM
  1235. }
  1236. if u.FsConfig.Provider != sdk.LocalFilesystemProvider {
  1237. result.WriteString(fmt.Sprintf("Storage: %s. ", u.FsConfig.Provider.ShortInfo()))
  1238. }
  1239. if len(u.PublicKeys) > 0 {
  1240. result.WriteString(fmt.Sprintf("Public keys: %v. ", len(u.PublicKeys)))
  1241. }
  1242. if u.MaxSessions > 0 {
  1243. result.WriteString(fmt.Sprintf("Max sessions: %v. ", u.MaxSessions))
  1244. }
  1245. if u.UID > 0 {
  1246. result.WriteString(fmt.Sprintf("UID: %v. ", u.UID))
  1247. }
  1248. if u.GID > 0 {
  1249. result.WriteString(fmt.Sprintf("GID: %v. ", u.GID))
  1250. }
  1251. if len(u.Filters.DeniedIP) > 0 {
  1252. result.WriteString(fmt.Sprintf("Denied IP/Mask: %v. ", len(u.Filters.DeniedIP)))
  1253. }
  1254. if len(u.Filters.AllowedIP) > 0 {
  1255. result.WriteString(fmt.Sprintf("Allowed IP/Mask: %v", len(u.Filters.AllowedIP)))
  1256. }
  1257. return result.String()
  1258. }
  1259. // GetStatusAsString returns the user status as a string
  1260. func (u *User) GetStatusAsString() string {
  1261. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  1262. return "Expired"
  1263. }
  1264. if u.Status == 1 {
  1265. return "Active"
  1266. }
  1267. return "Inactive"
  1268. }
  1269. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  1270. func (u *User) GetExpirationDateAsString() string {
  1271. if u.ExpirationDate > 0 {
  1272. t := util.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  1273. return t.Format("2006-01-02")
  1274. }
  1275. return ""
  1276. }
  1277. // GetAllowedIPAsString returns the allowed IP as comma separated string
  1278. func (u *User) GetAllowedIPAsString() string {
  1279. return strings.Join(u.Filters.AllowedIP, ",")
  1280. }
  1281. // GetDeniedIPAsString returns the denied IP as comma separated string
  1282. func (u *User) GetDeniedIPAsString() string {
  1283. return strings.Join(u.Filters.DeniedIP, ",")
  1284. }
  1285. // HasExternalAuth returns true if the external authentication is globally enabled
  1286. // and it is not disabled for this user
  1287. func (u *User) HasExternalAuth() bool {
  1288. if u.Filters.Hooks.ExternalAuthDisabled {
  1289. return false
  1290. }
  1291. if config.ExternalAuthHook != "" {
  1292. return true
  1293. }
  1294. return plugin.Handler.HasAuthenticators()
  1295. }
  1296. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  1297. func (u *User) CountUnusedRecoveryCodes() int {
  1298. unused := 0
  1299. for _, code := range u.Filters.RecoveryCodes {
  1300. if !code.Used {
  1301. unused++
  1302. }
  1303. }
  1304. return unused
  1305. }
  1306. // SetEmptySecretsIfNil sets the secrets to empty if nil
  1307. func (u *User) SetEmptySecretsIfNil() {
  1308. u.FsConfig.SetEmptySecretsIfNil()
  1309. for idx := range u.VirtualFolders {
  1310. vfolder := &u.VirtualFolders[idx]
  1311. vfolder.FsConfig.SetEmptySecretsIfNil()
  1312. }
  1313. if u.Filters.TOTPConfig.Secret == nil {
  1314. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  1315. }
  1316. }
  1317. func (u *User) hasMainDataTransferLimits() bool {
  1318. return u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 || u.TotalDataTransfer > 0
  1319. }
  1320. // HasPrimaryGroup returns true if the user has the specified primary group
  1321. func (u *User) HasPrimaryGroup(name string) bool {
  1322. for _, g := range u.Groups {
  1323. if g.Name == name {
  1324. return g.Type == sdk.GroupTypePrimary
  1325. }
  1326. }
  1327. return false
  1328. }
  1329. // HasSecondaryGroup returns true if the user has the specified secondary group
  1330. func (u *User) HasSecondaryGroup(name string) bool {
  1331. for _, g := range u.Groups {
  1332. if g.Name == name {
  1333. return g.Type == sdk.GroupTypeSecondary
  1334. }
  1335. }
  1336. return false
  1337. }
  1338. func (u *User) applyGroupSettings(groupsMapping map[string]Group) {
  1339. if len(u.Groups) == 0 {
  1340. return
  1341. }
  1342. if u.groupSettingsApplied {
  1343. return
  1344. }
  1345. for _, g := range u.Groups {
  1346. if g.Type == sdk.GroupTypePrimary {
  1347. if group, ok := groupsMapping[g.Name]; ok {
  1348. u.mergeWithPrimaryGroup(group)
  1349. } else {
  1350. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1351. }
  1352. break
  1353. }
  1354. }
  1355. for _, g := range u.Groups {
  1356. if g.Type == sdk.GroupTypeSecondary {
  1357. if group, ok := groupsMapping[g.Name]; ok {
  1358. u.mergeAdditiveProperties(group, sdk.GroupTypeSecondary)
  1359. } else {
  1360. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1361. }
  1362. }
  1363. }
  1364. u.removeDuplicatesAfterGroupMerge()
  1365. }
  1366. // LoadAndApplyGroupSettings update the user by loading and applying the group settings
  1367. func (u *User) LoadAndApplyGroupSettings() error {
  1368. if len(u.Groups) == 0 {
  1369. return nil
  1370. }
  1371. if u.groupSettingsApplied {
  1372. return nil
  1373. }
  1374. names := make([]string, 0, len(u.Groups))
  1375. var primaryGroupName string
  1376. for _, g := range u.Groups {
  1377. if g.Type == sdk.GroupTypePrimary {
  1378. primaryGroupName = g.Name
  1379. }
  1380. names = append(names, g.Name)
  1381. }
  1382. groups, err := provider.getGroupsWithNames(names)
  1383. if err != nil {
  1384. return fmt.Errorf("unable to get groups: %w", err)
  1385. }
  1386. // make sure to always merge with the primary group first
  1387. for idx, g := range groups {
  1388. if g.Name == primaryGroupName {
  1389. u.mergeWithPrimaryGroup(g)
  1390. lastIdx := len(groups) - 1
  1391. groups[idx] = groups[lastIdx]
  1392. groups = groups[:lastIdx]
  1393. break
  1394. }
  1395. }
  1396. for _, g := range groups {
  1397. u.mergeAdditiveProperties(g, sdk.GroupTypeSecondary)
  1398. }
  1399. u.removeDuplicatesAfterGroupMerge()
  1400. return nil
  1401. }
  1402. func (u *User) replacePlaceholder(value string) string {
  1403. if value == "" {
  1404. return value
  1405. }
  1406. return strings.ReplaceAll(value, "%username%", u.Username)
  1407. }
  1408. func (u *User) replaceFsConfigPlaceholders() {
  1409. switch u.FsConfig.Provider {
  1410. case sdk.S3FilesystemProvider:
  1411. u.FsConfig.S3Config.KeyPrefix = u.replacePlaceholder(u.FsConfig.S3Config.KeyPrefix)
  1412. case sdk.GCSFilesystemProvider:
  1413. u.FsConfig.GCSConfig.KeyPrefix = u.replacePlaceholder(u.FsConfig.GCSConfig.KeyPrefix)
  1414. case sdk.AzureBlobFilesystemProvider:
  1415. u.FsConfig.AzBlobConfig.KeyPrefix = u.replacePlaceholder(u.FsConfig.AzBlobConfig.KeyPrefix)
  1416. case sdk.SFTPFilesystemProvider:
  1417. u.FsConfig.SFTPConfig.Username = u.replacePlaceholder(u.FsConfig.SFTPConfig.Username)
  1418. u.FsConfig.SFTPConfig.Prefix = u.replacePlaceholder(u.FsConfig.SFTPConfig.Prefix)
  1419. }
  1420. }
  1421. func (u *User) mergeWithPrimaryGroup(group Group) {
  1422. if group.UserSettings.HomeDir != "" {
  1423. u.HomeDir = u.replacePlaceholder(group.UserSettings.HomeDir)
  1424. }
  1425. if group.UserSettings.FsConfig.Provider != 0 {
  1426. u.FsConfig = group.UserSettings.FsConfig
  1427. u.replaceFsConfigPlaceholders()
  1428. }
  1429. if u.MaxSessions == 0 {
  1430. u.MaxSessions = group.UserSettings.MaxSessions
  1431. }
  1432. if u.QuotaSize == 0 {
  1433. u.QuotaSize = group.UserSettings.QuotaSize
  1434. }
  1435. if u.QuotaFiles == 0 {
  1436. u.QuotaFiles = group.UserSettings.QuotaFiles
  1437. }
  1438. if u.UploadBandwidth == 0 {
  1439. u.UploadBandwidth = group.UserSettings.UploadBandwidth
  1440. }
  1441. if u.DownloadBandwidth == 0 {
  1442. u.DownloadBandwidth = group.UserSettings.DownloadBandwidth
  1443. }
  1444. if !u.hasMainDataTransferLimits() {
  1445. u.UploadDataTransfer = group.UserSettings.UploadDataTransfer
  1446. u.DownloadDataTransfer = group.UserSettings.DownloadDataTransfer
  1447. u.TotalDataTransfer = group.UserSettings.TotalDataTransfer
  1448. }
  1449. u.mergePrimaryGroupFilters(group.UserSettings.Filters)
  1450. u.mergeAdditiveProperties(group, sdk.GroupTypePrimary)
  1451. }
  1452. func (u *User) mergePrimaryGroupFilters(filters sdk.BaseUserFilters) {
  1453. if u.Filters.MaxUploadFileSize == 0 {
  1454. u.Filters.MaxUploadFileSize = filters.MaxUploadFileSize
  1455. }
  1456. if u.Filters.TLSUsername == "" || u.Filters.TLSUsername == sdk.TLSUsernameNone {
  1457. u.Filters.TLSUsername = filters.TLSUsername
  1458. }
  1459. if !u.Filters.Hooks.CheckPasswordDisabled {
  1460. u.Filters.Hooks.CheckPasswordDisabled = filters.Hooks.CheckPasswordDisabled
  1461. }
  1462. if !u.Filters.Hooks.PreLoginDisabled {
  1463. u.Filters.Hooks.PreLoginDisabled = filters.Hooks.PreLoginDisabled
  1464. }
  1465. if !u.Filters.Hooks.ExternalAuthDisabled {
  1466. u.Filters.Hooks.ExternalAuthDisabled = filters.Hooks.ExternalAuthDisabled
  1467. }
  1468. if !u.Filters.DisableFsChecks {
  1469. u.Filters.DisableFsChecks = filters.DisableFsChecks
  1470. }
  1471. if !u.Filters.AllowAPIKeyAuth {
  1472. u.Filters.AllowAPIKeyAuth = filters.AllowAPIKeyAuth
  1473. }
  1474. if u.Filters.ExternalAuthCacheTime == 0 {
  1475. u.Filters.ExternalAuthCacheTime = filters.ExternalAuthCacheTime
  1476. }
  1477. if u.Filters.StartDirectory == "" {
  1478. u.Filters.StartDirectory = u.replacePlaceholder(filters.StartDirectory)
  1479. }
  1480. }
  1481. func (u *User) mergeAdditiveProperties(group Group, groupType int) {
  1482. u.mergeVirtualFolders(group, groupType)
  1483. u.mergePermissions(group, groupType)
  1484. u.mergeFilePatterns(group, groupType)
  1485. u.Filters.BandwidthLimits = append(u.Filters.BandwidthLimits, group.UserSettings.Filters.BandwidthLimits...)
  1486. u.Filters.DataTransferLimits = append(u.Filters.DataTransferLimits, group.UserSettings.Filters.DataTransferLimits...)
  1487. u.Filters.AllowedIP = append(u.Filters.AllowedIP, group.UserSettings.Filters.AllowedIP...)
  1488. u.Filters.DeniedIP = append(u.Filters.DeniedIP, group.UserSettings.Filters.DeniedIP...)
  1489. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, group.UserSettings.Filters.DeniedLoginMethods...)
  1490. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, group.UserSettings.Filters.DeniedProtocols...)
  1491. u.Filters.WebClient = append(u.Filters.WebClient, group.UserSettings.Filters.WebClient...)
  1492. u.Filters.TwoFactorAuthProtocols = append(u.Filters.TwoFactorAuthProtocols, group.UserSettings.Filters.TwoFactorAuthProtocols...)
  1493. }
  1494. func (u *User) mergeVirtualFolders(group Group, groupType int) {
  1495. if len(group.VirtualFolders) > 0 {
  1496. folderPaths := make(map[string]bool)
  1497. for _, folder := range u.VirtualFolders {
  1498. folderPaths[folder.VirtualPath] = true
  1499. }
  1500. for _, folder := range group.VirtualFolders {
  1501. if folder.VirtualPath == "/" && groupType != sdk.GroupTypePrimary {
  1502. continue
  1503. }
  1504. folder.VirtualPath = u.replacePlaceholder(folder.VirtualPath)
  1505. if _, ok := folderPaths[folder.VirtualPath]; !ok {
  1506. folder.MappedPath = u.replacePlaceholder(folder.MappedPath)
  1507. u.VirtualFolders = append(u.VirtualFolders, folder)
  1508. }
  1509. }
  1510. }
  1511. }
  1512. func (u *User) mergePermissions(group Group, groupType int) {
  1513. for k, v := range group.UserSettings.Permissions {
  1514. if k == "/" {
  1515. if groupType == sdk.GroupTypePrimary {
  1516. u.Permissions[k] = v
  1517. } else {
  1518. continue
  1519. }
  1520. }
  1521. k = u.replacePlaceholder(k)
  1522. if _, ok := u.Permissions[k]; !ok {
  1523. u.Permissions[k] = v
  1524. }
  1525. }
  1526. }
  1527. func (u *User) mergeFilePatterns(group Group, groupType int) {
  1528. if len(group.UserSettings.Filters.FilePatterns) > 0 {
  1529. patternPaths := make(map[string]bool)
  1530. for _, pattern := range u.Filters.FilePatterns {
  1531. patternPaths[pattern.Path] = true
  1532. }
  1533. for _, pattern := range group.UserSettings.Filters.FilePatterns {
  1534. if pattern.Path == "/" && groupType != sdk.GroupTypePrimary {
  1535. continue
  1536. }
  1537. pattern.Path = u.replacePlaceholder(pattern.Path)
  1538. if _, ok := patternPaths[pattern.Path]; !ok {
  1539. u.Filters.FilePatterns = append(u.Filters.FilePatterns, pattern)
  1540. }
  1541. }
  1542. }
  1543. }
  1544. func (u *User) removeDuplicatesAfterGroupMerge() {
  1545. u.Filters.AllowedIP = util.RemoveDuplicates(u.Filters.AllowedIP)
  1546. u.Filters.DeniedIP = util.RemoveDuplicates(u.Filters.DeniedIP)
  1547. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods)
  1548. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols)
  1549. u.Filters.WebClient = util.RemoveDuplicates(u.Filters.WebClient)
  1550. u.Filters.TwoFactorAuthProtocols = util.RemoveDuplicates(u.Filters.TwoFactorAuthProtocols)
  1551. u.SetEmptySecretsIfNil()
  1552. u.groupSettingsApplied = true
  1553. }
  1554. func (u *User) getACopy() User {
  1555. u.SetEmptySecretsIfNil()
  1556. pubKeys := make([]string, len(u.PublicKeys))
  1557. copy(pubKeys, u.PublicKeys)
  1558. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  1559. for idx := range u.VirtualFolders {
  1560. vfolder := u.VirtualFolders[idx].GetACopy()
  1561. virtualFolders = append(virtualFolders, vfolder)
  1562. }
  1563. groups := make([]sdk.GroupMapping, 0, len(u.Groups))
  1564. for _, g := range u.Groups {
  1565. groups = append(groups, sdk.GroupMapping{
  1566. Name: g.Name,
  1567. Type: g.Type,
  1568. })
  1569. }
  1570. permissions := make(map[string][]string)
  1571. for k, v := range u.Permissions {
  1572. perms := make([]string, len(v))
  1573. copy(perms, v)
  1574. permissions[k] = perms
  1575. }
  1576. filters := UserFilters{
  1577. BaseUserFilters: copyBaseUserFilters(u.Filters.BaseUserFilters),
  1578. }
  1579. filters.TOTPConfig.Enabled = u.Filters.TOTPConfig.Enabled
  1580. filters.TOTPConfig.ConfigName = u.Filters.TOTPConfig.ConfigName
  1581. filters.TOTPConfig.Secret = u.Filters.TOTPConfig.Secret.Clone()
  1582. filters.TOTPConfig.Protocols = make([]string, len(u.Filters.TOTPConfig.Protocols))
  1583. copy(filters.TOTPConfig.Protocols, u.Filters.TOTPConfig.Protocols)
  1584. filters.RecoveryCodes = make([]RecoveryCode, 0, len(u.Filters.RecoveryCodes))
  1585. for _, code := range u.Filters.RecoveryCodes {
  1586. if code.Secret == nil {
  1587. code.Secret = kms.NewEmptySecret()
  1588. }
  1589. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  1590. Secret: code.Secret.Clone(),
  1591. Used: code.Used,
  1592. })
  1593. }
  1594. return User{
  1595. BaseUser: sdk.BaseUser{
  1596. ID: u.ID,
  1597. Username: u.Username,
  1598. Email: u.Email,
  1599. Password: u.Password,
  1600. PublicKeys: pubKeys,
  1601. HomeDir: u.HomeDir,
  1602. UID: u.UID,
  1603. GID: u.GID,
  1604. MaxSessions: u.MaxSessions,
  1605. QuotaSize: u.QuotaSize,
  1606. QuotaFiles: u.QuotaFiles,
  1607. Permissions: permissions,
  1608. UsedQuotaSize: u.UsedQuotaSize,
  1609. UsedQuotaFiles: u.UsedQuotaFiles,
  1610. LastQuotaUpdate: u.LastQuotaUpdate,
  1611. UploadBandwidth: u.UploadBandwidth,
  1612. DownloadBandwidth: u.DownloadBandwidth,
  1613. UploadDataTransfer: u.UploadDataTransfer,
  1614. DownloadDataTransfer: u.DownloadDataTransfer,
  1615. TotalDataTransfer: u.TotalDataTransfer,
  1616. UsedUploadDataTransfer: u.UsedUploadDataTransfer,
  1617. UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
  1618. Status: u.Status,
  1619. ExpirationDate: u.ExpirationDate,
  1620. LastLogin: u.LastLogin,
  1621. AdditionalInfo: u.AdditionalInfo,
  1622. Description: u.Description,
  1623. CreatedAt: u.CreatedAt,
  1624. UpdatedAt: u.UpdatedAt,
  1625. },
  1626. Filters: filters,
  1627. VirtualFolders: virtualFolders,
  1628. Groups: groups,
  1629. FsConfig: u.FsConfig.GetACopy(),
  1630. groupSettingsApplied: u.groupSettingsApplied,
  1631. }
  1632. }
  1633. // GetEncryptionAdditionalData returns the additional data to use for AEAD
  1634. func (u *User) GetEncryptionAdditionalData() string {
  1635. return u.Username
  1636. }
  1637. // GetGCSCredentialsFilePath returns the path for GCS credentials
  1638. func (u *User) GetGCSCredentialsFilePath() string {
  1639. return filepath.Join(credentialsDirPath, fmt.Sprintf("%v_gcs_credentials.json", u.Username))
  1640. }