user.go 57 KB

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