user.go 61 KB

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