user.go 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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. func (u *User) setAnonymousSettings() {
  352. for k := range u.Permissions {
  353. u.Permissions[k] = []string{PermListItems, PermDownload}
  354. }
  355. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, protocolSSH, protocolHTTP)
  356. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  357. for _, method := range ValidLoginMethods {
  358. if method != LoginMethodPassword {
  359. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, method)
  360. }
  361. }
  362. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  363. }
  364. // RenderAsJSON implements the renderer interface used within plugins
  365. func (u *User) RenderAsJSON(reload bool) ([]byte, error) {
  366. if reload {
  367. user, err := provider.userExists(u.Username)
  368. if err != nil {
  369. providerLog(logger.LevelError, "unable to reload user before rendering as json: %v", err)
  370. return nil, err
  371. }
  372. user.PrepareForRendering()
  373. return json.Marshal(user)
  374. }
  375. u.PrepareForRendering()
  376. return json.Marshal(u)
  377. }
  378. // PrepareForRendering prepares a user for rendering.
  379. // It hides confidential data and set to nil the empty secrets
  380. // so they are not serialized
  381. func (u *User) PrepareForRendering() {
  382. u.hideConfidentialData()
  383. u.FsConfig.SetNilSecretsIfEmpty()
  384. for idx := range u.VirtualFolders {
  385. folder := &u.VirtualFolders[idx]
  386. folder.PrepareForRendering()
  387. }
  388. }
  389. // HasRedactedSecret returns true if the user has a redacted secret
  390. func (u *User) hasRedactedSecret() bool {
  391. if u.FsConfig.HasRedactedSecret() {
  392. return true
  393. }
  394. for idx := range u.VirtualFolders {
  395. folder := &u.VirtualFolders[idx]
  396. if folder.HasRedactedSecret() {
  397. return true
  398. }
  399. }
  400. return u.Filters.TOTPConfig.Secret.IsRedacted()
  401. }
  402. // CloseFs closes the underlying filesystems
  403. func (u *User) CloseFs() error {
  404. if u.fsCache == nil {
  405. return nil
  406. }
  407. var err error
  408. for _, fs := range u.fsCache {
  409. errClose := fs.Close()
  410. if err == nil {
  411. err = errClose
  412. }
  413. }
  414. return err
  415. }
  416. // IsPasswordHashed returns true if the password is hashed
  417. func (u *User) IsPasswordHashed() bool {
  418. return util.IsStringPrefixInSlice(u.Password, hashPwdPrefixes)
  419. }
  420. // IsTLSUsernameVerificationEnabled returns true if we need to extract the username
  421. // from the client TLS certificate
  422. func (u *User) IsTLSUsernameVerificationEnabled() bool {
  423. if u.Filters.TLSUsername != "" {
  424. return u.Filters.TLSUsername != sdk.TLSUsernameNone
  425. }
  426. return false
  427. }
  428. // SetEmptySecrets sets to empty any user secret
  429. func (u *User) SetEmptySecrets() {
  430. u.FsConfig.SetEmptySecrets()
  431. for idx := range u.VirtualFolders {
  432. folder := &u.VirtualFolders[idx]
  433. folder.FsConfig.SetEmptySecrets()
  434. }
  435. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  436. }
  437. // GetPermissionsForPath returns the permissions for the given path.
  438. // The path must be a SFTPGo exposed path
  439. func (u *User) GetPermissionsForPath(p string) []string {
  440. permissions := []string{}
  441. if perms, ok := u.Permissions["/"]; ok {
  442. // if only root permissions are defined returns them unconditionally
  443. if len(u.Permissions) == 1 {
  444. return perms
  445. }
  446. // fallback permissions
  447. permissions = perms
  448. }
  449. dirsForPath := util.GetDirsForVirtualPath(p)
  450. // dirsForPath contains all the dirs for a given path in reverse order
  451. // for example if the path is: /1/2/3/4 it contains:
  452. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  453. // so the first match is the one we are interested to
  454. for idx := range dirsForPath {
  455. if perms, ok := u.Permissions[dirsForPath[idx]]; ok {
  456. permissions = perms
  457. break
  458. }
  459. }
  460. return permissions
  461. }
  462. func (u *User) getForbiddenSFTPSelfUsers(username string) ([]string, error) {
  463. if allowSelfConnections == 0 {
  464. return nil, nil
  465. }
  466. sftpUser, err := UserExists(username)
  467. if err == nil {
  468. err = sftpUser.LoadAndApplyGroupSettings()
  469. }
  470. if err == nil {
  471. // we don't allow local nested SFTP folders
  472. var forbiddens []string
  473. if sftpUser.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  474. forbiddens = append(forbiddens, sftpUser.Username)
  475. return forbiddens, nil
  476. }
  477. for idx := range sftpUser.VirtualFolders {
  478. v := &sftpUser.VirtualFolders[idx]
  479. if v.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  480. forbiddens = append(forbiddens, sftpUser.Username)
  481. return forbiddens, nil
  482. }
  483. }
  484. return forbiddens, nil
  485. }
  486. if _, ok := err.(*util.RecordNotFoundError); !ok {
  487. return nil, err
  488. }
  489. return nil, nil
  490. }
  491. // GetFsConfigForPath returns the file system configuration for the specified virtual path
  492. func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem {
  493. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  494. folder, err := u.GetVirtualFolderForPath(virtualPath)
  495. if err == nil {
  496. return folder.FsConfig
  497. }
  498. }
  499. return u.FsConfig
  500. }
  501. // GetFilesystemForPath returns the filesystem for the given path
  502. func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error) {
  503. if u.fsCache == nil {
  504. u.fsCache = make(map[string]vfs.Fs)
  505. }
  506. // allow to override the `/` path with a virtual folder
  507. if len(u.VirtualFolders) > 0 {
  508. folder, err := u.GetVirtualFolderForPath(virtualPath)
  509. if err == nil {
  510. if fs, ok := u.fsCache[folder.VirtualPath]; ok {
  511. return fs, nil
  512. }
  513. forbiddenSelfUsers := []string{u.Username}
  514. if folder.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  515. forbiddens, err := u.getForbiddenSFTPSelfUsers(folder.FsConfig.SFTPConfig.Username)
  516. if err != nil {
  517. return nil, err
  518. }
  519. forbiddenSelfUsers = append(forbiddenSelfUsers, forbiddens...)
  520. }
  521. fs, err := folder.GetFilesystem(connectionID, forbiddenSelfUsers)
  522. if err == nil {
  523. u.fsCache[folder.VirtualPath] = fs
  524. }
  525. return fs, err
  526. }
  527. }
  528. if val, ok := u.fsCache["/"]; ok {
  529. return val, nil
  530. }
  531. fs, err := u.getRootFs(connectionID)
  532. if err != nil {
  533. return fs, err
  534. }
  535. u.fsCache["/"] = fs
  536. return fs, err
  537. }
  538. // GetVirtualFolderForPath returns the virtual folder containing the specified virtual path.
  539. // If the path is not inside a virtual folder an error is returned
  540. func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error) {
  541. var folder vfs.VirtualFolder
  542. if len(u.VirtualFolders) == 0 {
  543. return folder, errNoMatchingVirtualFolder
  544. }
  545. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  546. for index := range dirsForPath {
  547. for idx := range u.VirtualFolders {
  548. v := &u.VirtualFolders[idx]
  549. if v.VirtualPath == dirsForPath[index] {
  550. return *v, nil
  551. }
  552. }
  553. }
  554. return folder, errNoMatchingVirtualFolder
  555. }
  556. // CheckMetadataConsistency checks the consistency between the metadata stored
  557. // in the configured metadata plugin and the filesystem
  558. func (u *User) CheckMetadataConsistency() error {
  559. fs, err := u.getRootFs("")
  560. if err != nil {
  561. return err
  562. }
  563. defer fs.Close()
  564. if err = fs.CheckMetadata(); err != nil {
  565. return err
  566. }
  567. for idx := range u.VirtualFolders {
  568. v := &u.VirtualFolders[idx]
  569. if err = v.CheckMetadataConsistency(); err != nil {
  570. return err
  571. }
  572. }
  573. return nil
  574. }
  575. // ScanQuota scans the user home dir and virtual folders, included in its quota,
  576. // and returns the number of files and their size
  577. func (u *User) ScanQuota() (int, int64, error) {
  578. fs, err := u.getRootFs("")
  579. if err != nil {
  580. return 0, 0, err
  581. }
  582. defer fs.Close()
  583. numFiles, size, err := fs.ScanRootDirContents()
  584. if err != nil {
  585. return numFiles, size, err
  586. }
  587. for idx := range u.VirtualFolders {
  588. v := &u.VirtualFolders[idx]
  589. if !v.IsIncludedInUserQuota() {
  590. continue
  591. }
  592. num, s, err := v.ScanQuota()
  593. if err != nil {
  594. return numFiles, size, err
  595. }
  596. numFiles += num
  597. size += s
  598. }
  599. return numFiles, size, nil
  600. }
  601. // GetVirtualFoldersInPath returns the virtual folders inside virtualPath including
  602. // any parents
  603. func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool {
  604. result := make(map[string]bool)
  605. for idx := range u.VirtualFolders {
  606. v := &u.VirtualFolders[idx]
  607. dirsForPath := util.GetDirsForVirtualPath(v.VirtualPath)
  608. for index := range dirsForPath {
  609. d := dirsForPath[index]
  610. if d == "/" {
  611. continue
  612. }
  613. if path.Dir(d) == virtualPath {
  614. result[d] = true
  615. }
  616. }
  617. }
  618. if u.Filters.StartDirectory != "" {
  619. dirsForPath := util.GetDirsForVirtualPath(u.Filters.StartDirectory)
  620. for index := range dirsForPath {
  621. d := dirsForPath[index]
  622. if d == "/" {
  623. continue
  624. }
  625. if path.Dir(d) == virtualPath {
  626. result[d] = true
  627. }
  628. }
  629. }
  630. return result
  631. }
  632. func (u *User) hasVirtualDirs() bool {
  633. if u.Filters.StartDirectory != "" {
  634. return true
  635. }
  636. numFolders := len(u.VirtualFolders)
  637. if numFolders == 1 {
  638. return u.VirtualFolders[0].VirtualPath != "/"
  639. }
  640. return numFolders > 0
  641. }
  642. // FilterListDir adds virtual folders and remove hidden items from the given files list
  643. func (u *User) FilterListDir(dirContents []os.FileInfo, virtualPath string) []os.FileInfo {
  644. filter := u.getPatternsFilterForPath(virtualPath)
  645. if !u.hasVirtualDirs() && filter.DenyPolicy != sdk.DenyPolicyHide {
  646. return dirContents
  647. }
  648. vdirs := make(map[string]bool)
  649. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  650. dirName := path.Base(dir)
  651. if filter.DenyPolicy == sdk.DenyPolicyHide {
  652. if !filter.CheckAllowed(dirName) {
  653. continue
  654. }
  655. }
  656. vdirs[dirName] = true
  657. }
  658. validIdx := 0
  659. for index, fi := range dirContents {
  660. for dir := range vdirs {
  661. if fi.Name() == dir {
  662. if !fi.IsDir() {
  663. fi = vfs.NewFileInfo(dir, true, 0, time.Unix(0, 0), false)
  664. dirContents[index] = fi
  665. }
  666. delete(vdirs, dir)
  667. }
  668. }
  669. if filter.DenyPolicy == sdk.DenyPolicyHide {
  670. if filter.CheckAllowed(fi.Name()) {
  671. dirContents[validIdx] = fi
  672. validIdx++
  673. }
  674. }
  675. }
  676. if filter.DenyPolicy == sdk.DenyPolicyHide {
  677. for idx := validIdx; idx < len(dirContents); idx++ {
  678. dirContents[idx] = nil
  679. }
  680. dirContents = dirContents[:validIdx]
  681. }
  682. for dir := range vdirs {
  683. fi := vfs.NewFileInfo(dir, true, 0, time.Unix(0, 0), false)
  684. dirContents = append(dirContents, fi)
  685. }
  686. return dirContents
  687. }
  688. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  689. // The filesystem path must be cleaned before calling this method
  690. func (u *User) IsMappedPath(fsPath string) bool {
  691. for idx := range u.VirtualFolders {
  692. v := &u.VirtualFolders[idx]
  693. if fsPath == v.MappedPath {
  694. return true
  695. }
  696. }
  697. return false
  698. }
  699. // IsVirtualFolder returns true if the specified virtual path is a virtual folder
  700. func (u *User) IsVirtualFolder(virtualPath string) bool {
  701. for idx := range u.VirtualFolders {
  702. v := &u.VirtualFolders[idx]
  703. if virtualPath == v.VirtualPath {
  704. return true
  705. }
  706. }
  707. return false
  708. }
  709. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  710. // specified virtual path. We assume that path are cleaned
  711. func (u *User) HasVirtualFoldersInside(virtualPath string) bool {
  712. if virtualPath == "/" && len(u.VirtualFolders) > 0 {
  713. return true
  714. }
  715. for idx := range u.VirtualFolders {
  716. v := &u.VirtualFolders[idx]
  717. if len(v.VirtualPath) > len(virtualPath) {
  718. if strings.HasPrefix(v.VirtualPath, virtualPath+"/") {
  719. return true
  720. }
  721. }
  722. }
  723. return false
  724. }
  725. // HasPermissionsInside returns true if the specified virtualPath has no permissions itself and
  726. // no subdirs with defined permissions
  727. func (u *User) HasPermissionsInside(virtualPath string) bool {
  728. for dir, perms := range u.Permissions {
  729. if len(perms) == 1 && perms[0] == PermAny {
  730. continue
  731. }
  732. if dir == virtualPath {
  733. return true
  734. } else if len(dir) > len(virtualPath) {
  735. if strings.HasPrefix(dir, virtualPath+"/") {
  736. return true
  737. }
  738. }
  739. }
  740. return false
  741. }
  742. // HasPerm returns true if the user has the given permission or any permission
  743. func (u *User) HasPerm(permission, path string) bool {
  744. perms := u.GetPermissionsForPath(path)
  745. if util.Contains(perms, PermAny) {
  746. return true
  747. }
  748. return util.Contains(perms, permission)
  749. }
  750. // HasAnyPerm returns true if the user has at least one of the given permissions
  751. func (u *User) HasAnyPerm(permissions []string, path string) bool {
  752. perms := u.GetPermissionsForPath(path)
  753. if util.Contains(perms, PermAny) {
  754. return true
  755. }
  756. for _, permission := range permissions {
  757. if util.Contains(perms, permission) {
  758. return true
  759. }
  760. }
  761. return false
  762. }
  763. // HasPerms returns true if the user has all the given permissions
  764. func (u *User) HasPerms(permissions []string, path string) bool {
  765. perms := u.GetPermissionsForPath(path)
  766. if util.Contains(perms, PermAny) {
  767. return true
  768. }
  769. for _, permission := range permissions {
  770. if !util.Contains(perms, permission) {
  771. return false
  772. }
  773. }
  774. return true
  775. }
  776. // HasPermsDeleteAll returns true if the user can delete both files and directories
  777. // for the given path
  778. func (u *User) HasPermsDeleteAll(path string) bool {
  779. perms := u.GetPermissionsForPath(path)
  780. canDeleteFiles := false
  781. canDeleteDirs := false
  782. for _, permission := range perms {
  783. if permission == PermAny || permission == PermDelete {
  784. return true
  785. }
  786. if permission == PermDeleteFiles {
  787. canDeleteFiles = true
  788. }
  789. if permission == PermDeleteDirs {
  790. canDeleteDirs = true
  791. }
  792. }
  793. return canDeleteFiles && canDeleteDirs
  794. }
  795. // HasPermsRenameAll returns true if the user can rename both files and directories
  796. // for the given path
  797. func (u *User) HasPermsRenameAll(path string) bool {
  798. perms := u.GetPermissionsForPath(path)
  799. canRenameFiles := false
  800. canRenameDirs := false
  801. for _, permission := range perms {
  802. if permission == PermAny || permission == PermRename {
  803. return true
  804. }
  805. if permission == PermRenameFiles {
  806. canRenameFiles = true
  807. }
  808. if permission == PermRenameDirs {
  809. canRenameDirs = true
  810. }
  811. }
  812. return canRenameFiles && canRenameDirs
  813. }
  814. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  815. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  816. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  817. return true
  818. }
  819. return false
  820. }
  821. // IsLoginMethodAllowed returns true if the specified login method is allowed
  822. func (u *User) IsLoginMethodAllowed(loginMethod, protocol string, partialSuccessMethods []string) bool {
  823. if len(u.Filters.DeniedLoginMethods) == 0 {
  824. return true
  825. }
  826. if len(partialSuccessMethods) == 1 {
  827. for _, method := range u.GetNextAuthMethods(partialSuccessMethods, true) {
  828. if method == loginMethod {
  829. return true
  830. }
  831. }
  832. }
  833. if util.Contains(u.Filters.DeniedLoginMethods, loginMethod) {
  834. return false
  835. }
  836. if protocol == protocolSSH && loginMethod == LoginMethodPassword {
  837. if util.Contains(u.Filters.DeniedLoginMethods, SSHLoginMethodPassword) {
  838. return false
  839. }
  840. }
  841. return true
  842. }
  843. // GetNextAuthMethods returns the list of authentications methods that
  844. // can continue for multi-step authentication
  845. func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string {
  846. var methods []string
  847. if len(partialSuccessMethods) != 1 {
  848. return methods
  849. }
  850. if partialSuccessMethods[0] != SSHLoginMethodPublicKey {
  851. return methods
  852. }
  853. for _, method := range u.GetAllowedLoginMethods() {
  854. if method == SSHLoginMethodKeyAndPassword && isPasswordAuthEnabled {
  855. methods = append(methods, LoginMethodPassword)
  856. }
  857. if method == SSHLoginMethodKeyAndKeyboardInt {
  858. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  859. }
  860. }
  861. return methods
  862. }
  863. // IsPartialAuth returns true if the specified login method is a step for
  864. // a multi-step Authentication.
  865. // We support publickey+password and publickey+keyboard-interactive, so
  866. // only publickey can returns partial success.
  867. // We can have partial success if only multi-step Auth methods are enabled
  868. func (u *User) IsPartialAuth(loginMethod string) bool {
  869. if loginMethod != SSHLoginMethodPublicKey {
  870. return false
  871. }
  872. for _, method := range u.GetAllowedLoginMethods() {
  873. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd ||
  874. method == SSHLoginMethodPassword {
  875. continue
  876. }
  877. if !util.Contains(SSHMultiStepsLoginMethods, method) {
  878. return false
  879. }
  880. }
  881. return true
  882. }
  883. // GetAllowedLoginMethods returns the allowed login methods
  884. func (u *User) GetAllowedLoginMethods() []string {
  885. var allowedMethods []string
  886. for _, method := range ValidLoginMethods {
  887. if method == SSHLoginMethodPassword {
  888. continue
  889. }
  890. if !util.Contains(u.Filters.DeniedLoginMethods, method) {
  891. allowedMethods = append(allowedMethods, method)
  892. }
  893. }
  894. return allowedMethods
  895. }
  896. func (u *User) getPatternsFilterForPath(virtualPath string) sdk.PatternsFilter {
  897. var filter sdk.PatternsFilter
  898. if len(u.Filters.FilePatterns) == 0 {
  899. return filter
  900. }
  901. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  902. for _, dir := range dirsForPath {
  903. for _, f := range u.Filters.FilePatterns {
  904. if f.Path == dir {
  905. filter = f
  906. break
  907. }
  908. }
  909. if filter.Path != "" {
  910. break
  911. }
  912. }
  913. return filter
  914. }
  915. func (u *User) isDirHidden(virtualPath string) bool {
  916. if len(u.Filters.FilePatterns) == 0 {
  917. return false
  918. }
  919. for _, dirPath := range util.GetDirsForVirtualPath(virtualPath) {
  920. if dirPath == "/" {
  921. return false
  922. }
  923. filter := u.getPatternsFilterForPath(dirPath)
  924. if filter.DenyPolicy == sdk.DenyPolicyHide {
  925. if !filter.CheckAllowed(path.Base(dirPath)) {
  926. return true
  927. }
  928. }
  929. }
  930. return false
  931. }
  932. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters.
  933. // The second parameter returned is the deny policy
  934. func (u *User) IsFileAllowed(virtualPath string) (bool, int) {
  935. dirPath := path.Dir(virtualPath)
  936. if u.isDirHidden(dirPath) {
  937. return false, sdk.DenyPolicyHide
  938. }
  939. filter := u.getPatternsFilterForPath(dirPath)
  940. return filter.CheckAllowed(path.Base(virtualPath)), filter.DenyPolicy
  941. }
  942. // CanManageMFA returns true if the user can add a multi-factor authentication configuration
  943. func (u *User) CanManageMFA() bool {
  944. if util.Contains(u.Filters.WebClient, sdk.WebClientMFADisabled) {
  945. return false
  946. }
  947. return len(mfa.GetAvailableTOTPConfigs()) > 0
  948. }
  949. func (u *User) isExternalAuthCached() bool {
  950. if u.ID <= 0 {
  951. return false
  952. }
  953. if u.Filters.ExternalAuthCacheTime <= 0 {
  954. return false
  955. }
  956. return isLastActivityRecent(u.LastLogin, time.Duration(u.Filters.ExternalAuthCacheTime)*time.Second)
  957. }
  958. // CanManageShares returns true if the user can add, update and list shares
  959. func (u *User) CanManageShares() bool {
  960. return !util.Contains(u.Filters.WebClient, sdk.WebClientSharesDisabled)
  961. }
  962. // CanResetPassword returns true if this user is allowed to reset its password
  963. func (u *User) CanResetPassword() bool {
  964. return !util.Contains(u.Filters.WebClient, sdk.WebClientPasswordResetDisabled)
  965. }
  966. // CanChangePassword returns true if this user is allowed to change its password
  967. func (u *User) CanChangePassword() bool {
  968. return !util.Contains(u.Filters.WebClient, sdk.WebClientPasswordChangeDisabled)
  969. }
  970. // CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
  971. func (u *User) CanChangeAPIKeyAuth() bool {
  972. return !util.Contains(u.Filters.WebClient, sdk.WebClientAPIKeyAuthChangeDisabled)
  973. }
  974. // CanChangeInfo returns true if this user is allowed to change its info such as email and description
  975. func (u *User) CanChangeInfo() bool {
  976. return !util.Contains(u.Filters.WebClient, sdk.WebClientInfoChangeDisabled)
  977. }
  978. // CanManagePublicKeys returns true if this user is allowed to manage public keys
  979. // from the web client. Used in web client UI
  980. func (u *User) CanManagePublicKeys() bool {
  981. return !util.Contains(u.Filters.WebClient, sdk.WebClientPubKeyChangeDisabled)
  982. }
  983. // CanAddFilesFromWeb returns true if the client can add files from the web UI.
  984. // The specified target is the directory where the files must be uploaded
  985. func (u *User) CanAddFilesFromWeb(target string) bool {
  986. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  987. return false
  988. }
  989. return u.HasPerm(PermUpload, target) || u.HasPerm(PermOverwrite, target)
  990. }
  991. // CanAddDirsFromWeb returns true if the client can add directories from the web UI.
  992. // The specified target is the directory where the new directory must be created
  993. func (u *User) CanAddDirsFromWeb(target string) bool {
  994. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  995. return false
  996. }
  997. return u.HasPerm(PermCreateDirs, target)
  998. }
  999. // CanRenameFromWeb returns true if the client can rename objects from the web UI.
  1000. // The specified src and dest are the source and target directories for the rename.
  1001. func (u *User) CanRenameFromWeb(src, dest string) bool {
  1002. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1003. return false
  1004. }
  1005. return u.HasAnyPerm(permsRenameAny, src) && u.HasAnyPerm(permsRenameAny, dest)
  1006. }
  1007. // CanDeleteFromWeb returns true if the client can delete objects from the web UI.
  1008. // The specified target is the parent directory for the object to delete
  1009. func (u *User) CanDeleteFromWeb(target string) bool {
  1010. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1011. return false
  1012. }
  1013. return u.HasAnyPerm(permsDeleteAny, target)
  1014. }
  1015. // MustSetSecondFactor returns true if the user must set a second factor authentication
  1016. func (u *User) MustSetSecondFactor() bool {
  1017. if len(u.Filters.TwoFactorAuthProtocols) > 0 {
  1018. if !u.Filters.TOTPConfig.Enabled {
  1019. return true
  1020. }
  1021. for _, p := range u.Filters.TwoFactorAuthProtocols {
  1022. if !util.Contains(u.Filters.TOTPConfig.Protocols, p) {
  1023. return true
  1024. }
  1025. }
  1026. }
  1027. return false
  1028. }
  1029. // MustSetSecondFactorForProtocol returns true if the user must set a second factor authentication
  1030. // for the specified protocol
  1031. func (u *User) MustSetSecondFactorForProtocol(protocol string) bool {
  1032. if util.Contains(u.Filters.TwoFactorAuthProtocols, protocol) {
  1033. if !u.Filters.TOTPConfig.Enabled {
  1034. return true
  1035. }
  1036. if !util.Contains(u.Filters.TOTPConfig.Protocols, protocol) {
  1037. return true
  1038. }
  1039. }
  1040. return false
  1041. }
  1042. // GetSignature returns a signature for this admin.
  1043. // It could change after an update
  1044. func (u *User) GetSignature() string {
  1045. data := []byte(fmt.Sprintf("%v_%v_%v", u.Username, u.Status, u.ExpirationDate))
  1046. data = append(data, []byte(u.Password)...)
  1047. signature := sha256.Sum256(data)
  1048. return base64.StdEncoding.EncodeToString(signature[:])
  1049. }
  1050. // GetBandwidthForIP returns the upload and download bandwidth for the specified IP
  1051. func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64) {
  1052. if len(u.Filters.BandwidthLimits) > 0 {
  1053. ip := net.ParseIP(clientIP)
  1054. if ip != nil {
  1055. for _, bwLimit := range u.Filters.BandwidthLimits {
  1056. for _, source := range bwLimit.Sources {
  1057. _, ipNet, err := net.ParseCIDR(source)
  1058. if err == nil {
  1059. if ipNet.Contains(ip) {
  1060. logger.Debug(logSender, connectionID, "override bandwidth limit for ip %#v, upload limit: %v KB/s, download limit: %v KB/s",
  1061. clientIP, bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth)
  1062. return bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. return u.UploadBandwidth, u.DownloadBandwidth
  1070. }
  1071. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  1072. // If AllowedIP is defined only the specified IP/Mask can login.
  1073. // If DeniedIP is defined the specified IP/Mask cannot login.
  1074. // If an IP is both allowed and denied then login will be allowed
  1075. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  1076. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  1077. return true
  1078. }
  1079. remoteIP := net.ParseIP(util.GetIPFromRemoteAddress(remoteAddr))
  1080. // if remoteIP is invalid we allow login, this should never happen
  1081. if remoteIP == nil {
  1082. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %#v", remoteAddr)
  1083. return true
  1084. }
  1085. for _, IPMask := range u.Filters.AllowedIP {
  1086. _, IPNet, err := net.ParseCIDR(IPMask)
  1087. if err != nil {
  1088. return false
  1089. }
  1090. if IPNet.Contains(remoteIP) {
  1091. return true
  1092. }
  1093. }
  1094. for _, IPMask := range u.Filters.DeniedIP {
  1095. _, IPNet, err := net.ParseCIDR(IPMask)
  1096. if err != nil {
  1097. return false
  1098. }
  1099. if IPNet.Contains(remoteIP) {
  1100. return false
  1101. }
  1102. }
  1103. return len(u.Filters.AllowedIP) == 0
  1104. }
  1105. // GetPermissionsAsJSON returns the permissions as json byte array
  1106. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  1107. return json.Marshal(u.Permissions)
  1108. }
  1109. // GetPublicKeysAsJSON returns the public keys as json byte array
  1110. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  1111. return json.Marshal(u.PublicKeys)
  1112. }
  1113. // GetFiltersAsJSON returns the filters as json byte array
  1114. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  1115. return json.Marshal(u.Filters)
  1116. }
  1117. // GetFsConfigAsJSON returns the filesystem config as json byte array
  1118. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  1119. return json.Marshal(u.FsConfig)
  1120. }
  1121. // GetUID returns a validate uid, suitable for use with os.Chown
  1122. func (u *User) GetUID() int {
  1123. if u.UID <= 0 || u.UID > math.MaxInt32 {
  1124. return -1
  1125. }
  1126. return u.UID
  1127. }
  1128. // GetGID returns a validate gid, suitable for use with os.Chown
  1129. func (u *User) GetGID() int {
  1130. if u.GID <= 0 || u.GID > math.MaxInt32 {
  1131. return -1
  1132. }
  1133. return u.GID
  1134. }
  1135. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  1136. func (u *User) GetHomeDir() string {
  1137. return u.HomeDir
  1138. }
  1139. // HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
  1140. func (u *User) HasRecentActivity() bool {
  1141. return isLastActivityRecent(u.LastLogin, lastLoginMinDelay)
  1142. }
  1143. // HasQuotaRestrictions returns true if there are any disk quota restrictions
  1144. func (u *User) HasQuotaRestrictions() bool {
  1145. return u.QuotaFiles > 0 || u.QuotaSize > 0
  1146. }
  1147. // HasTransferQuotaRestrictions returns true if there are any data transfer restrictions
  1148. func (u *User) HasTransferQuotaRestrictions() bool {
  1149. if len(u.Filters.DataTransferLimits) > 0 {
  1150. return true
  1151. }
  1152. return u.UploadDataTransfer > 0 || u.TotalDataTransfer > 0 || u.DownloadDataTransfer > 0
  1153. }
  1154. // GetDataTransferLimits returns upload, download and total data transfer limits
  1155. func (u *User) GetDataTransferLimits(clientIP string) (int64, int64, int64) {
  1156. var total, ul, dl int64
  1157. if len(u.Filters.DataTransferLimits) > 0 {
  1158. ip := net.ParseIP(clientIP)
  1159. if ip != nil {
  1160. for _, limit := range u.Filters.DataTransferLimits {
  1161. for _, source := range limit.Sources {
  1162. _, ipNet, err := net.ParseCIDR(source)
  1163. if err == nil {
  1164. if ipNet.Contains(ip) {
  1165. if limit.TotalDataTransfer > 0 {
  1166. total = limit.TotalDataTransfer * 1048576
  1167. }
  1168. if limit.DownloadDataTransfer > 0 {
  1169. dl = limit.DownloadDataTransfer * 1048576
  1170. }
  1171. if limit.UploadDataTransfer > 0 {
  1172. ul = limit.UploadDataTransfer * 1048576
  1173. }
  1174. return ul, dl, total
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }
  1180. }
  1181. if u.TotalDataTransfer > 0 {
  1182. total = u.TotalDataTransfer * 1048576
  1183. }
  1184. if u.DownloadDataTransfer > 0 {
  1185. dl = u.DownloadDataTransfer * 1048576
  1186. }
  1187. if u.UploadDataTransfer > 0 {
  1188. ul = u.UploadDataTransfer * 1048576
  1189. }
  1190. return ul, dl, total
  1191. }
  1192. // GetQuotaSummary returns used quota and limits if defined
  1193. func (u *User) GetQuotaSummary() string {
  1194. var sb strings.Builder
  1195. addSection := func() {
  1196. if sb.Len() > 0 {
  1197. sb.WriteString(". ")
  1198. }
  1199. }
  1200. if u.UsedQuotaFiles > 0 || u.QuotaFiles > 0 {
  1201. sb.WriteString(fmt.Sprintf("Files: %v", u.UsedQuotaFiles))
  1202. if u.QuotaFiles > 0 {
  1203. sb.WriteString(fmt.Sprintf("/%v", u.QuotaFiles))
  1204. }
  1205. }
  1206. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  1207. addSection()
  1208. sb.WriteString(fmt.Sprintf("Size: %v", util.ByteCountIEC(u.UsedQuotaSize)))
  1209. if u.QuotaSize > 0 {
  1210. sb.WriteString(fmt.Sprintf("/%v", util.ByteCountIEC(u.QuotaSize)))
  1211. }
  1212. }
  1213. if u.TotalDataTransfer > 0 {
  1214. addSection()
  1215. total := u.UsedDownloadDataTransfer + u.UsedUploadDataTransfer
  1216. sb.WriteString(fmt.Sprintf("Transfer: %v/%v", util.ByteCountIEC(total),
  1217. util.ByteCountIEC(u.TotalDataTransfer*1048576)))
  1218. }
  1219. if u.UploadDataTransfer > 0 {
  1220. addSection()
  1221. sb.WriteString(fmt.Sprintf("UL: %v/%v", util.ByteCountIEC(u.UsedUploadDataTransfer),
  1222. util.ByteCountIEC(u.UploadDataTransfer*1048576)))
  1223. }
  1224. if u.DownloadDataTransfer > 0 {
  1225. addSection()
  1226. sb.WriteString(fmt.Sprintf("DL: %v/%v", util.ByteCountIEC(u.UsedDownloadDataTransfer),
  1227. util.ByteCountIEC(u.DownloadDataTransfer*1048576)))
  1228. }
  1229. return sb.String()
  1230. }
  1231. // GetPermissionsAsString returns the user's permissions as comma separated string
  1232. func (u *User) GetPermissionsAsString() string {
  1233. result := ""
  1234. for dir, perms := range u.Permissions {
  1235. dirPerms := strings.Join(perms, ", ")
  1236. dp := fmt.Sprintf("%#v: %#v", dir, dirPerms)
  1237. if dir == "/" {
  1238. if result != "" {
  1239. result = dp + ", " + result
  1240. } else {
  1241. result = dp
  1242. }
  1243. } else {
  1244. if result != "" {
  1245. result += ", "
  1246. }
  1247. result += dp
  1248. }
  1249. }
  1250. return result
  1251. }
  1252. // GetBandwidthAsString returns bandwidth limits if defines
  1253. func (u *User) GetBandwidthAsString() string {
  1254. var sb strings.Builder
  1255. sb.WriteString("DL: ")
  1256. if u.DownloadBandwidth > 0 {
  1257. sb.WriteString(util.ByteCountIEC(u.DownloadBandwidth*1000) + "/s.")
  1258. } else {
  1259. sb.WriteString("unlimited.")
  1260. }
  1261. sb.WriteString(" UL: ")
  1262. if u.UploadBandwidth > 0 {
  1263. sb.WriteString(util.ByteCountIEC(u.UploadBandwidth*1000) + "/s.")
  1264. } else {
  1265. sb.WriteString("unlimited.")
  1266. }
  1267. return sb.String()
  1268. }
  1269. // GetMFAStatusAsString returns MFA status
  1270. func (u *User) GetMFAStatusAsString() string {
  1271. if u.Filters.TOTPConfig.Enabled {
  1272. return strings.Join(u.Filters.TOTPConfig.Protocols, ", ")
  1273. }
  1274. return "Disabled"
  1275. }
  1276. // GetLastLoginAsString returns the last login as string
  1277. func (u *User) GetLastLoginAsString() string {
  1278. if u.LastLogin > 0 {
  1279. return util.GetTimeFromMsecSinceEpoch(u.LastLogin).UTC().Format(iso8601UTCFormat)
  1280. }
  1281. return ""
  1282. }
  1283. // GetLastQuotaUpdateAsString returns the last quota update as string
  1284. func (u *User) GetLastQuotaUpdateAsString() string {
  1285. if u.LastQuotaUpdate > 0 {
  1286. return util.GetTimeFromMsecSinceEpoch(u.LastQuotaUpdate).UTC().Format(iso8601UTCFormat)
  1287. }
  1288. return ""
  1289. }
  1290. // GetStorageDescrition returns the storage description
  1291. func (u *User) GetStorageDescrition() string {
  1292. switch u.FsConfig.Provider {
  1293. case sdk.LocalFilesystemProvider:
  1294. return fmt.Sprintf("Local: %v", u.GetHomeDir())
  1295. case sdk.S3FilesystemProvider:
  1296. return fmt.Sprintf("S3: %v", u.FsConfig.S3Config.Bucket)
  1297. case sdk.GCSFilesystemProvider:
  1298. return fmt.Sprintf("GCS: %v", u.FsConfig.GCSConfig.Bucket)
  1299. case sdk.AzureBlobFilesystemProvider:
  1300. return fmt.Sprintf("AzBlob: %v", u.FsConfig.AzBlobConfig.Container)
  1301. case sdk.CryptedFilesystemProvider:
  1302. return fmt.Sprintf("Encrypted: %v", u.GetHomeDir())
  1303. case sdk.SFTPFilesystemProvider:
  1304. return fmt.Sprintf("SFTP: %v", u.FsConfig.SFTPConfig.Endpoint)
  1305. case sdk.HTTPFilesystemProvider:
  1306. return fmt.Sprintf("HTTP: %v", u.FsConfig.HTTPConfig.Endpoint)
  1307. default:
  1308. return ""
  1309. }
  1310. }
  1311. // GetGroupsAsString returns the user's groups as a string
  1312. func (u *User) GetGroupsAsString() string {
  1313. if len(u.Groups) == 0 {
  1314. return ""
  1315. }
  1316. var groups []string
  1317. for _, g := range u.Groups {
  1318. if g.Type == sdk.GroupTypePrimary {
  1319. groups = append(groups, "")
  1320. copy(groups[1:], groups)
  1321. groups[0] = g.Name
  1322. } else {
  1323. groups = append(groups, g.Name)
  1324. }
  1325. }
  1326. return strings.Join(groups, ",")
  1327. }
  1328. // GetInfoString returns user's info as string.
  1329. // Storage provider, number of public keys, max sessions, uid,
  1330. // gid, denied and allowed IP/Mask are returned
  1331. func (u *User) GetInfoString() string {
  1332. var result strings.Builder
  1333. if len(u.PublicKeys) > 0 {
  1334. result.WriteString(fmt.Sprintf("Public keys: %v. ", len(u.PublicKeys)))
  1335. }
  1336. if u.MaxSessions > 0 {
  1337. result.WriteString(fmt.Sprintf("Max sessions: %v. ", u.MaxSessions))
  1338. }
  1339. if u.UID > 0 {
  1340. result.WriteString(fmt.Sprintf("UID: %v. ", u.UID))
  1341. }
  1342. if u.GID > 0 {
  1343. result.WriteString(fmt.Sprintf("GID: %v. ", u.GID))
  1344. }
  1345. if len(u.Filters.DeniedLoginMethods) > 0 {
  1346. result.WriteString(fmt.Sprintf("Denied login methods: %v. ", strings.Join(u.Filters.DeniedLoginMethods, ",")))
  1347. }
  1348. if len(u.Filters.DeniedProtocols) > 0 {
  1349. result.WriteString(fmt.Sprintf("Denied protocols: %v. ", strings.Join(u.Filters.DeniedProtocols, ",")))
  1350. }
  1351. if len(u.Filters.DeniedIP) > 0 {
  1352. result.WriteString(fmt.Sprintf("Denied IP/Mask: %v. ", len(u.Filters.DeniedIP)))
  1353. }
  1354. if len(u.Filters.AllowedIP) > 0 {
  1355. result.WriteString(fmt.Sprintf("Allowed IP/Mask: %v", len(u.Filters.AllowedIP)))
  1356. }
  1357. return result.String()
  1358. }
  1359. // GetStatusAsString returns the user status as a string
  1360. func (u *User) GetStatusAsString() string {
  1361. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  1362. return "Expired"
  1363. }
  1364. if u.Status == 1 {
  1365. return "Active"
  1366. }
  1367. return "Inactive"
  1368. }
  1369. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  1370. func (u *User) GetExpirationDateAsString() string {
  1371. if u.ExpirationDate > 0 {
  1372. t := util.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  1373. return t.Format("2006-01-02")
  1374. }
  1375. return ""
  1376. }
  1377. // GetAllowedIPAsString returns the allowed IP as comma separated string
  1378. func (u *User) GetAllowedIPAsString() string {
  1379. return strings.Join(u.Filters.AllowedIP, ",")
  1380. }
  1381. // GetDeniedIPAsString returns the denied IP as comma separated string
  1382. func (u *User) GetDeniedIPAsString() string {
  1383. return strings.Join(u.Filters.DeniedIP, ",")
  1384. }
  1385. // HasExternalAuth returns true if the external authentication is globally enabled
  1386. // and it is not disabled for this user
  1387. func (u *User) HasExternalAuth() bool {
  1388. if u.Filters.Hooks.ExternalAuthDisabled {
  1389. return false
  1390. }
  1391. if config.ExternalAuthHook != "" {
  1392. return true
  1393. }
  1394. return plugin.Handler.HasAuthenticators()
  1395. }
  1396. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  1397. func (u *User) CountUnusedRecoveryCodes() int {
  1398. unused := 0
  1399. for _, code := range u.Filters.RecoveryCodes {
  1400. if !code.Used {
  1401. unused++
  1402. }
  1403. }
  1404. return unused
  1405. }
  1406. // SetEmptySecretsIfNil sets the secrets to empty if nil
  1407. func (u *User) SetEmptySecretsIfNil() {
  1408. u.FsConfig.SetEmptySecretsIfNil()
  1409. for idx := range u.VirtualFolders {
  1410. vfolder := &u.VirtualFolders[idx]
  1411. vfolder.FsConfig.SetEmptySecretsIfNil()
  1412. }
  1413. if u.Filters.TOTPConfig.Secret == nil {
  1414. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  1415. }
  1416. }
  1417. func (u *User) hasMainDataTransferLimits() bool {
  1418. return u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 || u.TotalDataTransfer > 0
  1419. }
  1420. // HasPrimaryGroup returns true if the user has the specified primary group
  1421. func (u *User) HasPrimaryGroup(name string) bool {
  1422. for _, g := range u.Groups {
  1423. if g.Name == name {
  1424. return g.Type == sdk.GroupTypePrimary
  1425. }
  1426. }
  1427. return false
  1428. }
  1429. // HasSecondaryGroup returns true if the user has the specified secondary group
  1430. func (u *User) HasSecondaryGroup(name string) bool {
  1431. for _, g := range u.Groups {
  1432. if g.Name == name {
  1433. return g.Type == sdk.GroupTypeSecondary
  1434. }
  1435. }
  1436. return false
  1437. }
  1438. // HasMembershipGroup returns true if the user has the specified membership group
  1439. func (u *User) HasMembershipGroup(name string) bool {
  1440. for _, g := range u.Groups {
  1441. if g.Name == name {
  1442. return g.Type == sdk.GroupTypeMembership
  1443. }
  1444. }
  1445. return false
  1446. }
  1447. func (u *User) hasSettingsFromGroups() bool {
  1448. for _, g := range u.Groups {
  1449. if g.Type != sdk.GroupTypeMembership {
  1450. return true
  1451. }
  1452. }
  1453. return false
  1454. }
  1455. func (u *User) applyGroupSettings(groupsMapping map[string]Group) {
  1456. if !u.hasSettingsFromGroups() {
  1457. return
  1458. }
  1459. if u.groupSettingsApplied {
  1460. return
  1461. }
  1462. replacer := u.getGroupPlacehodersReplacer()
  1463. for _, g := range u.Groups {
  1464. if g.Type == sdk.GroupTypePrimary {
  1465. if group, ok := groupsMapping[g.Name]; ok {
  1466. u.mergeWithPrimaryGroup(group, replacer)
  1467. } else {
  1468. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1469. }
  1470. break
  1471. }
  1472. }
  1473. for _, g := range u.Groups {
  1474. if g.Type == sdk.GroupTypeSecondary {
  1475. if group, ok := groupsMapping[g.Name]; ok {
  1476. u.mergeAdditiveProperties(group, sdk.GroupTypeSecondary, replacer)
  1477. } else {
  1478. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1479. }
  1480. }
  1481. }
  1482. u.removeDuplicatesAfterGroupMerge()
  1483. }
  1484. // LoadAndApplyGroupSettings update the user by loading and applying the group settings
  1485. func (u *User) LoadAndApplyGroupSettings() error {
  1486. if !u.hasSettingsFromGroups() {
  1487. return nil
  1488. }
  1489. if u.groupSettingsApplied {
  1490. return nil
  1491. }
  1492. names := make([]string, 0, len(u.Groups))
  1493. var primaryGroupName string
  1494. for _, g := range u.Groups {
  1495. if g.Type == sdk.GroupTypePrimary {
  1496. primaryGroupName = g.Name
  1497. }
  1498. if g.Type != sdk.GroupTypeMembership {
  1499. names = append(names, g.Name)
  1500. }
  1501. }
  1502. groups, err := provider.getGroupsWithNames(names)
  1503. if err != nil {
  1504. return fmt.Errorf("unable to get groups: %w", err)
  1505. }
  1506. replacer := u.getGroupPlacehodersReplacer()
  1507. // make sure to always merge with the primary group first
  1508. for idx, g := range groups {
  1509. if g.Name == primaryGroupName {
  1510. u.mergeWithPrimaryGroup(g, replacer)
  1511. lastIdx := len(groups) - 1
  1512. groups[idx] = groups[lastIdx]
  1513. groups = groups[:lastIdx]
  1514. break
  1515. }
  1516. }
  1517. for _, g := range groups {
  1518. u.mergeAdditiveProperties(g, sdk.GroupTypeSecondary, replacer)
  1519. }
  1520. u.removeDuplicatesAfterGroupMerge()
  1521. return nil
  1522. }
  1523. func (u *User) getGroupPlacehodersReplacer() *strings.Replacer {
  1524. return strings.NewReplacer("%username%", u.Username)
  1525. }
  1526. func (u *User) replacePlaceholder(value string, replacer *strings.Replacer) string {
  1527. if value == "" {
  1528. return value
  1529. }
  1530. return replacer.Replace(value)
  1531. }
  1532. func (u *User) replaceFsConfigPlaceholders(fsConfig vfs.Filesystem, replacer *strings.Replacer) vfs.Filesystem {
  1533. switch fsConfig.Provider {
  1534. case sdk.S3FilesystemProvider:
  1535. fsConfig.S3Config.KeyPrefix = u.replacePlaceholder(fsConfig.S3Config.KeyPrefix, replacer)
  1536. case sdk.GCSFilesystemProvider:
  1537. fsConfig.GCSConfig.KeyPrefix = u.replacePlaceholder(fsConfig.GCSConfig.KeyPrefix, replacer)
  1538. case sdk.AzureBlobFilesystemProvider:
  1539. fsConfig.AzBlobConfig.KeyPrefix = u.replacePlaceholder(fsConfig.AzBlobConfig.KeyPrefix, replacer)
  1540. case sdk.SFTPFilesystemProvider:
  1541. fsConfig.SFTPConfig.Username = u.replacePlaceholder(fsConfig.SFTPConfig.Username, replacer)
  1542. fsConfig.SFTPConfig.Prefix = u.replacePlaceholder(fsConfig.SFTPConfig.Prefix, replacer)
  1543. case sdk.HTTPFilesystemProvider:
  1544. fsConfig.HTTPConfig.Username = u.replacePlaceholder(fsConfig.HTTPConfig.Username, replacer)
  1545. }
  1546. return fsConfig
  1547. }
  1548. func (u *User) mergeWithPrimaryGroup(group Group, replacer *strings.Replacer) {
  1549. if group.UserSettings.HomeDir != "" {
  1550. u.HomeDir = u.replacePlaceholder(group.UserSettings.HomeDir, replacer)
  1551. }
  1552. if group.UserSettings.FsConfig.Provider != 0 {
  1553. u.FsConfig = u.replaceFsConfigPlaceholders(group.UserSettings.FsConfig, replacer)
  1554. }
  1555. if u.MaxSessions == 0 {
  1556. u.MaxSessions = group.UserSettings.MaxSessions
  1557. }
  1558. if u.QuotaSize == 0 {
  1559. u.QuotaSize = group.UserSettings.QuotaSize
  1560. }
  1561. if u.QuotaFiles == 0 {
  1562. u.QuotaFiles = group.UserSettings.QuotaFiles
  1563. }
  1564. if u.UploadBandwidth == 0 {
  1565. u.UploadBandwidth = group.UserSettings.UploadBandwidth
  1566. }
  1567. if u.DownloadBandwidth == 0 {
  1568. u.DownloadBandwidth = group.UserSettings.DownloadBandwidth
  1569. }
  1570. if !u.hasMainDataTransferLimits() {
  1571. u.UploadDataTransfer = group.UserSettings.UploadDataTransfer
  1572. u.DownloadDataTransfer = group.UserSettings.DownloadDataTransfer
  1573. u.TotalDataTransfer = group.UserSettings.TotalDataTransfer
  1574. }
  1575. u.mergePrimaryGroupFilters(group.UserSettings.Filters, replacer)
  1576. u.mergeAdditiveProperties(group, sdk.GroupTypePrimary, replacer)
  1577. }
  1578. func (u *User) mergePrimaryGroupFilters(filters sdk.BaseUserFilters, replacer *strings.Replacer) {
  1579. if u.Filters.MaxUploadFileSize == 0 {
  1580. u.Filters.MaxUploadFileSize = filters.MaxUploadFileSize
  1581. }
  1582. if u.Filters.TLSUsername == "" || u.Filters.TLSUsername == sdk.TLSUsernameNone {
  1583. u.Filters.TLSUsername = filters.TLSUsername
  1584. }
  1585. if !u.Filters.Hooks.CheckPasswordDisabled {
  1586. u.Filters.Hooks.CheckPasswordDisabled = filters.Hooks.CheckPasswordDisabled
  1587. }
  1588. if !u.Filters.Hooks.PreLoginDisabled {
  1589. u.Filters.Hooks.PreLoginDisabled = filters.Hooks.PreLoginDisabled
  1590. }
  1591. if !u.Filters.Hooks.ExternalAuthDisabled {
  1592. u.Filters.Hooks.ExternalAuthDisabled = filters.Hooks.ExternalAuthDisabled
  1593. }
  1594. if !u.Filters.DisableFsChecks {
  1595. u.Filters.DisableFsChecks = filters.DisableFsChecks
  1596. }
  1597. if !u.Filters.AllowAPIKeyAuth {
  1598. u.Filters.AllowAPIKeyAuth = filters.AllowAPIKeyAuth
  1599. }
  1600. if !u.Filters.IsAnonymous {
  1601. u.Filters.IsAnonymous = filters.IsAnonymous
  1602. }
  1603. if u.Filters.ExternalAuthCacheTime == 0 {
  1604. u.Filters.ExternalAuthCacheTime = filters.ExternalAuthCacheTime
  1605. }
  1606. if u.Filters.FTPSecurity == 0 {
  1607. u.Filters.FTPSecurity = filters.FTPSecurity
  1608. }
  1609. if u.Filters.StartDirectory == "" {
  1610. u.Filters.StartDirectory = u.replacePlaceholder(filters.StartDirectory, replacer)
  1611. }
  1612. if u.Filters.DefaultSharesExpiration == 0 {
  1613. u.Filters.DefaultSharesExpiration = filters.DefaultSharesExpiration
  1614. }
  1615. }
  1616. func (u *User) mergeAdditiveProperties(group Group, groupType int, replacer *strings.Replacer) {
  1617. u.mergeVirtualFolders(group, groupType, replacer)
  1618. u.mergePermissions(group, groupType, replacer)
  1619. u.mergeFilePatterns(group, groupType, replacer)
  1620. u.Filters.BandwidthLimits = append(u.Filters.BandwidthLimits, group.UserSettings.Filters.BandwidthLimits...)
  1621. u.Filters.DataTransferLimits = append(u.Filters.DataTransferLimits, group.UserSettings.Filters.DataTransferLimits...)
  1622. u.Filters.AllowedIP = append(u.Filters.AllowedIP, group.UserSettings.Filters.AllowedIP...)
  1623. u.Filters.DeniedIP = append(u.Filters.DeniedIP, group.UserSettings.Filters.DeniedIP...)
  1624. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, group.UserSettings.Filters.DeniedLoginMethods...)
  1625. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, group.UserSettings.Filters.DeniedProtocols...)
  1626. u.Filters.WebClient = append(u.Filters.WebClient, group.UserSettings.Filters.WebClient...)
  1627. u.Filters.TwoFactorAuthProtocols = append(u.Filters.TwoFactorAuthProtocols, group.UserSettings.Filters.TwoFactorAuthProtocols...)
  1628. }
  1629. func (u *User) mergeVirtualFolders(group Group, groupType int, replacer *strings.Replacer) {
  1630. if len(group.VirtualFolders) > 0 {
  1631. folderPaths := make(map[string]bool)
  1632. for _, folder := range u.VirtualFolders {
  1633. folderPaths[folder.VirtualPath] = true
  1634. }
  1635. for _, folder := range group.VirtualFolders {
  1636. if folder.VirtualPath == "/" && groupType != sdk.GroupTypePrimary {
  1637. continue
  1638. }
  1639. folder.VirtualPath = u.replacePlaceholder(folder.VirtualPath, replacer)
  1640. if _, ok := folderPaths[folder.VirtualPath]; !ok {
  1641. folder.MappedPath = u.replacePlaceholder(folder.MappedPath, replacer)
  1642. folder.FsConfig = u.replaceFsConfigPlaceholders(folder.FsConfig, replacer)
  1643. u.VirtualFolders = append(u.VirtualFolders, folder)
  1644. }
  1645. }
  1646. }
  1647. }
  1648. func (u *User) mergePermissions(group Group, groupType int, replacer *strings.Replacer) {
  1649. for k, v := range group.UserSettings.Permissions {
  1650. if k == "/" {
  1651. if groupType == sdk.GroupTypePrimary {
  1652. u.Permissions[k] = v
  1653. } else {
  1654. continue
  1655. }
  1656. }
  1657. k = u.replacePlaceholder(k, replacer)
  1658. if _, ok := u.Permissions[k]; !ok {
  1659. u.Permissions[k] = v
  1660. }
  1661. }
  1662. }
  1663. func (u *User) mergeFilePatterns(group Group, groupType int, replacer *strings.Replacer) {
  1664. if len(group.UserSettings.Filters.FilePatterns) > 0 {
  1665. patternPaths := make(map[string]bool)
  1666. for _, pattern := range u.Filters.FilePatterns {
  1667. patternPaths[pattern.Path] = true
  1668. }
  1669. for _, pattern := range group.UserSettings.Filters.FilePatterns {
  1670. if pattern.Path == "/" && groupType != sdk.GroupTypePrimary {
  1671. continue
  1672. }
  1673. pattern.Path = u.replacePlaceholder(pattern.Path, replacer)
  1674. if _, ok := patternPaths[pattern.Path]; !ok {
  1675. u.Filters.FilePatterns = append(u.Filters.FilePatterns, pattern)
  1676. }
  1677. }
  1678. }
  1679. }
  1680. func (u *User) removeDuplicatesAfterGroupMerge() {
  1681. u.Filters.AllowedIP = util.RemoveDuplicates(u.Filters.AllowedIP, false)
  1682. u.Filters.DeniedIP = util.RemoveDuplicates(u.Filters.DeniedIP, false)
  1683. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  1684. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  1685. u.Filters.WebClient = util.RemoveDuplicates(u.Filters.WebClient, false)
  1686. u.Filters.TwoFactorAuthProtocols = util.RemoveDuplicates(u.Filters.TwoFactorAuthProtocols, false)
  1687. u.SetEmptySecretsIfNil()
  1688. u.groupSettingsApplied = true
  1689. }
  1690. func (u *User) getACopy() User {
  1691. u.SetEmptySecretsIfNil()
  1692. pubKeys := make([]string, len(u.PublicKeys))
  1693. copy(pubKeys, u.PublicKeys)
  1694. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  1695. for idx := range u.VirtualFolders {
  1696. vfolder := u.VirtualFolders[idx].GetACopy()
  1697. virtualFolders = append(virtualFolders, vfolder)
  1698. }
  1699. groups := make([]sdk.GroupMapping, 0, len(u.Groups))
  1700. for _, g := range u.Groups {
  1701. groups = append(groups, sdk.GroupMapping{
  1702. Name: g.Name,
  1703. Type: g.Type,
  1704. })
  1705. }
  1706. permissions := make(map[string][]string)
  1707. for k, v := range u.Permissions {
  1708. perms := make([]string, len(v))
  1709. copy(perms, v)
  1710. permissions[k] = perms
  1711. }
  1712. filters := UserFilters{
  1713. BaseUserFilters: copyBaseUserFilters(u.Filters.BaseUserFilters),
  1714. }
  1715. filters.TOTPConfig.Enabled = u.Filters.TOTPConfig.Enabled
  1716. filters.TOTPConfig.ConfigName = u.Filters.TOTPConfig.ConfigName
  1717. filters.TOTPConfig.Secret = u.Filters.TOTPConfig.Secret.Clone()
  1718. filters.TOTPConfig.Protocols = make([]string, len(u.Filters.TOTPConfig.Protocols))
  1719. copy(filters.TOTPConfig.Protocols, u.Filters.TOTPConfig.Protocols)
  1720. filters.RecoveryCodes = make([]RecoveryCode, 0, len(u.Filters.RecoveryCodes))
  1721. for _, code := range u.Filters.RecoveryCodes {
  1722. if code.Secret == nil {
  1723. code.Secret = kms.NewEmptySecret()
  1724. }
  1725. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  1726. Secret: code.Secret.Clone(),
  1727. Used: code.Used,
  1728. })
  1729. }
  1730. return User{
  1731. BaseUser: sdk.BaseUser{
  1732. ID: u.ID,
  1733. Username: u.Username,
  1734. Email: u.Email,
  1735. Password: u.Password,
  1736. PublicKeys: pubKeys,
  1737. HomeDir: u.HomeDir,
  1738. UID: u.UID,
  1739. GID: u.GID,
  1740. MaxSessions: u.MaxSessions,
  1741. QuotaSize: u.QuotaSize,
  1742. QuotaFiles: u.QuotaFiles,
  1743. Permissions: permissions,
  1744. UsedQuotaSize: u.UsedQuotaSize,
  1745. UsedQuotaFiles: u.UsedQuotaFiles,
  1746. LastQuotaUpdate: u.LastQuotaUpdate,
  1747. UploadBandwidth: u.UploadBandwidth,
  1748. DownloadBandwidth: u.DownloadBandwidth,
  1749. UploadDataTransfer: u.UploadDataTransfer,
  1750. DownloadDataTransfer: u.DownloadDataTransfer,
  1751. TotalDataTransfer: u.TotalDataTransfer,
  1752. UsedUploadDataTransfer: u.UsedUploadDataTransfer,
  1753. UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
  1754. Status: u.Status,
  1755. ExpirationDate: u.ExpirationDate,
  1756. LastLogin: u.LastLogin,
  1757. FirstDownload: u.FirstDownload,
  1758. FirstUpload: u.FirstUpload,
  1759. AdditionalInfo: u.AdditionalInfo,
  1760. Description: u.Description,
  1761. CreatedAt: u.CreatedAt,
  1762. UpdatedAt: u.UpdatedAt,
  1763. },
  1764. Filters: filters,
  1765. VirtualFolders: virtualFolders,
  1766. Groups: groups,
  1767. FsConfig: u.FsConfig.GetACopy(),
  1768. groupSettingsApplied: u.groupSettingsApplied,
  1769. }
  1770. }
  1771. // GetEncryptionAdditionalData returns the additional data to use for AEAD
  1772. func (u *User) GetEncryptionAdditionalData() string {
  1773. return u.Username
  1774. }